Repository navigation
Effect persistence layer - #83
juliusmarminge wants to merge 22 commits into
Conversation
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
Co-authored-by: Julius Marminge <juliusmarminge@users.noreply.github.com>
|
Cursor Agent can help with this pull request. Just |
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
Adopt an Effect-based SQLite persistence layer for server state and route all CRUD and event flow through
|
| import path from "node:path"; | ||
|
|
||
| export function normalizeCwd(rawCwd: string): string { | ||
| const resolved = path.resolve(rawCwd.trim()); |
There was a problem hiding this comment.
🟡 Medium
domain/projects.ts:5 On POSIX, directory names can contain leading/trailing whitespace (e.g., "repo "), so .trim() may corrupt valid paths. If this is intentional input sanitization, consider documenting that assumption; otherwise, consider removing .trim().
| const resolved = path.resolve(rawCwd.trim()); | |
| const resolved = path.resolve(rawCwd); |
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/domain/projects.ts around line 5:
On POSIX, directory names can contain leading/trailing whitespace (e.g., `"repo "`), so `.trim()` may corrupt valid paths. If this is intentional input sanitization, consider documenting that assumption; otherwise, consider removing `.trim()`.
Evidence trail:
apps/server/src/persistence/domain/projects.ts line 5 at commit 40f9885dceed14d5af286fb33d23b48e7fd3e974 shows: `const resolved = path.resolve(rawCwd.trim());` - confirming `.trim()` is called on the path input. POSIX filesystem specification allows whitespace characters in filenames/directory names.
| return [...new Set(runningTerminalIds)] | ||
| .map((id) => id.trim()) | ||
| .filter((id) => id.length > 0 && validTerminalIds.has(id)) |
There was a problem hiding this comment.
🟡 Medium
domain/threads.ts:25 Deduplication via Set happens before trim(), so "a" and " a" both survive deduplication and become duplicate "a" entries after trimming. Consider trimming before deduplicating, similar to normalizeTerminalIds.
| return [...new Set(runningTerminalIds)] | |
| .map((id) => id.trim()) | |
| .filter((id) => id.length > 0 && validTerminalIds.has(id)) | |
| return [...new Set(runningTerminalIds.map((id) => id.trim()).filter((id) => id.length > 0))] | |
| .filter((id) => validTerminalIds.has(id)) |
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/domain/threads.ts around lines 25-27:
Deduplication via `Set` happens before `trim()`, so `"a"` and `" a"` both survive deduplication and become duplicate `"a"` entries after trimming. Consider trimming before deduplicating, similar to `normalizeTerminalIds`.
Evidence trail:
apps/server/src/persistence/domain/threads.ts lines 24-28 (commit 40f9885): `return [...new Set(runningTerminalIds)].map((id) => id.trim())...` shows Set deduplication before trim().
apps/server/src/persistence/domain/threads.ts lines 7-8 (commit 40f9885): `...new Set(ids.map((id) => id.trim()).filter...)` shows normalizeTerminalIds correctly trims before deduplicating.
| private readonly sessionThreadIds = new Map<string, string>(); | ||
| private readonly runtimeThreadIds = new Map<string, string>(); | ||
| private readonly stateEventsQueue = Effect.runSync(Queue.unbounded<StateEvent>()); | ||
| private readonly stateEventsBridge = Effect.runFork(this.runStateEventsBridge()); |
There was a problem hiding this comment.
🟡 Medium
src/persistenceService.ts:195 The stateEventsBridge fiber is started in a field initializer before the constructor body runs. If runPersistenceMigrations throws, the fiber is never interrupted because the caller never receives an instance to call close(). Consider moving fiber creation after migration succeeds, or interrupting the fiber in the catch block.
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistenceService.ts around line 195:
The `stateEventsBridge` fiber is started in a field initializer before the constructor body runs. If `runPersistenceMigrations` throws, the fiber is never interrupted because the caller never receives an instance to call `close()`. Consider moving fiber creation after migration succeeds, or interrupting the fiber in the `catch` block.
Evidence trail:
apps/server/src/persistenceService.ts lines 194-235 at commit 40f9885dceed14d5af286fb33d23b48e7fd3e974:
- Line 195: `private readonly stateEventsBridge = Effect.runFork(this.runStateEventsBridge());` (field initializer starts fiber)
- Lines 198-217: constructor body, with try-catch around `runPersistenceMigrations` at lines 202-213
- Lines 204-213: catch block closes db but does not interrupt stateEventsBridge
- Lines 219-235: close() method interrupts fiber at line 230, but caller never gets instance if constructor throws
| Effect.runSync(Scope.close(this.scope, Exit.void)); | ||
| } | ||
|
|
||
| runWithSqlClient<A, E>(effect: Effect.Effect<A, E, SqlClient.SqlClient>): A { |
There was a problem hiding this comment.
🟢 Low
persistence/sqliteAdapter.ts:150 runWithSqlClient uses Effect.runSync internally, which throws on async effects. Consider documenting this sync-only restriction in the method signature (e.g., rename to runSyncWithSqlClient) or updating the implementation to handle async effects.
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/sqliteAdapter.ts around line 150:
`runWithSqlClient` uses `Effect.runSync` internally, which throws on async effects. Consider documenting this sync-only restriction in the method signature (e.g., rename to `runSyncWithSqlClient`) or updating the implementation to handle async effects.
Evidence trail:
apps/server/src/persistence/sqliteAdapter.ts lines 150-152 (runWithSqlClient calls this.runEffect), lines 173-176 (runEffect uses Effect.runSync on line 175) at commit 40f9885dceed14d5af286fb33d23b48e7fd3e974
| [afterSeq], | ||
| ) | ||
| .unprepared) as StateEventRow[]; | ||
| return decodeStateEventRows(rows).map((row) => |
There was a problem hiding this comment.
🟠 High
repos/stateEventsRepo.ts:93 StateEventRowSchema expects seq: Number and payload_json: String, but the database may return bigint for sequences and NULL for payloads (when JSON.stringify(undefined) is inserted). Consider updating the schema to handle bigint (via Schema.Union) and nullable strings.
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/repos/stateEventsRepo.ts around line 93:
`StateEventRowSchema` expects `seq: Number` and `payload_json: String`, but the database may return `bigint` for sequences and `NULL` for payloads (when `JSON.stringify(undefined)` is inserted). Consider updating the schema to handle `bigint` (via `Schema.Union`) and nullable strings.
Evidence trail:
apps/server/src/persistence/schema.ts:17 - `NumberOrBigIntSchema = Schema.Union([Schema.Number, Schema.BigInt])`
apps/server/src/persistence/schema.ts:34-40 - `StateEventRowSchema` with `seq: Schema.Number` and `payload_json: Schema.String`
apps/server/src/persistence/schema.ts:42-44 - `StateSeqRowSchema` uses `Schema.optional(Schema.NullOr(NumberOrBigIntSchema))` for seq
apps/server/src/persistence/schema.ts:24-27 - `CompletedProviderItemRowSchema` uses `Schema.NullOr(Schema.String)` for payload_json
apps/server/src/persistence/repos/stateEventsRepo.ts:41-52 - `appendStateEvent` with `payload: unknown` and `JSON.stringify(input.payload)`
apps/server/src/persistence/repos/stateEventsRepo.ts:93 - `decodeStateEventRows(rows)` usage
| const normalized = diff.replace(/\r\n/g, "\n"); | ||
| const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m); | ||
| if (bPath?.[1]) return bPath[1]; | ||
| const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m); |
There was a problem hiding this comment.
🟡 Medium
domain/turnSummaries.ts:8 Suggestion: make parsePathFromDiff resilient to renames and deletions. Capture the destination path from the diff --git header (avoid the backreference), and when +++ is /dev/null, derive the path from the --- a/... line so deleted files aren’t omitted.
| const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m); | |
| const gitHeader = normalized.match(/^diff --git a\/.+ b\/(.+)$/m); |
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/domain/turnSummaries.ts around line 8:
Suggestion: make `parsePathFromDiff` resilient to renames and deletions. Capture the destination path from the `diff --git` header (avoid the backreference), and when `+++` is `/dev/null`, derive the path from the `--- a/...` line so deleted files aren’t omitted.
Evidence trail:
apps/server/src/persistence/domain/turnSummaries.ts lines 4-15 at commit 40f9885dceed14d5af286fb33d23b48e7fd3e974. Line 8 shows backreference `\1` in regex `/^diff --git a\/(.+) b\/\1$/m` which prevents rename matching. Lines 10-13 show that when `+++ /dev/null` is detected, the function returns `null` instead of deriving path from `--- a/...` line.
| export function inferProjectName(cwd: string): string { | ||
| const name = path.basename(cwd); | ||
| return name.length > 0 ? name : "project"; | ||
| } |
There was a problem hiding this comment.
🟢 Low
domain/projects.ts:21 On Windows, path.basename returns empty for drive roots like D:\ or E:\, so all root paths get the same name "project". Consider extracting the drive letter (e.g., "D-root") to avoid collisions when multiple drive roots are registered.
| export function inferProjectName(cwd: string): string { | |
| const name = path.basename(cwd); | |
| return name.length > 0 ? name : "project"; | |
| } | |
| export function inferProjectName(cwd: string): string { | |
| const name = path.basename(cwd); | |
| if (name.length > 0) { | |
| return name; | |
| } | |
| // Handle Windows drive roots (e.g., "C:\" -> "C-root") | |
| if (process.platform === "win32") { | |
| const drive = path.parse(cwd).root.replace(/[:\\]/g, "").toUpperCase(); | |
| if (drive) { | |
| return `${drive}-root`; | |
| } | |
| } | |
| return "project"; | |
| } |
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/domain/projects.ts around lines 21-24:
On Windows, `path.basename` returns empty for drive roots like `D:\` or `E:\`, so all root paths get the same name `"project"`. Consider extracting the drive letter (e.g., `"D-root"`) to avoid collisions when multiple drive roots are registered.
Evidence trail:
apps/server/src/persistence/domain/projects.ts lines 21-24 at commit 40f9885dceed14d5af286fb33d23b48e7fd3e974. The `inferProjectName` function uses `path.basename(cwd)` and falls back to `"project"` when the result is empty. Node.js `path.basename` behavior for Windows drive roots like `D:\` returns empty string (documented behavior in Node.js path module).
| continue; | ||
| } | ||
|
|
||
| if (char === ";" && !inSingleQuote && !inDoubleQuote && !inBacktick) { |
There was a problem hiding this comment.
🟡 Medium
persistence/sqliteAdapter.ts:72 Semicolons inside SQL comments (-- or /* */) will incorrectly split statements, causing syntax errors. Consider adding comment detection to skip semicolons within -- line comments and /* */ block comments.
🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/sqliteAdapter.ts around line 72:
Semicolons inside SQL comments (`--` or `/* */`) will incorrectly split statements, causing syntax errors. Consider adding comment detection to skip semicolons within `--` line comments and `/* */` block comments.
Evidence trail:
apps/server/src/persistence/sqliteAdapter.ts lines 47-90 at commit 40f9885dceed14d5af286fb33d23b48e7fd3e974. Specifically: lines 51-53 show only quote tracking (inSingleQuote, inDoubleQuote, inBacktick), line 72 shows the semicolon split condition only checks these three flags, no comment detection variables or logic exists in the function.
| if (typeof value === "bigint") { | ||
| return Number(value); | ||
| } |
There was a problem hiding this comment.
🟡 Medium
persistence/sqliteAdapter.ts:96 Converting bigint to number via Number(value) silently loses precision for values exceeding Number.MAX_SAFE_INTEGER. Consider checking bounds and throwing an error, or returning bigint to preserve precision for large lastInsertRowid values.
- if (typeof value === "bigint") {
- return Number(value);
- }
+ if (typeof value === "bigint") {
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
+ throw new RangeError(`Value ${value} exceeds safe integer range`);
+ }
+ return Number(value);
+ }🚀 Want me to fix this? Reply ex: "fix it for me".
🤖 Prompt for AI
In file apps/server/src/persistence/sqliteAdapter.ts around lines 96-98:
Converting `bigint` to `number` via `Number(value)` silently loses precision for values exceeding `Number.MAX_SAFE_INTEGER`. Consider checking bounds and throwing an error, or returning `bigint` to preserve precision for large `lastInsertRowid` values.
Evidence trail:
apps/server/src/persistence/sqliteAdapter.ts lines 92-100 (toSafeInteger function with bigint->Number conversion), lines 154-167 (runStatement using toSafeInteger for lastInsertRowid). Commit 40f9885dceed14d5af286fb33d23b48e7fd3e974.
Active view: fold settled threads; view swap is instant
|
@coderabbitai review |
|
|
Merged via direct push to |
…t-lines feat(machine-map): show the lines that the pause cut instead of hiding them
… above the page and can be enlarged' (pingdotgg#83) from fix/browser-pane-blank into dev Reviewed-on: https://git.nepjua.org/yasinuslu/t3code/pulls/83
…owser/cloud/terminal,+221 key)
… 翻译、resetsIn 拼接改全角、whitelist 订正
…browser/cloud/terminal wrap + 初翻(+230 key) # Conflicts: # packages/shared/src/i18n.zh.json # scripts/whitelist.json
Merge pinned main d5a5ee1 into imessage/marker-cross-thread-reads at b514eb3. Base: 688ae7c. Preserve pingdotgg#83's atomic marker/message checkpoints, retained-run refresh, shared metadata reads and fresh-tick admission fences alongside pingdotgg#72's outage gate and durable response/reset recovery, pingdotgg#61 bus delivery, and slow Moni callback readiness. Conflict decisions (paths under integrations/spectrum-bridge/src): - control.ts:170, disjoint-intent: retain HEAD's readTickId/beginReadTick and main's readonly linkGate on the same client. Poll attribution and link gating operate together; request guards and counters stay intact. - robob.ts:224, disjoint-intent: retain main's default-enabled gate-aware client construction plus HEAD's nativeAliases lookup/registration and existing shared MessageCache. Superseded subdecision: use main's gated default client instead of HEAD's ungated default; explicit linkGate:false and caller-supplied clients still work. Native/cache sharing is retained. - router.ts:734, disjoint-intent: retain main's RobobLinkDown branch with telemetry cancellation, retry-slot refund and lease release. Then retain HEAD's probeDeferred branch with lease release/rethrow before failure telemetry/backoff. Local snapshot deferrals create no cooldown or false failure; gate refusals consume no retry slot. Real failures still back off. - toollog.ts:39, disjoint-intent: union ID/numeric allowlists. Preserve tickId and all marker/cross-thread/detail/evidence/discovery counters, plus main's downMs, skippedCalls and failedProbes. Auto-merged outage, bus and Moni readiness logging remains intact. Only these four conflict regions were edited. All source bytes outside markers and every pre-existing staged main entry were verified unchanged. No fetch, push, install, deploy, restart or live database access occurred. Narrow local verification, existing parity-checked dependencies: - bun test test/robob.test.ts -t 'marker polling': 93 pass, 0 fail; 800 assertions. Five-thread idle/active/steer polling counts stay 60/112/112 and active/steer completion stays at second 50. - bun test test/control-routing.test.ts test/link-gate.test.ts: 217 pass, 0 fail; 2855 assertions, including outage and response recovery. - git diff --cached --check and outside-conflict/index checks passed. Parent owns merged-head re-review and required focused/full offbox checks. No result from earlier queued offbox clients is claimed as verification.
Merge pinned main 8c61334 into imessage/marker-cross-thread-reads at 1c89090. Merge base: d5a5ee1. Preserve pingdotgg#83 marker/cross-thread cache telemetry, separate evidence/detail counters, tick attribution and gate-admitted physical counts alongside pingdotgg#94 durable ambiguous wake recovery/status diagnostics and pingdotgg#97 runtime log isolation for non-installed entry scripts. Conflict decision (one hunk): - integrations/spectrum-bridge/src/toollog.ts:39, disjoint-intent: retain HEAD's ID_KEYS including tickId and NUMBERS including markerPolls, crossThreadReads, crossThreadPages, markerSkips, fallbacks, trackedThreads, detailReads, evidenceReads, discoveryReads, markerChecks and crossThreadChecks. These are supersets of main's ID/numeric keys. Insert main's WAKE_EVENTS allowlist between those declarations, retaining all six lifecycle events. Main's already-merged wake metadata filtering and log-cap exemptions remain intact. Both independent behaviors survive; no competing design answer was selected and no product decision arose. Only the marked conflict region was manually edited. Every byte outside that region and every other pre-existing staged entry were verified unchanged, including router.ts and installed-entry log isolation. Repeated toollog allowlist conflicts remain a reconciliation hotspot. Narrow local validation with existing dependencies: - bun test test/toollog.test.ts: 46 pass, 0 fail, 158 assertions. - git diff --cached --check passed; no conflict markers or unstaged files. - Original index comparison and reviewed tree reconfirmed before commit. Parent owns merged-head Sol re-review and both required offbox commands. Previous 1c89090 test results do not certify this merged tree. No fetch, push, install, deploy, restart or live database access occurred. Model: gpt-6.1-sol; harness: Codex (T3 Code).
Merge pinned main 9f1ace1 into imessage/marker-cross-thread-reads at 63b8c88. Merge base: 8c61334. Preserve pingdotgg#83 marker/cross-thread polling, pingdotgg#50-equivalent records, tick attribution, separate gate-admitted physical read counters and bounded outage logs alongside main's bounded scans, loop-stall diagnostics and wake delivery waits (pingdotgg#105/pingdotgg#108), Moni boundary (pingdotgg#73) and outage detail (pingdotgg#100). Intent sources: both base-to-side diffs and full commit messages, including 34667c0, 77c3c89, 273e77d, 6802d61 and 8eb5542. Conflict decision: one hunk in integrations/spectrum-bridge/src/toollog.ts:40, classified disjoint-intent, with three independent subdecisions: - ID_KEYS: retain HEAD's complete set, including tickId. It contains all main IDs, including outageId, so tick attribution and correlation coexist. - WAKE_EVENTS: retain main's seven-event set, adding wake.waiting to all six existing events. Bounded wait diagnostics survive the already-merged wake metadata filter and cap exemptions. - NUMBERS: retain HEAD's complete set. It contains every main numeric key plus markerPolls, crossThreadReads, crossThreadPages, markerSkips, fallbacks, trackedThreads, detailReads, evidenceReads, discoveryReads, markerChecks and crossThreadChecks. downMs, skippedCalls and failedProbes remain. Each resulting declaration is exactly the union of both sides. No competing product answer or superseded behavior was selected. Only this marked conflict region was manually edited. Every byte outside it and all 31,695 other index entries match the halted merge, including router.ts, main.ts, sb-main.ts and runtime log isolation. The repeated allowlist conflict remains a hotspot already flagged by the parent. Validation: - bun test test/toollog.test.ts: 46 pass, 0 fail, 158 assertions. - git diff --cached --check passed; no staged conflict markers remain. - Pinned parents, reviewed index and tree reconfirmed immediately before commit. Parent owns exact-merged-head Sol re-review and both unchanged packet commands offbox. Predecessor receipts do not certify this merge. No push, deploy, restart, install, offbox, broad suite or live DB access.
Neutral reconcile against latest main after pingdotgg#522 (bounded active roster refetches), 1a0ddd7 (idle creation family discovery dropped) and pingdotgg#93 (linear recordsFromThread) landed. Conflicts, two files: - src/toollog.ts: union. Keep pingdotgg#83's "timeout"/"error"/"status" reason values and add main's new `attribution` enum. - test/robob.test.ts (60-second router budget test, 2 hunks): keep pingdotgg#83's loop with the evaluator-authorized 15 s timeout for the legacy 1,500-row active/steer cases only. pingdotgg#93 dropped main's blanket 30 s stopgap; the narrower per-case headroom is kept, and pingdotgg#93's linear recordsFromThread merges in unchanged. Outside the conflicts, ActiveRoster's checkpoint/observe/finish API is unchanged on main (DetailRead gains an optional `event`), so the MessageCache physical-detail connector keeps working without edits.
Main moved 7 commits after 950de7d (pingdotgg#134 batch-membership index and stall timings; pingdotgg#111/pingdotgg#128/pingdotgg#130 requeue caps, failed-turn backoff, steer retries). Only src/toollog.ts conflicted, and both sides only added entries: - NUMBERS: union. Main's streakCount/backoffMs plus pingdotgg#83's marker, detail and evidence counters. - reason: union. pingdotgg#83's timeout/error/status plus main's agent_no_reply and providerFailureStreak. - attribution: main's list (adds pending_inbound; superset of ours).
This pull request contains changes generated by a Cursor Cloud Agent