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

test([add-emitrunstarted-hook-shape-test-to-runner]): pin emitRunStarted payload-flattening contract

[._.]/ Adam Eivy8a3a98ca0265
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9c17d6e183..6b714b5b2e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changed
+- **[add-emitrunstarted-hook-shape-test-to-runner] Pin `emitRunStarted` payload-flattening contract in `server/services/runner.test.js`.** The `provider?.name || provider?.id` and `model ?? provider?.defaultModel` fallbacks in `runner.js:198-204` previously had zero direct coverage — `tuiPromptRunner.js`'s PTY tests mock `emitRunStarted` itself, so a regression that dropped the `name` preference or flipped the model fallback from `??` to `||` (silently rewriting an intentionally-empty model to `defaultModel`) would have slipped past every test. New `describe('emitRunStarted — payload-flattening contract')` block in `runner.test.js` exports `emitRunStarted` from the module under test, registers a `runnerConfig.hooks.onRunStarted` mock via `setAIToolkit(fakeToolkit(), { hooks })`, and asserts the hook payload across 8 cases: `name`-preferred-over-`id`, `id` fallback when `name` is absent, explicit `model` overriding `defaultModel`, `defaultModel` fallback when `model` is `undefined`, `defaultModel` fallback when `model` is `null` (`??` semantics), empty-string `model` preserved (guards against a `||` regression), `provider: undefined` → both fields `undefined`, and the no-op path when no hook is registered. 43/43 runner tests pass (35 prior + 8 new).
+
- **[med-importer-server-services-importer-test-js-no] Pin `existingCanonBlock` dedupe wiring in importer service tests.** `server/services/importer.test.js` had no coverage for the `existingCanonBlock` argument that `analyzeImport` passes into the `importer-canon-extract` LLM call at `importer.js:472-479` — a refactor that dropped the arg or wired it to `null`/`''` would leave the canon-extract LLM blind to already-seeded characters / places / objects, and every second-pass import would silently re-extract duplicates. New `'wires existingCanonBlock into the canon-extract prompt for dedup on a second-pass import'` test in `analyzeImport`'s describe block seeds a universe with one character via `universeSvc.createUniverse` + `updateUniverse`, runs `analyzeImport` against the seeded universe name, looks up the `importer-canon-extract` call by stage name (defensive against future `Promise.all` scheduling changes vs. the brittle `calls[0]` shape from the PLAN ask), and asserts the seeded character name reaches `existingCanonBlock`. The lookup-by-stage-name is the only deviation from the PLAN ask's literal `calls[0][1]` shape — `analyzeImport` fires canon + arc via `Promise.all` and any future deferral / reorder would silently break the test. 46/46 importer tests pass.
- **[audit-remaining-getissue-prechecks-in-pipeline-routes] Audit of remaining `getIssue` prechecks in `pipeline.js`; music attach/delete routes drop the redundant read.** Followed up on the comic-cover consolidation by tracing each of the 10 sites cited in PLAN.md plus `:1427` found during the audit, so 11 sites total in `server/routes/pipeline.js`. Verdict: **8 stay, 2 drop, 1 keep-but-unbind**. **Drop** at `/issues/:id/stages/audio/music/attach` and `DELETE /issues/:id/stages/audio/music` — the only consumer was `audioStatusAfterMusicChange(issue)` (reads `issue.stages.audio.lines.length`), which now derives from `currentStage` inside `updateStageWithLatest`'s `computeFn` instead. Helper signature changed from `(issue) => …` to `(stage) => …`. **Keep-but-unbind** at `/issues/:id/stages/audio/music/upload` — the precheck must gate `importUploadedTrack` (a filesystem write) so a bad id doesn't orphan an imported file when the subsequent write 404s; the binding is dropped because the status computation now uses the freshest stage too. **Keep** at the other 8 sites because each route consumes issue data the called service can't supply: `extract-audio-lines` / `audio/lines/:lineIdx/render` / `storyboards/extract-scenes` / `comicPages/extract-pages` / `:stageId/extract-canon` all need `issue.seriesId` (or stage-locked guard against a sibling stage); `GET /issues/:id` IS the read; `comicPages/pages/:pageIndex/render` keeps the precheck-only-error-shape pageIndex bounds check (the inline comment explicitly justifies it as "avoids loading the bible context just to error out"); and `auto-run-text` keeps the precheck-only-error-shape sync 404 (the runner's IIFE is fire-and-forget, so without the precheck a bad id returns 200 with a runId that immediately errors out via SSE). Net: per-request `data/issues.json` reads on attach/delete music drop from 2 → 1, and the status computation moves from a stale snapshot to the freshest persisted state (eliminates a small TOCTOU window vs. a concurrent line edit). New tests pin the 404 status AND `PIPELINE_ISSUE_NOT_FOUND` error code for both refactored routes (the precheck-removal equivalence depends on the downstream not changing the error shape). 87/87 pipeline route tests pass; 6152/6152 server tests pass.
diff --git a/PLAN.md b/PLAN.md
index 7465b0e54e..78e2c4da99 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -15,7 +15,6 @@ _Nothing currently parked — pick the next item from the Backlog._
### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)
- [ ] [med-canon-server-services-canonusage-js-zero-test] **[MED][CANON]** `server/services/canonUsage.js` — zero test coverage for `getUniverseCanonUsage`. The "Appears-in sort: issueCount desc + alpha tiebreaker" invariant lives at line ~101 with no test. Add a `canonUsage.test.js`.
-- [ ] [add-emitrunstarted-hook-shape-test-to-runner] **[LOW][TESTS]** `server/services/runner.test.js` has no coverage for `emitRunStarted`'s payload shape — `runner.js:198-204` flattens `provider` to `provider?.name || provider?.id` and falls back `model ?? provider?.defaultModel`, but no test pins that contract. The `executeTuiRun` PTY tests intentionally mock `emitRunStarted`, so a regression in the flattening logic (e.g. dropping the `name` preference or breaking the model fallback) would slip past `tuiPromptRunner.test.js`. Add a focused test that registers a `runnerConfig.hooks.onRunStarted` mock, calls `emitRunStarted({ runId, provider, model })` with `{ name, id, defaultModel }` variants, and asserts the hook payload shape. Surfaced by codex review iter 1 during `[med-tests-no-direct-tests-for-executetuirun-pty]`; deferred because the scope of that PR was `executeTuiRun` (not `runner.js`), and the fix touches a different test file.
### Better-audit residue
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 57aba35a25..640de3ceaf 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -18,7 +18,7 @@ vi.mock('fs/promises', () => ({
const { spawn } = await import('child_process');
const runner = await import('./runner.js');
-const { setAIToolkit, executeCliRun, buildCliArgs, hasModelFlag, extractBakedModel } = runner;
+const { setAIToolkit, executeCliRun, buildCliArgs, hasModelFlag, extractBakedModel, emitRunStarted } = runner;
// Minimal toolkit stub that satisfies executeCliRun's expectations
function fakeToolkit() {
@@ -294,3 +294,97 @@ describe('extractBakedModel', () => {
expect(extractBakedModel(['--model', 'first', '-m', 'second'])).toBe('first');
});
});
+
+// emitRunStarted's payload-flattening contract is consumed by tuiPromptRunner.js
+// (and any future non-toolkit execution path) — the TUI tests mock emitRunStarted
+// itself, so this is the only place the `name || id` and `model ?? defaultModel`
+// fallbacks are pinned. A regression here would silently break run-tracking
+// attribution without any other suite catching it.
+describe('emitRunStarted — payload-flattening contract', () => {
+ function captureHook() {
+ const onRunStarted = vi.fn();
+ setAIToolkit(fakeToolkit(), { dataDir: '/tmp/test-runner', hooks: { onRunStarted } });
+ return onRunStarted;
+ }
+
+ it('prefers provider.name over provider.id when both are present', () => {
+ const onRunStarted = captureHook();
+ emitRunStarted({
+ runId: 'r1',
+ provider: { name: 'codex', id: 'codex-id', defaultModel: 'gpt-5' },
+ model: 'gpt-4o',
+ });
+ expect(onRunStarted).toHaveBeenCalledWith({ runId: 'r1', provider: 'codex', model: 'gpt-4o' });
+ });
+
+ it('falls back to provider.id when provider.name is missing', () => {
+ const onRunStarted = captureHook();
+ emitRunStarted({
+ runId: 'r2',
+ provider: { id: 'gemini-cli', defaultModel: 'gemini-2.5-pro' },
+ model: 'gemini-2.0-flash',
+ });
+ expect(onRunStarted).toHaveBeenCalledWith({ runId: 'r2', provider: 'gemini-cli', model: 'gemini-2.0-flash' });
+ });
+
+ it('uses the explicit model argument when given (overrides provider.defaultModel)', () => {
+ const onRunStarted = captureHook();
+ emitRunStarted({
+ runId: 'r3',
+ provider: { name: 'claude-code', defaultModel: 'claude-opus-4-7' },
+ model: 'claude-sonnet-4-6',
+ });
+ expect(onRunStarted).toHaveBeenCalledWith({ runId: 'r3', provider: 'claude-code', model: 'claude-sonnet-4-6' });
+ });
+
+ it('falls back to provider.defaultModel when model is undefined', () => {
+ const onRunStarted = captureHook();
+ emitRunStarted({
+ runId: 'r4',
+ provider: { name: 'codex', defaultModel: 'codex-configured-default' },
+ model: undefined,
+ });
+ expect(onRunStarted).toHaveBeenCalledWith({
+ runId: 'r4',
+ provider: 'codex',
+ model: 'codex-configured-default',
+ });
+ });
+
+ it('falls back to provider.defaultModel when model is null (?? semantics)', () => {
+ const onRunStarted = captureHook();
+ emitRunStarted({
+ runId: 'r5',
+ provider: { name: 'codex', defaultModel: 'o4-mini' },
+ model: null,
+ });
+ expect(onRunStarted).toHaveBeenCalledWith({ runId: 'r5', provider: 'codex', model: 'o4-mini' });
+ });
+
+ it('keeps an empty-string model rather than falling back (?? treats "" as defined)', () => {
+ // Guards the ?? semantics — if this ever flips to ||, intentionally-empty
+ // models would be silently rewritten to defaultModel.
+ const onRunStarted = captureHook();
+ emitRunStarted({
+ runId: 'r6',
+ provider: { name: 'codex', defaultModel: 'o4-mini' },
+ model: '',
+ });
+ expect(onRunStarted).toHaveBeenCalledWith({ runId: 'r6', provider: 'codex', model: '' });
+ });
+
+ it('emits undefined provider/model when provider is missing entirely', () => {
+ const onRunStarted = captureHook();
+ emitRunStarted({ runId: 'r7', provider: undefined, model: undefined });
+ expect(onRunStarted).toHaveBeenCalledWith({ runId: 'r7', provider: undefined, model: undefined });
+ });
+
+ it('is a no-op when no onRunStarted hook is registered', () => {
+ setAIToolkit(fakeToolkit(), { dataDir: '/tmp/test-runner' });
+ expect(() => emitRunStarted({
+ runId: 'r8',
+ provider: { name: 'codex', defaultModel: 'o4-mini' },
+ model: 'gpt-4',
+ })).not.toThrow();
+ });
+});