Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: v2.10.0 release-review follow-ups + test coverage

Adam Eivy354b40a43c2f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2c4e6babcb..b1ae232c45 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -21,5 +21,6 @@ TBD
- **[peer-sync-per-category-version-gate] Machines on different PortOS versions keep syncing everything except the one changed data type.** When one federated machine updates to a version that changes how a single kind of data is stored (universes, comics, or media collections), the others used to refuse the *entire* sync until they caught up — silently stalling all data between them. Now only transfers of the changed data type wait for the lagging machine to update; every other kind keeps flowing.
- **Voice timers survive a restart and no longer double-fire.** A timer or reminder you set by voice ("remind me in 30 minutes to call mom") is now saved to disk, so it still goes off if PortOS restarts before it's due — any that came due while it was down fire as soon as it's back. A single request can no longer arm two timers, so you won't get the same reminder twice.
- **Federated media collections: a merged-away duplicate no longer survives on peers.** When a universe (or series) *merge* tombstones the loser's auto-collection, a receiving peer applies the universe tombstone first — and its cascade (`unlinkCollectionsForUniverse` / `unlinkCollectionsForSeries`) was stamping the linked collection's `updatedAt` to "now", which then defeated the collection's own (older) tombstone under Last-Writer-Wins and left a live duplicate "Universe: X" collection on the peer. The cascade unlink now **preserves `updatedAt`** (it's a derived side-effect of the owner's deletion, not a user edit), so the collection tombstone still wins and both machines converge to deleted. Items are never lost — they're always unioned on merge.
+- **Federated sync metadata no longer grows without bound.** When a duplicate universe or series is merged away (or otherwise force-pruned), its leftover entry in the cross-machine sync base-hash file used to linger forever. Those orphaned entries are now removed as part of the prune, so the file doesn't slowly accumulate dead rows on long-lived federated installs.
## Removed
diff --git a/PLAN.md b/PLAN.md
index ef9a78698a..3f50b3f8a9 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -150,15 +150,16 @@ Surfaced while adding merge-verified worktree reaping (`isBranchMergedInto` + `r
Surfaced by the multi-reviewer release gate for v2.10.0. The CRITICAL/correctness findings were fixed in-release (paused-agent cleanup protection, browser spawn/loadConfig guards, CLI pause-ordering double-finalize, runner immediate-fallback exit-0 race, conflict-journal `ERR_TARGET_GONE`→409, pause-route Zod). The items below were deferred as test-coverage gaps or non-blocking improvements.
-- [ ] [test-paused-agent-cleanup-protection] **Add a test that `agentDataCleanup` excludes paused agents from worktree/data reaping.** The fix (`server/services/autonomousJobs.js` reads `data/cos/state.json` and unions `status === 'paused'` ids into the protect set) is currently unverified by tests — `agentDataCleanup` is a private (non-exported) handler and has no test today. Export it (or the `SCRIPT_HANDLERS` map), build fs (`readdir`/`stat`/`rm`) + `reapMergedWorktrees`/`cleanupOrphanedWorktrees` mocks, seed a state.json with a paused agent, and assert its worktree + data dir are NOT reaped. (Batch-1 CRITICAL review follow-up.)
-- [ ] [test-pause-agent-branches] **Cover the non-happy-path `pauseAgent` branches.** `agentManagement.test.js` only tests the direct-mode happy path. Add: runner-branch success + `pauseAgentViaRunner` failure → `pausedAgents` rolled back and agent stays in `runnerAgents`; TUI branch (ESC + delayed `killSession`); and the close-handler skip-finalization contract (a `pausedAgents`-flagged agent hitting the CLI/TUI/runner close handler does NOT finalize the task / clean the worktree). (Batch-1 IMPROVEMENT.)
-- [ ] [cosrunner-orphan-paused-emit] **`cos-runner/index.js` emits `agent:paused` but nothing listens.** `cosRunnerClient.js` never subscribes to `agent:paused` (pause state is applied synchronously via the HTTP `/pause` path), so the emit is dead code implying a server listener that doesn't exist. Either drop the emit or wire `socket.on('agent:paused', …)` and handle it idempotently. (Batch-1 NIT.)
-- [ ] [merge-union-seasons-collision] **`unionSeasons` silently drops a loser season whose `number` collides with a survivor's.** `server/services/recordMerge.js` (~line 151) `continue`s past a colliding loser season, discarding its authored title/episodes/arc metadata even though the merge is documented as "no data loss" (this is a local merge, so the conflict journal never sees it). Either union the loser season's non-empty fields into the survivor, or surface a count in the `cascade` summary so the UI can warn "N loser seasons not merged." (Batch-2 NIT.)
-- [ ] [conflict-journal-basehash-evict] **`sync_base_hashes.json` entries are never evicted on record delete.** `server/lib/conflictJournal.js#setSyncBaseHash` keys by `${kind}:${id}`; when a record is tombstoned and force-pruned its base-hash entry leaks (slow unbounded growth on a long-lived federated install — not a correctness bug). Delete the entry as part of the delete cascade / tombstone prune. (Batch-2 NIT.)
-- [ ] [test-merge-route-contracts] **Route-level tests for the merge endpoints' contracts.** `universeBuilder.test.js`/`pipeline.test.js` only assert `status === 400` for identical-ids and never pin the body `code` (`MERGE_VALIDATION`); there's no route test for a successful `POST /merge` (`{ merged, cascade }`), the `DELETE /universe-builder/:id` 409 `UNIVERSE_HAS_LIVE_SERIES` + `context.blockingSeries` body the UI depends on, nor the `POST /merge/ai-resolve` error contract (`MERGE_AI_NO_MERGEABLE_FIELDS` 422, no-provider, `LLM_INVALID_JSON` 502). Add them. (Batch-2 IMPROVEMENT.)
-- [ ] [share-empty-scalar-helper] **Move `isEmptyScalar` out of `recordMerge.js` into a shared util.** `recordMerge.js`'s `isEmptyScalar` (null/undefined/empty-string/empty-array predicate) is now used by `resolveScalars` and `unionSeasons` and is a generic enough "is this value blank" check to live in `server/lib/objects.js` (or `validation.js`) for reuse. Low priority. (Batch-3/gemini NIT.)
-- [ ] [test-codereview-defaults-cache-isolation] **`codeReview.test.js` doesn't reset the module-level `cachedDefaults` between tests.** `getCodeReviewDefaults` memoizes into `cachedDefaults` (invalidated only by a `settings:updated` event the test stubs as a no-op); `afterEach` resets `mockedSettings.current` but never clears the cache, so a future test adding a second `getCodeReviewDefaults()` call with different settings would silently read stale data. Export a test-only `__resetCodeReviewDefaultsCache()` and call it in `afterEach`. Latent (no current failure). (Batch-1/claude NIT.)
-- [ ] [test-codereview-local-route] **`POST /api/code-review/local` has no route-level test.** Add a supertest-style test (mocking `runLocalCodeReview`/`getSettings`): empty `diff` → 400 (Zod), unknown `backend` → 400 (`z.enum`), `model` omitted falls back to the settings model, and `{ ok: false }` service result → 502. Also add `validation.test.js` assertions that `featureProviderConfigSchema.parse({ providerId:'', model:'' })` yields `undefined`s and `codeReviewSettingsSchema` rejects unknown keys (`.strict()`). (Batch-3 IMPROVEMENT/NIT.)
+- [x] [test-paused-agent-cleanup-protection] _(DONE post-v2.10.0 patch)_ **Add a test that `agentDataCleanup` excludes paused agents from worktree/data reaping.** The fix (`server/services/autonomousJobs.js` reads `data/cos/state.json` and unions `status === 'paused'` ids into the protect set) is currently unverified by tests — `agentDataCleanup` is a private (non-exported) handler and has no test today. Export it (or the `SCRIPT_HANDLERS` map), build fs (`readdir`/`stat`/`rm`) + `reapMergedWorktrees`/`cleanupOrphanedWorktrees` mocks, seed a state.json with a paused agent, and assert its worktree + data dir are NOT reaped. (Batch-1 CRITICAL review follow-up.)
+- [x] [test-pause-agent-branches] _(DONE post-v2.10.0 patch)_ **Cover the non-happy-path `pauseAgent` branches.** `agentManagement.test.js` only tests the direct-mode happy path. Add: runner-branch success + `pauseAgentViaRunner` failure → `pausedAgents` rolled back and agent stays in `runnerAgents`; TUI branch (ESC + delayed `killSession`); and the close-handler skip-finalization contract (a `pausedAgents`-flagged agent hitting the CLI/TUI/runner close handler does NOT finalize the task / clean the worktree). (Batch-1 IMPROVEMENT.)
+- [x] [cosrunner-orphan-paused-emit] _(DONE post-v2.10.0 patch — dropped the dead emit per YAGNI)_ **`cos-runner/index.js` emits `agent:paused` but nothing listens.** `cosRunnerClient.js` never subscribes to `agent:paused` (pause state is applied synchronously via the HTTP `/pause` path), so the emit is dead code implying a server listener that doesn't exist. Either drop the emit or wire `socket.on('agent:paused', …)` and handle it idempotently. (Batch-1 NIT.)
+- [x] [merge-union-seasons-collision] _(DONE — already fixed in #505 merge-union-summary; verified `unionSeasons` gap-fills colliding loser seasons into the survivor instead of dropping them)_ **`unionSeasons` silently drops a loser season whose `number` collides with a survivor's.** `server/services/recordMerge.js` (~line 151) `continue`s past a colliding loser season, discarding its authored title/episodes/arc metadata even though the merge is documented as "no data loss" (this is a local merge, so the conflict journal never sees it). Either union the loser season's non-empty fields into the survivor, or surface a count in the `cascade` summary so the UI can warn "N loser seasons not merged." (Batch-2 NIT.)
+- [x] [conflict-journal-basehash-evict] _(DONE post-v2.10.0 patch)_ **`sync_base_hashes.json` entries are never evicted on record delete.** `server/lib/conflictJournal.js#setSyncBaseHash` keys by `${kind}:${id}`; when a record is tombstoned and force-pruned its base-hash entry leaks (slow unbounded growth on a long-lived federated install — not a correctness bug). Delete the entry as part of the delete cascade / tombstone prune. (Batch-2 NIT.)
+- [x] [test-merge-route-contracts] _(DONE post-v2.10.0 patch — route identical-ids returns `VALIDATION_ERROR` via Zod refine; service-level `MERGE_VALIDATION` still pinned in recordMerge.test.js)_ **Route-level tests for the merge endpoints' contracts.** `universeBuilder.test.js`/`pipeline.test.js` only assert `status === 400` for identical-ids and never pin the body `code` (`MERGE_VALIDATION`); there's no route test for a successful `POST /merge` (`{ merged, cascade }`), the `DELETE /universe-builder/:id` 409 `UNIVERSE_HAS_LIVE_SERIES` + `context.blockingSeries` body the UI depends on, nor the `POST /merge/ai-resolve` error contract (`MERGE_AI_NO_MERGEABLE_FIELDS` 422, no-provider, `LLM_INVALID_JSON` 502). Add them. (Batch-2 IMPROVEMENT.)
+- [x] [share-empty-scalar-helper] _(DONE post-v2.10.0 patch — moved to `server/lib/objects.js`)_ **Move `isEmptyScalar` out of `recordMerge.js` into a shared util.** `recordMerge.js`'s `isEmptyScalar` (null/undefined/empty-string/empty-array predicate) is now used by `resolveScalars` and `unionSeasons` and is a generic enough "is this value blank" check to live in `server/lib/objects.js` (or `validation.js`) for reuse. Low priority. (Batch-3/gemini NIT.)
+- [x] [test-codereview-defaults-cache-isolation] _(DONE post-v2.10.0 patch)_ **`codeReview.test.js` doesn't reset the module-level `cachedDefaults` between tests.** `getCodeReviewDefaults` memoizes into `cachedDefaults` (invalidated only by a `settings:updated` event the test stubs as a no-op); `afterEach` resets `mockedSettings.current` but never clears the cache, so a future test adding a second `getCodeReviewDefaults()` call with different settings would silently read stale data. Export a test-only `__resetCodeReviewDefaultsCache()` and call it in `afterEach`. Latent (no current failure). (Batch-1/claude NIT.)
+- [x] [test-codereview-local-route] _(DONE post-v2.10.0 patch)_ **`POST /api/code-review/local` has no route-level test.** Add a supertest-style test (mocking `runLocalCodeReview`/`getSettings`): empty `diff` → 400 (Zod), unknown `backend` → 400 (`z.enum`), `model` omitted falls back to the settings model, and `{ ok: false }` service result → 502. Also add `validation.test.js` assertions that `featureProviderConfigSchema.parse({ providerId:'', model:'' })` yields `undefined`s and `codeReviewSettingsSchema` rejects unknown keys (`.strict()`). (Batch-3 IMPROVEMENT/NIT.)
+- [ ] [test-route-suites-peer-fanout-mock-noise] **`pipeline.test.js` / `universeBuilder.test.js` log noisy `auto-subscribe after create failed: [vitest] error when mocking a module` warnings on every record-creating test (pre-existing on main — ~88 in pipeline.test.js alone, surfaced during the v2.10.0 patch code review).** Root cause: `createSeries`/`createUniverse` fire-and-forget `import('../sharing/peerSync.js').then(autoSubscribeRecordToAllPeers)`, and in these suites that dynamic import trips a hoisting-broken `vi.mock` factory elsewhere in the graph, so the `.catch` swallows it and logs. Tests still pass (non-fatal). The canonical fix is to mock `services/instances.js` (`mockNoPeers`) + `services/sharing/peerSync.js` (`mockNoPeerSync`) per the CLAUDE.md test contract — but the route graph statically imports a broad peerSync surface (`installPeerSyncListener`, `peerSyncEvents`, `listPeerSubscriptions`, `assetShaListForRecord`), so a full-replace mock drops needed exports and the `importActual`-spread form currently throws the same vitest mock-factory error. Needs a dedicated investigation into why `vi.importActual('../services/sharing/peerSync.js')` inside the factory errors here (likely a circular/hoist interaction with the other mocks) before the noise can be silenced. Out of scope for the v2.10.0 patch (pre-existing, non-fatal). Surfaced 2026-05-26.
## Future Ideas
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 478b9ac901..a349749265 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -716,7 +716,6 @@ app.post('/pause/:agentId', async (req, res) => {
if (current?.paused) current.process.kill('SIGKILL');
}, 5000);
- emitToServer('agent:paused', { agentId, taskId: agent.taskId, pid: agent.pid, pausedAt, reason });
res.json({ success: true, agentId, pid: agent.pid, pausedAt });
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 05f970e36d..232ceb6422 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -83,7 +83,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. |
-| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
+| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store. `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from `pruneTombstonedUniverses`/`pruneTombstonedSeries`) so the side store doesn't grow without bound. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
@@ -172,7 +172,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `asyncMutex.js` | Promise-based async mutex. |
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |
-| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing). |
+| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 51f146d3cf..c25776af85 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -104,6 +104,20 @@ export async function setSyncBaseHash(kind, id, hash) {
_baseDirty = true;
}
+/**
+ * Remove the base hash for a pruned record (idempotent — no-op if already
+ * absent). Call when a tombstone is force-pruned so the entry doesn't grow
+ * without bound on long-lived federated installs.
+ */
+export async function deleteSyncBaseHash(kind, id) {
+ const map = await ensureBaseLoaded();
+ const key = baseKey(kind, id);
+ if (!map.has(key)) return;
+ map.delete(key);
+ _baseDirty = true;
+ await flushBaseHashes();
+}
+
/** Persist the base-hash map if dirty. Serialized so concurrent flushes can't
* interleave file writes. Call once after a merge's write loop. */
export function flushBaseHashes() {
diff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.js
index ef171822b1..57bbe798dc 100644
--- a/server/lib/conflictJournal.test.js
+++ b/server/lib/conflictJournal.test.js
@@ -114,4 +114,18 @@ describe('conflictJournal', () => {
expect(entries).toHaveLength(1);
expect(entries[0].localSnapshot.starterPrompt).toBe('precious local edit');
});
+
+ it('deleteSyncBaseHash removes an existing entry so getSyncBaseHash returns null', async () => {
+ const base = uni({ starterPrompt: 'base' });
+ const hash = cj.contentHashForRecord('universe', base);
+ await cj.setSyncBaseHash('universe', 'u-del', hash);
+ expect(await cj.getSyncBaseHash('universe', 'u-del')).toBe(hash);
+ await cj.deleteSyncBaseHash('universe', 'u-del');
+ expect(await cj.getSyncBaseHash('universe', 'u-del')).toBeNull();
+ });
+
+ it('deleteSyncBaseHash is a no-op for a key that was never set', async () => {
+ await expect(cj.deleteSyncBaseHash('universe', 'nonexistent')).resolves.toBeUndefined();
+ expect(await cj.getSyncBaseHash('universe', 'nonexistent')).toBeNull();
+ });
});
diff --git a/server/lib/objects.js b/server/lib/objects.js
index 469cc0b4b4..b610c16c8d 100644
--- a/server/lib/objects.js
+++ b/server/lib/objects.js
@@ -33,6 +33,15 @@
export const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+/**
+ * `isEmptyScalar(v)` — `true` when `v` is null, undefined, a whitespace-only
+ * string, or an empty array. Used to gate one-way gap-fill logic in merge
+ * helpers: only overwrite a field on the survivor when the survivor's value is
+ * "empty" by this definition AND the loser's value is not.
+ */
+export const isEmptyScalar = (v) => v === null || v === undefined || (typeof v === 'string' && v.trim() === '')
+ || (Array.isArray(v) && v.length === 0);
+
// Prototype-pollution guard: skip keys that would mutate Object.prototype
// when assigned through normal property access. Every current call site
// gates input through a Zod schema (which strips unknown keys), but the
diff --git a/server/lib/objects.test.js b/server/lib/objects.test.js
index 0b01201cfd..b7056b46e8 100644
--- a/server/lib/objects.test.js
+++ b/server/lib/objects.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { deepMerge, isPlainObject, canonicalStringify } from './objects.js';
+import { deepMerge, isEmptyScalar, isPlainObject, canonicalStringify } from './objects.js';
describe('isPlainObject', () => {
it('returns true for plain `{}`-shaped values', () => {
@@ -32,6 +32,40 @@ describe('isPlainObject', () => {
});
});
+describe('isEmptyScalar', () => {
+ it('returns true for null and undefined', () => {
+ expect(isEmptyScalar(null)).toBe(true);
+ expect(isEmptyScalar(undefined)).toBe(true);
+ });
+
+ it('returns true for empty string and whitespace-only strings', () => {
+ expect(isEmptyScalar('')).toBe(true);
+ expect(isEmptyScalar(' ')).toBe(true);
+ expect(isEmptyScalar('\t\n')).toBe(true);
+ });
+
+ it('returns true for an empty array', () => {
+ expect(isEmptyScalar([])).toBe(true);
+ });
+
+ it('returns false for non-empty strings', () => {
+ expect(isEmptyScalar('hello')).toBe(false);
+ expect(isEmptyScalar(' x ')).toBe(false);
+ });
+
+ it('returns false for non-empty arrays', () => {
+ expect(isEmptyScalar([1])).toBe(false);
+ expect(isEmptyScalar([''])).toBe(false);
+ });
+
+ it('returns false for numbers, booleans, and plain objects', () => {
+ expect(isEmptyScalar(0)).toBe(false);
+ expect(isEmptyScalar(false)).toBe(false);
+ expect(isEmptyScalar({})).toBe(false);
+ expect(isEmptyScalar({ a: 1 })).toBe(false);
+ });
+});
+
describe('deepMerge', () => {
it('merges nested objects recursively', () => {
const base = { a: { b: 1, c: 2 }, d: 3 };
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 52f68ef6b8..3569c40daa 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -14,6 +14,7 @@ import {
buildReviewWithArgs,
createCosTaskSchema,
featureProviderConfigSchema,
+ codeReviewSettingsSchema,
locationSettingsSchema
} from './validation.js';
@@ -41,6 +42,39 @@ describe('validation.js', () => {
});
});
+ describe('codeReviewSettingsSchema', () => {
+ it('accepts a valid full payload', () => {
+ const r = codeReviewSettingsSchema.safeParse({
+ reviewers: ['copilot', 'lmstudio'],
+ stopMode: 'on-clean',
+ reviewerApplies: true,
+ lmstudioModel: 'qwen2.5-coder:7b',
+ ollamaModel: 'codellama',
+ })
+ expect(r.success).toBe(true)
+ })
+
+ it('accepts an empty object (all fields optional)', () => {
+ expect(codeReviewSettingsSchema.safeParse({}).success).toBe(true)
+ })
+
+ it('rejects unknown keys (strict mode)', () => {
+ const r = codeReviewSettingsSchema.safeParse({
+ reviewers: ['copilot'],
+ unknownField: 'oops',
+ })
+ expect(r.success).toBe(false)
+ })
+
+ it('rejects an unknown reviewer enum value', () => {
+ expect(codeReviewSettingsSchema.safeParse({ reviewers: ['bogus'] }).success).toBe(false)
+ })
+
+ it('rejects an unknown stopMode', () => {
+ expect(codeReviewSettingsSchema.safeParse({ stopMode: 'nope' }).success).toBe(false)
+ })
+ })
+
describe('processSchema', () => {
it('should validate a complete process object', () => {
const process = {
diff --git a/server/routes/codeReview.test.js b/server/routes/codeReview.test.js
new file mode 100644
index 0000000000..d3d14fddc2
--- /dev/null
+++ b/server/routes/codeReview.test.js
@@ -0,0 +1,140 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import express from 'express'
+import { request } from '../lib/testHelper.js'
+import { errorMiddleware } from '../lib/errorHandler.js'
+
+vi.mock('../services/codeReview.js', () => ({
+ runLocalCodeReview: vi.fn(),
+ getCodeReviewDefaults: vi.fn(),
+}))
+
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(),
+}))
+
+const codeReviewSvc = await import('../services/codeReview.js')
+const settingsSvc = await import('../services/settings.js')
+const { default: routes } = await import('./codeReview.js')
+
+const makeApp = () => {
+ const app = express()
+ app.use(express.json())
+ app.use('/api/code-review', routes)
+ app.use(errorMiddleware)
+ return app
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ // Default settings stub — tests override as needed
+ settingsSvc.getSettings.mockResolvedValue({})
+ codeReviewSvc.getCodeReviewDefaults.mockResolvedValue({
+ reviewers: ['copilot'],
+ stopMode: 'all',
+ reviewerApplies: false,
+ lmstudioModel: null,
+ ollamaModel: null,
+ })
+})
+
+describe('POST /api/code-review/local', () => {
+ it('returns 400 when diff is empty (Zod min(1) rejection)', async () => {
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'lmstudio', model: 'qwen', diff: '' })
+ expect(res.status).toBe(400)
+ expect(codeReviewSvc.runLocalCodeReview).not.toHaveBeenCalled()
+ })
+
+ it('returns 400 when diff is missing', async () => {
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'ollama', model: 'codellama' })
+ expect(res.status).toBe(400)
+ expect(codeReviewSvc.runLocalCodeReview).not.toHaveBeenCalled()
+ })
+
+ it('returns 400 when backend is an unknown enum value', async () => {
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'copilot', model: 'x', diff: 'diff --git a b' })
+ expect(res.status).toBe(400)
+ expect(codeReviewSvc.runLocalCodeReview).not.toHaveBeenCalled()
+ })
+
+ it('falls back to the settings model when model is omitted', async () => {
+ settingsSvc.getSettings.mockResolvedValue({
+ codeReview: { lmstudioModel: 'settings-model' },
+ })
+ codeReviewSvc.runLocalCodeReview.mockResolvedValue({
+ ok: true,
+ backend: 'lmstudio',
+ model: 'settings-model',
+ findings: 'No findings.',
+ })
+
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'lmstudio', diff: 'diff --git a b' })
+
+ expect(res.status).toBe(200)
+ expect(codeReviewSvc.runLocalCodeReview).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'settings-model' }),
+ )
+ })
+
+ it('passes the caller-supplied model through when present', async () => {
+ settingsSvc.getSettings.mockResolvedValue({
+ codeReview: { ollamaModel: 'settings-model' },
+ })
+ codeReviewSvc.runLocalCodeReview.mockResolvedValue({
+ ok: true,
+ backend: 'ollama',
+ model: 'caller-model',
+ findings: 'No findings.',
+ })
+
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'ollama', model: 'caller-model', diff: 'diff --git a b' })
+
+ expect(res.status).toBe(200)
+ expect(codeReviewSvc.runLocalCodeReview).toHaveBeenCalledWith(
+ expect.objectContaining({ model: 'caller-model' }),
+ )
+ })
+
+ it('returns 502 when the service returns { ok: false }', async () => {
+ codeReviewSvc.runLocalCodeReview.mockResolvedValue({
+ ok: false,
+ backend: 'lmstudio',
+ model: 'm',
+ error: 'lmstudio API error 503: service unavailable',
+ })
+
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'lmstudio', model: 'm', diff: 'diff --git a b' })
+
+ expect(res.status).toBe(502)
+ expect(res.body.ok).toBe(false)
+ expect(res.body.error).toMatch(/lmstudio API error/)
+ })
+
+ it('returns 200 with findings on success', async () => {
+ codeReviewSvc.runLocalCodeReview.mockResolvedValue({
+ ok: true,
+ backend: 'ollama',
+ model: 'codellama',
+ findings: '## Blocking\n- file.js:10 fix the bug',
+ })
+
+ const res = await request(makeApp())
+ .post('/api/code-review/local')
+ .send({ backend: 'ollama', model: 'codellama', diff: 'diff --git a b' })
+
+ expect(res.status).toBe(200)
+ expect(res.body.ok).toBe(true)
+ expect(res.body.findings).toContain('Blocking')
+ })
+})
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index aa4a46257d..47a867d0ab 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -269,6 +269,20 @@ vi.mock('../lib/multipart.js', () => ({
uploadFields: () => (_req, _res, next) => next(),
}));
+// Controllable mergeSeries for series merge route contract tests.
+const mergeSeriesMock = vi.fn();
+vi.mock('../services/recordMerge.js', async () => {
+ const actual = await vi.importActual('../services/recordMerge.js');
+ return { ...actual, mergeSeries: (...args) => mergeSeriesMock(...args) };
+});
+
+// Controllable mergeFieldsWithAI for series/merge/ai-resolve error contracts.
+const mergeFieldsWithAIMock = vi.fn();
+vi.mock('../services/recordMergeAI.js', async () => {
+ const actual = await vi.importActual('../services/recordMergeAI.js');
+ return { ...actual, mergeFieldsWithAI: (...args) => mergeFieldsWithAIMock(...args) };
+});
+
const pipelineRouter = (await import('./pipeline.js')).default;
const universeSvc = await import('../services/universeBuilder.js');
@@ -288,6 +302,8 @@ describe('pipeline routes', () => {
fileStore.clear();
uuidCounter = 0;
vi.clearAllMocks();
+ mergeSeriesMock.mockReset();
+ mergeFieldsWithAIMock.mockReset();
});
it('POST /series → 201 with created series', async () => {
@@ -328,7 +344,8 @@ describe('pipeline routes', () => {
expect(res.body).toHaveProperty('orphans');
});
- it('POST /series/merge rejects identical survivor/loser ids with 400', async () => {
+ it('POST /series/merge rejects identical survivor/loser ids with 400 (Zod refine)', async () => {
+ // Zod catches same-id at schema level → 400 with generic validation code.
const app = makeApp();
const res = await request(app)
.post('/api/pipeline/series/merge')
@@ -336,6 +353,106 @@ describe('pipeline routes', () => {
expect(res.status).toBe(400);
});
+ it('POST /series/merge returns { merged: true, cascade } on success', async () => {
+ const app = makeApp();
+ mergeSeriesMock.mockResolvedValueOnce({
+ survivorId: 'ser-uuid-1',
+ loserId: 'ser-uuid-2',
+ merged: true,
+ cascade: { issuesToRepoint: 0, loserCollectionItemCount: 0 },
+ });
+
+ const res = await request(app)
+ .post('/api/pipeline/series/merge')
+ .send({ survivorId: 'ser-uuid-1', loserId: 'ser-uuid-2' });
+ expect(res.status).toBe(200);
+ expect(res.body.merged).toBe(true);
+ expect(res.body).toHaveProperty('cascade');
+ expect(res.body.survivorId).toBe('ser-uuid-1');
+ expect(mergeSeriesMock).toHaveBeenCalledWith(
+ 'ser-uuid-1', 'ser-uuid-2', {}, expect.objectContaining({ fieldOverrides: {} }),
+ );
+ });
+
+ describe('POST /series/merge/ai-resolve error contracts', () => {
+ it('400 when survivorId === loserId (Zod schema guard)', async () => {
+ const res = await request(makeApp())
+ .post('/api/pipeline/series/merge/ai-resolve')
+ .send({ survivorId: 'ser-1', loserId: 'ser-1', fields: ['logline'] });
+ expect(res.status).toBe(400);
+ expect(mergeFieldsWithAIMock).not.toHaveBeenCalled();
+ });
+
+ it('400 when survivorId does not match ser-<uuid> pattern', async () => {
+ const res = await request(makeApp())
+ .post('/api/pipeline/series/merge/ai-resolve')
+ .send({ survivorId: 'u-1', loserId: 'ser-uuid-2', fields: ['logline'] });
+ expect(res.status).toBe(400);
+ expect(mergeFieldsWithAIMock).not.toHaveBeenCalled();
+ });
+
+ it('422 MERGE_AI_NO_MERGEABLE_FIELDS when fields are not non-empty strings on both sides', async () => {
+ const { ServerError } = await import('../lib/errorHandler.js');
+ mergeFieldsWithAIMock.mockRejectedValueOnce(
+ new ServerError('No mergeable text fields', { status: 422, code: 'MERGE_AI_NO_MERGEABLE_FIELDS' }),
+ );
+
+ // Pre-populate series so the route can fetch them.
+ const app = makeApp();
+ await request(app).post('/api/pipeline/series').send({ name: 'AI-A', universeId: 'u-1' });
+ await request(app).post('/api/pipeline/series').send({ name: 'AI-B', universeId: 'u-1' });
+ const seriesSvc = await import('../services/pipeline/series.js');
+ const all = await seriesSvc.listSeries();
+ const [serA, serB] = all;
+
+ const res = await request(app)
+ .post('/api/pipeline/series/merge/ai-resolve')
+ .send({ survivorId: serA.id, loserId: serB.id, fields: ['logline'] });
+ expect(res.status).toBe(422);
+ expect(res.body.code).toBe('MERGE_AI_NO_MERGEABLE_FIELDS');
+ });
+
+ it('503 MERGE_AI_NO_PROVIDER when no AI provider is configured', async () => {
+ const { ServerError } = await import('../lib/errorHandler.js');
+ mergeFieldsWithAIMock.mockRejectedValueOnce(
+ new ServerError('No AI provider available', { status: 503, code: 'MERGE_AI_NO_PROVIDER' }),
+ );
+
+ const app = makeApp();
+ await request(app).post('/api/pipeline/series').send({ name: 'P-A', universeId: 'u-1', logline: 'x' });
+ await request(app).post('/api/pipeline/series').send({ name: 'P-B', universeId: 'u-1', logline: 'y' });
+ const seriesSvc = await import('../services/pipeline/series.js');
+ const all = await seriesSvc.listSeries();
+ const [serA, serB] = all;
+
+ const res = await request(app)
+ .post('/api/pipeline/series/merge/ai-resolve')
+ .send({ survivorId: serA.id, loserId: serB.id, fields: ['logline'] });
+ expect(res.status).toBe(503);
+ expect(res.body.code).toBe('MERGE_AI_NO_PROVIDER');
+ });
+
+ it('502 LLM_INVALID_JSON when the LLM returns unparseable JSON', async () => {
+ const { ServerError } = await import('../lib/errorHandler.js');
+ mergeFieldsWithAIMock.mockRejectedValueOnce(
+ new ServerError('LLM returned invalid JSON', { status: 502, code: 'LLM_INVALID_JSON' }),
+ );
+
+ const app = makeApp();
+ await request(app).post('/api/pipeline/series').send({ name: 'J-A', universeId: 'u-1', logline: 'x' });
+ await request(app).post('/api/pipeline/series').send({ name: 'J-B', universeId: 'u-1', logline: 'y' });
+ const seriesSvc = await import('../services/pipeline/series.js');
+ const all = await seriesSvc.listSeries();
+ const [serA, serB] = all;
+
+ const res = await request(app)
+ .post('/api/pipeline/series/merge/ai-resolve')
+ .send({ survivorId: serA.id, loserId: serB.id, fields: ['logline'] });
+ expect(res.status).toBe(502);
+ expect(res.body.code).toBe('LLM_INVALID_JSON');
+ });
+ });
+
it('PATCH /series/:id 404s for unknown id', async () => {
const app = makeApp();
const r = await request(app).patch('/api/pipeline/series/ser-nope').send({ name: 'x' });
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index 0a76e01d96..8f31f5c5c9 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -165,6 +165,21 @@ vi.mock('../lib/mediaModels.js', () => ({
isErnie: () => false,
}));
+// Controllable listSeries for DELETE /:id → 409 UNIVERSE_HAS_LIVE_SERIES test.
+// universeBuilder.deleteUniverse() calls listSeries() to guard against live series.
+const listSeriesMock = vi.fn(async () => []);
+vi.mock('../services/pipeline/series.js', async () => {
+ const actual = await vi.importActual('../services/pipeline/series.js');
+ return { ...actual, listSeries: (...args) => listSeriesMock(...args) };
+});
+
+// Controllable mergeFieldsWithAI for ai-resolve error contract tests.
+const mergeFieldsWithAIMock = vi.fn();
+vi.mock('../services/recordMergeAI.js', async () => {
+ const actual = await vi.importActual('../services/recordMergeAI.js');
+ return { ...actual, mergeFieldsWithAI: (...args) => mergeFieldsWithAIMock(...args) };
+});
+
const universeBuilderRoutes = (await import('./universeBuilder.js')).default;
const buildApp = () => {
@@ -184,6 +199,9 @@ describe('universe-builder routes', () => {
uuidCounter = 0;
collectionsByName.clear();
collectionsByUniverseId.clear();
+ listSeriesMock.mockReset();
+ listSeriesMock.mockResolvedValue([]);
+ mergeFieldsWithAIMock.mockReset();
});
it('GET / returns []', async () => {
@@ -879,11 +897,116 @@ describe('universe-builder routes', () => {
expect(res.body).toEqual({ groups: [] });
});
- it('POST /merge rejects identical survivor/loser ids with 400', async () => {
+ it('POST /merge rejects identical survivor/loser ids with 400 (Zod refine)', async () => {
+ // Zod catches same-id at schema level → 400 with generic validation code.
const res = await request(buildApp())
.post('/api/universe-builder/merge')
.send({ survivorId: 'u-1', loserId: 'u-1' });
expect(res.status).toBe(400);
});
+
+ it('POST /merge returns { merged: true, cascade } on success', async () => {
+ const app = buildApp();
+ // Universe A has a logline; B has an empty logline — only A's name is
+ // non-empty, so there are no true scalar conflicts when `fieldChoices`
+ // picks the survivor for the `name` field.
+ const a = await request(app).post('/api/universe-builder').send({ name: 'Merge-A', logline: 'A logline' });
+ const b = await request(app).post('/api/universe-builder').send({ name: 'Merge-B' });
+ expect(a.status).toBe(201);
+ expect(b.status).toBe(201);
+
+ const res = await request(app)
+ .post('/api/universe-builder/merge')
+ // Explicitly resolve the name conflict so the merge can proceed.
+ .send({ survivorId: a.body.id, loserId: b.body.id, fieldChoices: { name: 'survivor' } });
+ expect(res.status).toBe(200);
+ expect(res.body.merged).toBe(true);
+ expect(res.body).toHaveProperty('cascade');
+ expect(res.body.survivorId).toBe(a.body.id);
+ expect(res.body.loserId).toBe(b.body.id);
+ });
+
+ it('DELETE /:id → 409 UNIVERSE_HAS_LIVE_SERIES with context.blockingSeries', async () => {
+ const app = buildApp();
+ const created = await request(app)
+ .post('/api/universe-builder')
+ .send({ name: 'Blocked Universe' });
+ expect(created.status).toBe(201);
+ const universeId = created.body.id;
+
+ // Simulate a live series linked to this universe so deleteUniverse throws.
+ listSeriesMock.mockResolvedValue([
+ { id: 'ser-uuid-block', name: 'Linked Series', universeId },
+ ]);
+
+ const del = await request(app).delete(`/api/universe-builder/${universeId}`);
+ expect(del.status).toBe(409);
+ expect(del.body.code).toBe('UNIVERSE_HAS_LIVE_SERIES');
+ expect(del.body.context).toBeDefined();
+ expect(Array.isArray(del.body.context.blockingSeries)).toBe(true);
+ expect(del.body.context.blockingSeries[0].id).toBe('ser-uuid-block');
+ });
+ });
+
+ describe('POST /merge/ai-resolve error contracts', () => {
+ it('422 MERGE_AI_NO_MERGEABLE_FIELDS when no fields are non-empty strings on both sides', async () => {
+ const app = buildApp();
+ const a = await request(app).post('/api/universe-builder').send({ name: 'AI-A' });
+ const b = await request(app).post('/api/universe-builder').send({ name: 'AI-B' });
+
+ // All requested fields are empty on at least one side — service throws.
+ const { ServerError } = await import('../lib/errorHandler.js');
+ mergeFieldsWithAIMock.mockRejectedValueOnce(
+ new ServerError('No mergeable text fields', { status: 422, code: 'MERGE_AI_NO_MERGEABLE_FIELDS' }),
+ );
+
+ const res = await request(app)
+ .post('/api/universe-builder/merge/ai-resolve')
+ .send({ survivorId: a.body.id, loserId: b.body.id, fields: ['logline'] });
+ expect(res.status).toBe(422);
+ expect(res.body.code).toBe('MERGE_AI_NO_MERGEABLE_FIELDS');
+ });
+
+ it('503 MERGE_AI_NO_PROVIDER when no AI provider is configured', async () => {
+ const app = buildApp();
+ const a = await request(app).post('/api/universe-builder').send({ name: 'NoProvider-A', logline: 'x' });
+ const b = await request(app).post('/api/universe-builder').send({ name: 'NoProvider-B', logline: 'y' });
+
+ const { ServerError } = await import('../lib/errorHandler.js');
+ mergeFieldsWithAIMock.mockRejectedValueOnce(
+ new ServerError('No AI provider available for AI-assisted merge', { status: 503, code: 'MERGE_AI_NO_PROVIDER' }),
+ );
+
+ const res = await request(app)
+ .post('/api/universe-builder/merge/ai-resolve')
+ .send({ survivorId: a.body.id, loserId: b.body.id, fields: ['logline'] });
+ expect(res.status).toBe(503);
+ expect(res.body.code).toBe('MERGE_AI_NO_PROVIDER');
+ });
+
+ it('502 LLM_INVALID_JSON when the LLM returns unparseable JSON', async () => {
+ const app = buildApp();
+ const a = await request(app).post('/api/universe-builder').send({ name: 'BadJSON-A', logline: 'x' });
+ const b = await request(app).post('/api/universe-builder').send({ name: 'BadJSON-B', logline: 'y' });
+
+ const { ServerError } = await import('../lib/errorHandler.js');
+ mergeFieldsWithAIMock.mockRejectedValueOnce(
+ new ServerError('LLM returned invalid JSON for AI merge', { status: 502, code: 'LLM_INVALID_JSON' }),
+ );
+
+ const res = await request(app)
+ .post('/api/universe-builder/merge/ai-resolve')
+ .send({ survivorId: a.body.id, loserId: b.body.id, fields: ['logline'] });
+ expect(res.status).toBe(502);
+ expect(res.body.code).toBe('LLM_INVALID_JSON');
+ });
+
+ it('400 when survivorId === loserId (Zod schema guard)', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/merge/ai-resolve')
+ .send({ survivorId: 'u-1', loserId: 'u-1', fields: ['logline'] });
+ expect(res.status).toBe(400);
+ expect(mergeFieldsWithAIMock).not.toHaveBeenCalled();
+ });
});
});
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 6b5b54abe2..c309be7b77 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -26,7 +26,19 @@
* async-heavy production module).
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+// Normalize CRLF→LF so the fixed char-window slices below stay deterministic on
+// Windows checkouts (CRLF inflates byte offsets and can push a matched anchor
+// past the window, producing a spurious failure).
+const normalizeEol = (s) => s.replace(/\r\n/g, '\n');
+const AGENT_CLI_SRC = normalizeEol(readFileSync(join(__dirname, 'agentCliSpawning.js'), 'utf-8'));
+const AGENT_TUI_SRC = normalizeEol(readFileSync(join(__dirname, 'agentTuiSpawning.js'), 'utf-8'));
+const AGENT_LIFECYCLE_SRC = normalizeEol(readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8'));
vi.mock('./cos.js', () => ({
updateTask: vi.fn().mockResolvedValue(true),
@@ -65,7 +77,9 @@ vi.mock('./worktreeManager.js', () => ({ cleanupOrphanedWorktrees: vi.fn() }));
import { handleOrphanedTask, pauseAgent } from './agentManagement.js';
import { updateTask, addTask, getTaskById } from './cos.js';
import { updateAgent } from './cosAgents.js';
-import { activeAgents, pausedAgents } from './agentState.js';
+import { pauseAgentViaRunner } from './cosRunnerClient.js';
+import * as shellService from './shell.js';
+import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
describe('handleOrphanedTask — duplicate-investigation guard', () => {
beforeEach(() => {
@@ -163,6 +177,7 @@ describe('pauseAgent', () => {
beforeEach(() => {
vi.clearAllMocks();
activeAgents.clear();
+ runnerAgents.clear();
pausedAgents.clear();
});
@@ -328,3 +343,268 @@ describe('getAgentProcessStats — Windows tasklist parsing', () => {
expect(result.memoryKb).toBe(10240);
});
});
+
+// ─── pauseAgent — runner branch ──────────────────────────────────────────────
+
+describe('pauseAgent — runner branch', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ activeAgents.clear();
+ runnerAgents.clear();
+ pausedAgents.clear();
+ });
+
+ it('success path: persists pause, removes agent from runnerAgents, returns mode=runner', async () => {
+ runnerAgents.set('runner-agent-1', {
+ taskId: 'task-r1',
+ task: { id: 'task-r1', taskType: 'user', description: 'Runner task', metadata: {} },
+ workspacePath: '/repo/worktree-r1',
+ runId: 'run-r1',
+ executionId: 'exec-r1'
+ });
+ getTaskById.mockResolvedValue({
+ id: 'task-r1',
+ taskType: 'user',
+ description: 'Runner task',
+ metadata: {}
+ });
+ pauseAgentViaRunner.mockResolvedValue({ success: true });
+
+ const result = await pauseAgent('runner-agent-1', 'cost limit');
+
+ expect(result).toMatchObject({ success: true, agentId: 'runner-agent-1', mode: 'runner' });
+ expect(pauseAgentViaRunner).toHaveBeenCalledWith('runner-agent-1', 'cost limit');
+ // Agent must be removed from runnerAgents after a successful pause
+ expect(runnerAgents.has('runner-agent-1')).toBe(false);
+ // pausedAgents is cleared by markAgentPaused + runnerAgents.delete path,
+ // but the Set entry is set during the call. Verify overall success persisted.
+ expect(updateAgent).toHaveBeenCalledWith('runner-agent-1', expect.objectContaining({
+ status: 'paused',
+ metadata: expect.objectContaining({ phase: 'paused', pauseReason: 'cost limit' })
+ }));
+ expect(updateTask).toHaveBeenCalledWith('task-r1', expect.objectContaining({
+ status: 'blocked',
+ metadata: expect.objectContaining({
+ blockedCategory: 'agent-paused',
+ pausedAgentId: 'runner-agent-1'
+ })
+ }), 'user');
+ });
+
+ it('failure path: pauseAgentViaRunner rejects → pausedAgents rolled back, runnerAgents intact', async () => {
+ runnerAgents.set('runner-agent-2', {
+ taskId: 'task-r2',
+ task: { id: 'task-r2', taskType: 'user', description: 'Runner task 2', metadata: {} },
+ workspacePath: '/repo/worktree-r2'
+ });
+ pauseAgentViaRunner.mockResolvedValue({ success: false, error: 'runner unreachable' });
+
+ const result = await pauseAgent('runner-agent-2', 'test-pause');
+
+ expect(result).toMatchObject({ success: false, error: 'runner unreachable' });
+ // pausedAgents must be rolled back when runner call fails
+ expect(pausedAgents.has('runner-agent-2')).toBe(false);
+ // runnerAgents must still contain the agent (not prematurely deleted)
+ expect(runnerAgents.has('runner-agent-2')).toBe(true);
+ });
+});
+
+// ─── pauseAgent — TUI branch ─────────────────────────────────────────────────
+
+describe('pauseAgent — TUI branch', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ activeAgents.clear();
+ runnerAgents.clear();
+ pausedAgents.clear();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('sends ESC to the TUI session and schedules a delayed killSession', async () => {
+ const sessionId = 'tui-session-99';
+ activeAgents.set('tui-agent-1', {
+ process: { kill: vi.fn() },
+ taskId: 'task-tui-1',
+ tuiSessionId: sessionId,
+ runId: 'run-tui-1',
+ pid: 999,
+ workspacePath: '/repo/worktree-tui',
+ executionId: 'exec-tui-1'
+ });
+ getTaskById.mockResolvedValue({
+ id: 'task-tui-1',
+ taskType: 'user',
+ description: 'TUI task',
+ metadata: {}
+ });
+
+ const result = await pauseAgent('tui-agent-1', 'user request');
+
+ expect(result).toMatchObject({ success: true, agentId: 'tui-agent-1', mode: 'tui' });
+ // ESC written immediately
+ expect(shellService.writeToSession).toHaveBeenCalledWith(sessionId, '\x1b');
+ // killSession not yet called (scheduled with 250ms delay)
+ expect(shellService.killSession).not.toHaveBeenCalled();
+
+ // Advance past the 250ms delay; agent is still in activeAgents at this point
+ vi.advanceTimersByTime(300);
+
+ expect(shellService.killSession).toHaveBeenCalledWith(sessionId);
+ });
+
+ it('does NOT call process.kill (SIGTERM) for a TUI agent', async () => {
+ const kill = vi.fn();
+ activeAgents.set('tui-agent-2', {
+ process: { kill },
+ taskId: 'task-tui-2',
+ tuiSessionId: 'tui-session-100',
+ pid: 888,
+ workspacePath: '/repo/worktree-tui2',
+ executionId: 'exec-tui-2'
+ });
+ getTaskById.mockResolvedValue({
+ id: 'task-tui-2',
+ taskType: 'user',
+ description: 'TUI task 2',
+ metadata: {}
+ });
+
+ await pauseAgent('tui-agent-2');
+
+ expect(kill).not.toHaveBeenCalled();
+ });
+});
+
+// ─── pauseAgent — not found ───────────────────────────────────────────────────
+
+describe('pauseAgent — agent not found', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ activeAgents.clear();
+ runnerAgents.clear();
+ pausedAgents.clear();
+ });
+
+ it('returns failure when agent is not in activeAgents or runnerAgents', async () => {
+ const result = await pauseAgent('nonexistent-agent');
+ expect(result).toMatchObject({ success: false, error: 'Agent not found or not running' });
+ });
+});
+
+// ─── Close-handler skip-finalization contract ─────────────────────────────────
+//
+// When a pausedAgents-flagged agent's process exits, the close handlers in
+// agentCliSpawning.js (CLI), agentTuiSpawning.js (TUI), and
+// agentLifecycle.js (runner handleAgentCompletion) must guard with
+// `pausedAgents.has(agentId)` and return BEFORE calling finalizeAgent /
+// cleanupWorktreeFn — so the worktree and task are preserved for a later resume.
+//
+// These tests use source-level assertions (matching the agentLifecycle.test.js
+// convention) to lock the structural contract without requiring the full
+// async dep chain to be wired up in this test suite.
+
+describe('close-handler skip-finalization — source contract', () => {
+ // Helper: extract the body of a function from source text.
+ // Returns everything from the function's opening brace to its matched closing brace.
+ function extractFunctionBody(src, fnSignatureSubstring) {
+ const fnStart = src.indexOf(fnSignatureSubstring);
+ if (fnStart === -1) return null;
+ const braceStart = src.indexOf('{', fnStart);
+ let depth = 0;
+ for (let i = braceStart; i < src.length; i++) {
+ if (src[i] === '{') depth++;
+ else if (src[i] === '}') { depth--; if (depth === 0) return src.slice(braceStart, i + 1); }
+ }
+ return null;
+ }
+
+ it('CLI close handler guards with pausedAgents.has and returns before finalizeAgent', () => {
+ // The guard appears in the claudeProcess.on('close', ...) callback.
+ const closeIdx = AGENT_CLI_SRC.indexOf("claudeProcess.on('close'");
+ expect(closeIdx, "claudeProcess 'close' handler must exist").toBeGreaterThan(-1);
+
+ const closeBody = AGENT_CLI_SRC.slice(closeIdx, closeIdx + 4000);
+
+ // Guard present
+ expect(closeBody).toMatch(/pausedAgents\.has\(agentId\)/);
+
+ // Guard appears BEFORE finalizeAgent in the close body
+ const guardPos = closeBody.indexOf('pausedAgents.has(agentId)');
+ const finalizePos = closeBody.indexOf('finalizeAgent(');
+ expect(guardPos, 'pause guard must precede finalizeAgent call').toBeLessThan(finalizePos);
+
+ // There is a `return` inside the pause guard block before finalizeAgent
+ // (the guard block ends with a bare `return;` or `return` before reaching finalize)
+ const guardBlock = closeBody.slice(guardPos, finalizePos);
+ expect(guardBlock).toMatch(/\breturn\b/);
+ });
+
+ it('TUI finish() guards with pausedAgents.has and returns before finalizeAgent', () => {
+ // finish() is defined as a const arrow-function inside spawnTuiAgent.
+ // The signature is: const finish = async ({ ... }) => {
+ // We need the body that starts at `=> {`, not the destructured params `{`.
+ const finishIdx = AGENT_TUI_SRC.indexOf('const finish = async');
+ expect(finishIdx, 'finish function must exist in agentTuiSpawning').toBeGreaterThan(-1);
+
+ // Find the `=> {` that opens the arrow body (past the parameter list)
+ const arrowIdx = AGENT_TUI_SRC.indexOf('=> {', finishIdx);
+ expect(arrowIdx, "'=> {' of finish() must exist").toBeGreaterThan(finishIdx);
+
+ // Extract body from the arrow body's `{` to its matched closing `}`
+ const braceStart = arrowIdx + 3; // points at `{`
+ let depth = 0;
+ let bodyEnd = braceStart;
+ for (let i = braceStart; i < AGENT_TUI_SRC.length; i++) {
+ if (AGENT_TUI_SRC[i] === '{') depth++;
+ else if (AGENT_TUI_SRC[i] === '}') { depth--; if (depth === 0) { bodyEnd = i; break; } }
+ }
+ const finishBody = AGENT_TUI_SRC.slice(braceStart, bodyEnd + 1);
+
+ // Guard present
+ expect(finishBody).toMatch(/pausedAgents\.has\(agentId\)/);
+
+ // Guard appears BEFORE finalizeAgent
+ const guardPos = finishBody.indexOf('pausedAgents.has(agentId)');
+ const finalizePos = finishBody.indexOf('finalizeAgent(');
+ expect(guardPos, 'pause guard must precede finalizeAgent in finish()').toBeLessThan(finalizePos);
+
+ // There is a return inside the guard block before reaching finalizeAgent
+ const guardBlock = finishBody.slice(guardPos, finalizePos);
+ expect(guardBlock).toMatch(/\breturn\b/);
+ });
+
+ it('runner handleAgentCompletion guards with pausedAgents.has and returns before completeAgent', () => {
+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
+ expect(fnStart, 'handleAgentCompletion must exist').toBeGreaterThan(-1);
+
+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 6000);
+
+ // Guard present
+ expect(fnBody).toMatch(/pausedAgents\.has\(agentId\)/);
+
+ // Guard appears BEFORE the main completeAgent / finalizeAgent calls
+ const guardPos = fnBody.indexOf('pausedAgents.has(agentId)');
+ const completePos = fnBody.indexOf('completeAgent(');
+ expect(guardPos, 'pause guard must precede completeAgent in handleAgentCompletion').toBeLessThan(completePos);
+
+ // There is a return inside the guard block (early exit before finalization)
+ const guardBlock = fnBody.slice(guardPos, completePos);
+ expect(guardBlock).toMatch(/\breturn\b/);
+ });
+
+ it('runner pause guard also cleans up runnerAgents entry before returning', () => {
+ // After returning early, the runner agent map entry must not be leaked.
+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 6000);
+
+ const guardPos = fnBody.indexOf('pausedAgents.has(agentId)');
+ const returnAfterGuard = fnBody.indexOf('return', guardPos);
+ // Between the guard and the early return, runnerAgents.delete must be called
+ const guardToReturn = fnBody.slice(guardPos, returnAfterGuard + 10);
+ expect(guardToReturn).toMatch(/runnerAgents\.delete\(agentId\)/);
+ });
+});
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index a6f7925ca5..ed3d95cd05 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -1579,6 +1579,7 @@ function getAllowedCommands() {
}
export {
+ agentDataCleanup,
getAllJobs,
getJob,
getEnabledJobs,
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index a2c3553838..6a17c18100 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -11,7 +11,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),
ensureDir: vi.fn().mockResolvedValue(),
atomicWrite: vi.fn().mockResolvedValue(),
safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw) } catch { return fallback } },
- PATHS: { cos: '/mock/data/cos', digitalTwin: '/mock/data/digital-twin', data: '/mock/data' },
+ PATHS: { cos: '/mock/data/cos', digitalTwin: '/mock/data/digital-twin', data: '/mock/data', root: '/mock/root' },
HOUR: 60 * 60 * 1000,
DAY: 24 * 60 * 60 * 1000
}))
@@ -19,7 +19,23 @@ tryReadFile: vi.fn().mockResolvedValue(null),
vi.mock('fs/promises', () => ({
writeFile: vi.fn().mockResolvedValue(),
readFile: vi.fn().mockResolvedValue('{}'),
- rename: vi.fn().mockResolvedValue()
+ rename: vi.fn().mockResolvedValue(),
+ readdir: vi.fn().mockResolvedValue([]),
+ stat: vi.fn().mockResolvedValue({ isDirectory: () => false, mtimeMs: 0 }),
+ rm: vi.fn().mockResolvedValue()
+}))
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn().mockReturnValue(false)
+}))
+
+vi.mock('./worktreeManager.js', () => ({
+ reapMergedWorktrees: vi.fn().mockResolvedValue({ reaped: [] }),
+ cleanupOrphanedWorktrees: vi.fn().mockResolvedValue(0)
+}))
+
+vi.mock('./agentState.js', () => ({
+ getActiveAgentIds: vi.fn().mockReturnValue([])
}))
vi.mock('./autobiography.js', () => ({
@@ -28,6 +44,7 @@ vi.mock('./autobiography.js', () => ({
// Import after mocks
import {
+ agentDataCleanup,
getAllJobs,
getJob,
getDueJobs,
@@ -46,6 +63,8 @@ import {
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js'
import { cosEvents } from './cosEvents.js'
import { checkAndPrompt } from './autobiography.js'
+import { reapMergedWorktrees, cleanupOrphanedWorktrees } from './worktreeManager.js'
+import { getActiveAgentIds } from './agentState.js'
describe('autonomousJobs', () => {
const mockJobsData = {
@@ -918,4 +937,81 @@ describe('autonomousJobs', () => {
await expect(executeScriptJob(regularJob)).rejects.toThrow('not a script job')
})
})
+
+ describe('agentDataCleanup — paused agent protection', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ reapMergedWorktrees.mockResolvedValue({ reaped: [] })
+ cleanupOrphanedWorktrees.mockResolvedValue(0)
+ // No active in-memory agents by default
+ getActiveAgentIds.mockReturnValue([])
+ })
+
+ it('paused agent id is in the activeAgentIds set passed to reapMergedWorktrees', async () => {
+ // agentDataCleanup calls readJSONFile once — for data/cos/state.json
+ readJSONFile.mockResolvedValueOnce({
+ agents: {
+ 'paused-agent-1': { status: 'paused' },
+ 'running-agent-2': { status: 'running' }
+ }
+ })
+
+ await agentDataCleanup()
+
+ expect(reapMergedWorktrees).toHaveBeenCalledOnce()
+ const [, opts] = reapMergedWorktrees.mock.calls[0]
+ expect(opts.activeAgentIds.has('paused-agent-1')).toBe(true)
+ })
+
+ it('paused agent id is in the set passed to cleanupOrphanedWorktrees', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ agents: {
+ 'paused-agent-1': { status: 'paused' },
+ 'running-agent-2': { status: 'running' }
+ }
+ })
+
+ await agentDataCleanup()
+
+ expect(cleanupOrphanedWorktrees).toHaveBeenCalledOnce()
+ const [, activeIds] = cleanupOrphanedWorktrees.mock.calls[0]
+ expect(activeIds.has('paused-agent-1')).toBe(true)
+ })
+
+ it('non-paused agent is NOT added to the protect set via state.json', async () => {
+ readJSONFile.mockResolvedValueOnce({
+ agents: {
+ 'paused-agent-1': { status: 'paused' },
+ 'running-agent-2': { status: 'running' }
+ }
+ })
+
+ await agentDataCleanup()
+
+ const [, opts] = reapMergedWorktrees.mock.calls[0]
+ // running-agent-2 is not paused and not in getActiveAgentIds() → NOT in protect set
+ expect(opts.activeAgentIds.has('running-agent-2')).toBe(false)
+ })
+
+ it('in-memory active agents are also protected alongside paused agents', async () => {
+ getActiveAgentIds.mockReturnValue(['live-agent-99'])
+ readJSONFile.mockResolvedValueOnce({
+ agents: { 'paused-agent-1': { status: 'paused' } }
+ })
+
+ await agentDataCleanup()
+
+ const [, opts] = reapMergedWorktrees.mock.calls[0]
+ expect(opts.activeAgentIds.has('paused-agent-1')).toBe(true)
+ expect(opts.activeAgentIds.has('live-agent-99')).toBe(true)
+ })
+
+ it('handles missing cosState gracefully (null state.json)', async () => {
+ readJSONFile.mockResolvedValueOnce(null)
+
+ await expect(agentDataCleanup()).resolves.not.toThrow()
+ expect(reapMergedWorktrees).toHaveBeenCalledOnce()
+ expect(cleanupOrphanedWorktrees).toHaveBeenCalledOnce()
+ })
+ })
})
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 1655356424..a88172e16d 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -73,6 +73,9 @@ export function pickCodeReviewDefaults(settings) {
let cachedDefaults = null
settingsEvents.on('settings:updated', () => { cachedDefaults = null })
+/** Test-only: reset the memoized defaults cache to its uninitialized sentinel. */
+export function __resetCodeReviewDefaultsCache() { cachedDefaults = null }
+
export async function getCodeReviewDefaults() {
if (cachedDefaults) return cachedDefaults
cachedDefaults = pickCodeReviewDefaults(await getSettings())
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index a5838dd417..8962c059c7 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -21,11 +21,13 @@ import {
pickCodeReviewDefaults,
getCodeReviewDefaults,
runLocalCodeReview,
+ __resetCodeReviewDefaultsCache,
} from './codeReview.js'
describe('codeReview helpers', () => {
afterEach(() => {
mockedSettings.current = {}
+ __resetCodeReviewDefaultsCache()
vi.restoreAllMocks()
})
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index b1153affcf..062be7e3a6 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -21,6 +21,7 @@ import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
+ deleteSyncBaseHash,
} from '../../lib/conflictJournal.js';
import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';
import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';
@@ -573,6 +574,7 @@ export async function pruneTombstonedSeries(beforeMs) {
const t = Date.parse(fresh.deletedAt || '');
if (!Number.isFinite(t) || t >= beforeMs) return false;
await s.deleteOneNow(id);
+ await deleteSyncBaseHash('series', id);
return true;
})
));
diff --git a/server/services/recordMerge.js b/server/services/recordMerge.js
index 60f32b234a..aeaad11ee2 100644
--- a/server/services/recordMerge.js
+++ b/server/services/recordMerge.js
@@ -30,7 +30,7 @@ import {
VARIATIONS_PER_CATEGORY_MAX, COMPOSITE_SHEETS_MAX, INFLUENCES_PER_LIST_MAX, IMAGE_REFS_PER_ENTRY_MAX,
} from './universeBuilder.js';
import { mergeExtractedBible, BIBLE_KIND } from '../lib/storyBible.js';
-import { canonicalStringify } from '../lib/objects.js';
+import { canonicalStringify, isEmptyScalar } from '../lib/objects.js';
import { getSeries, updateSeries, deleteSeries, listSeries } from './pipeline/series.js';
import { reassignIssuesToSeries, listIssues } from './pipeline/issues.js';
import {
@@ -177,9 +177,6 @@ const unionSeasons = (survivor = [], loser = []) => {
return out;
};
-const isEmptyScalar = (v) => v === null || v === undefined || (typeof v === 'string' && v.trim() === '')
- || (Array.isArray(v) && v.length === 0);
-
/**
* Resolve a set of scalar fields between survivor + loser.
* Returns `{ values, conflicts, autoResolved }`:
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 97237a0163..cbef791606 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -40,6 +40,7 @@ import { sanitizeOrigin } from '../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
+ deleteSyncBaseHash,
} from '../lib/conflictJournal.js';
import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';
import { renameCollectionForUniverse, unlinkCollectionsForUniverse } from './mediaCollections.js';
@@ -1494,6 +1495,7 @@ export async function pruneTombstonedUniverses(beforeMs) {
if (!Number.isFinite(t) || t >= beforeMs) return false;
const { rm } = await import('fs/promises');
await rm(s.recordDir(id), { recursive: true, force: true });
+ await deleteSyncBaseHash('universe', id);
return true;
})
));