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

feat([issue-1627]): inter-check context sharing within an editorial run

[._.]/ Adam Eivybcfb092c17b4
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index de9be0245e..1cc2d03e09 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -76,6 +76,31 @@ both win when budget is tight. A single-chunk (whole-fits) run never summarizes,
so it pays nothing. When the reverse-outline (#1349) or continuity-bible (#1305)
artifacts land, either could feed this context more cheaply than a per-chunk call.
+## Inter-check context sharing (#1627)
+
+Within a single pass a check can read the findings produced by **other checks it
+explicitly depends on**, so compound signals are possible (e.g. on-the-nose
+dialogue that is *also* doing exposition for a setup another check flagged). The
+sharing is **opt-in and scoped**, which keeps every other check a pure function of
+its declared `sources` (order-independent):
+
+- A check declares `dependsOn: ['<otherCheckId>', …]` on its registry entry. The
+ runner topologically orders the pass (`orderChecksByDependencies`) so every
+ declared dependency runs **before** the dependent — independent checks keep their
+ exact registry order, so a pass where nothing opts in is unchanged.
+- During its `run(ctx)`, the dependent reads `ctx.priorFindings` — the stamped
+ findings (each carrying `checkId`) that its declared dependencies produced earlier
+ this pass — or `ctx.findingsByCheck('<id>')` for a single dependency's findings.
+ Both are **scoped to declared deps only**: a check that declares no `dependsOn`
+ always sees an empty `ctx.priorFindings`, and `findingsByCheck` returns `[]` for
+ any id the check didn't declare. The array and each finding are **frozen** — a
+ check may read but never mutate another check's already-seeded findings.
+- Degrade-tolerant: a dependency that is disabled, outside a targeted subset run, or
+ errored this pass simply contributes no findings (the dependent still runs). A
+ dependency **cycle** is a registry bug — it's logged and the cycle's members fall
+ back to registry order. The dependent must therefore tolerate missing prior
+ findings. `dependsOn` shape (string-array, no self-reference) is enforced at load.
+
## Discovery rule
Before adding an editorial rule, check whether an existing registry entry covers
@@ -151,7 +176,7 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| Module | Purpose |
|---|---|
-| `checkRegistry.js` | `EDITORIAL_CHECKS` array + `EDITORIAL_SOURCES` (the per-check `sources` vocabulary the staleness runner fingerprints, #1387) + fail-fast guards + lookup/state helpers (`getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`). User-defined-check helpers (`buildCustomCheck`, `buildCustomCheckPrompt`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). Ships two reference checks: `naming.dissimilar-names` (deterministic) and `prose.info-dumping` (LLM). |
+| `checkRegistry.js` | `EDITORIAL_CHECKS` array + `EDITORIAL_SOURCES` (the per-check `sources` vocabulary the staleness runner fingerprints, #1387) + fail-fast guards + lookup/state helpers (`getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`, `orderChecksByDependencies` (the dependency topo-sort, #1627)). User-defined-check helpers (`buildCustomCheck`, `buildCustomCheckPrompt`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). Ships two reference checks: `naming.dissimilar-names` (deterministic) and `prose.info-dumping` (LLM). |
| `nameSimilarity.js` | Pure, dependency-free name-confusability primitives for `naming.dissimilar-names` (#1291): `normalizeName`, `vowelSkeleton`, `soundex` (phonetic key), `levenshtein` (edit distance), `nameSimilaritySignals` (the per-pair signal list, with option toggles), and `firstLetterHistogram` / `findFirstLetterClusters` (cast first-letter crowding). |
| `cliches.js` | Pure, dependency-free cliché + overwriting primitives for `prose.cliches` and `prose.modifier-stacking` (#1308): `CLICHE_PHRASES` (seed stock-simile/idiom list), `findCliches` (whole-word phrase scan with house-style allow/extra lists), and `findModifierStacking` (cumulative no-comma runs of 3+ stacked adjectives/adverbs). The LLM sibling `prose.dead-metaphor` handles the judgment cases (mixed/dead metaphor, novel clichés, purple prose). |
| `italicThoughts.js` | Pure, dependency-free italic-thought primitive for `prose.italic-thoughts` (#1300): `findItalicThoughts` (multi-word markdown `*…*` / `_…_` italic runs, dedup + word-count threshold so single-word emphasis, bold, and `snake_case` are skipped). The LLM siblings (`opening.wrong-start`, `prose.mirror-description`, `dialogue.pleasantries`, `prose.kill-your-darlings`) handle the judgment cases in the #1300 anti-pattern bundle. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 1286bc54aa..af1b522384 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -6291,6 +6291,21 @@ export function assertValidChecks(checks) {
}
}
}
+ // `dependsOn` (#1627) is optional: an array of OTHER check ids whose findings
+ // this check reads from `ctx.priorFindings`. The runner topologically orders the
+ // pass so a declared dependency runs first; a check sees ONLY the findings of
+ // the checks it lists here (everything else stays order-independent). Shape is
+ // validated at load; the *referenced* ids are NOT — a dependency on a disabled,
+ // unknown, or not-yet-loaded (custom) check is tolerated at run time (the
+ // dependent just runs without those findings). A self-reference is meaningless.
+ if (check.dependsOn !== undefined) {
+ if (!Array.isArray(check.dependsOn) || check.dependsOn.some((d) => typeof d !== 'string' || !d)) {
+ throw new Error(`checkRegistry: ${check.id} dependsOn must be an array of check-id strings`);
+ }
+ if (check.dependsOn.includes(check.id)) {
+ throw new Error(`checkRegistry: ${check.id} cannot depend on itself`);
+ }
+ }
if (seen.has(check.id)) throw new Error(`checkRegistry: duplicate id ${check.id}`);
seen.add(check.id);
}
@@ -6447,6 +6462,77 @@ export function applySeriesCheckConfig(enabled, seriesOverrides) {
});
}
+/**
+ * Stable topological ordering of enabled check pairs by their declared
+ * `dependsOn` (#1627). A check that names another *enabled* check in `dependsOn`
+ * is emitted AFTER it, so when the runner injects a dependency's findings into the
+ * dependent's `ctx.priorFindings` the dependency has already run this pass. Checks
+ * that declare no dependencies keep their exact registry order (stable) — so a run
+ * where nothing opts in is byte-identical to before this existed.
+ *
+ * Robustness:
+ * - A dependency on a check ABSENT from `pairs` (disabled, or outside a targeted
+ * subset run) is ignored — the dependent still runs, just without those findings
+ * (the runner's injection is likewise degrade-tolerant).
+ * - A dependency CYCLE (or a chain that transitively waits on one) can't be
+ * ordered; rather than drop a check or spin forever, the still-unplaced members
+ * are flushed in registry order and the cycle is logged once. The runner then
+ * simply can't guarantee a cyclic dependency's findings are present — acceptable,
+ * since a cycle is a registry bug a human must fix.
+ *
+ * Pure + side-effect-free (aside from the one cycle warning). O(n²) over the
+ * enabled set, which is tiny (≈ the registry size).
+ *
+ * @param {Array<{check: object}>} pairs enabled pairs (from getEnabledChecks / applySeriesCheckConfig)
+ * @returns {Array<{check: object}>} the same pairs, dependency-ordered
+ */
+export function orderChecksByDependencies(pairs) {
+ if (!Array.isArray(pairs)) return [];
+ if (pairs.length < 2) return pairs.slice();
+ // Only deps actually present in this run gate ordering — an absent dep can't be
+ // waited on (and would otherwise wedge the dependent forever).
+ const present = new Set();
+ for (const p of pairs) { const id = p?.check?.id; if (typeof id === 'string') present.add(id); }
+ const waits = pairs.map((p) => {
+ const id = p?.check?.id;
+ const declared = Array.isArray(p?.check?.dependsOn) ? p.check.dependsOn : [];
+ return new Set(declared.filter((d) => typeof d === 'string' && d !== id && present.has(d)));
+ });
+ const used = new Array(pairs.length).fill(false);
+ const emitted = new Set();
+ const result = [];
+ while (result.length < pairs.length) {
+ // Kahn's algorithm, but always take the LOWEST registry index among the ready
+ // nodes — that's what makes the sort stable (independent checks never move).
+ let pick = -1;
+ for (let i = 0; i < pairs.length; i += 1) {
+ if (used[i]) continue;
+ let ready = true;
+ for (const dep of waits[i]) { if (!emitted.has(dep)) { ready = false; break; } }
+ if (ready) { pick = i; break; }
+ }
+ if (pick === -1) {
+ // No ready node ⇒ every remaining node waits on another remaining node: a
+ // cycle. Flush the rest in registry order so nothing is dropped.
+ const stuck = [];
+ for (let i = 0; i < pairs.length; i += 1) {
+ if (used[i]) continue;
+ used[i] = true;
+ result.push(pairs[i]);
+ const id = pairs[i]?.check?.id;
+ if (typeof id === 'string') { emitted.add(id); stuck.push(id); }
+ }
+ console.warn(`⚠️ editorial check dependency cycle — running in registry order: ${stuck.join(', ')}`);
+ break;
+ }
+ used[pick] = true;
+ result.push(pairs[pick]);
+ const id = pairs[pick]?.check?.id;
+ if (typeof id === 'string') emitted.add(id);
+ }
+ return result;
+}
+
// ---------------------------------------------------------------------------
// User-defined checks (#1346) — definition storage + synthesis.
//
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 9fac5cdf66..51a0836aa5 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { z } from 'zod';
import {
EDITORIAL_CHECKS,
@@ -13,6 +13,7 @@ import {
resolveCheckSeverity,
getEnabledChecks,
applySeriesCheckConfig,
+ orderChecksByDependencies,
buildCustomCheck,
buildCustomCheckPrompt,
isValidCustomCheckDef,
@@ -5102,3 +5103,74 @@ describe('cast.representation-balance — deterministic check (#1312)', () => {
expect(runRep({ characters: [{}, { name: '' }] }, { sections: [sec(1, 'x')] })).toEqual([]);
});
});
+
+// Inter-check context sharing — dependency ordering (#1627).
+describe('orderChecksByDependencies (#1627)', () => {
+ // A pair is just `{ check: { id, dependsOn? } }` here — ordering reads only those.
+ const pair = (id, dependsOn) => ({ check: dependsOn ? { id, dependsOn } : { id } });
+ const ids = (pairs) => pairs.map((p) => p.check.id);
+
+ it('keeps registry order when no check declares a dependency (stable, identity)', () => {
+ const input = [pair('a'), pair('b'), pair('c')];
+ expect(ids(orderChecksByDependencies(input))).toEqual(['a', 'b', 'c']);
+ });
+
+ it('emits a declared dependency BEFORE the dependent even when registry order is reversed', () => {
+ // b depends on a, but is listed first — a must be pulled ahead of b.
+ const out = orderChecksByDependencies([pair('b', ['a']), pair('a'), pair('c')]);
+ expect(ids(out).indexOf('a')).toBeLessThan(ids(out).indexOf('b'));
+ // c (independent) stays in its relative slot — only b waited on something.
+ expect(ids(out)).toEqual(['a', 'b', 'c']);
+ });
+
+ it('orders a transitive chain c→b→a so every dependency precedes its dependent', () => {
+ const out = ids(orderChecksByDependencies([pair('c', ['b']), pair('b', ['a']), pair('a')]));
+ expect(out.indexOf('a')).toBeLessThan(out.indexOf('b'));
+ expect(out.indexOf('b')).toBeLessThan(out.indexOf('c'));
+ });
+
+ it('ignores a dependency that is absent from the run (disabled / subset) and still runs the dependent', () => {
+ // b depends on z, which isn't in the enabled set — b still runs, order preserved.
+ const out = orderChecksByDependencies([pair('a'), pair('b', ['z'])]);
+ expect(ids(out)).toEqual(['a', 'b']);
+ });
+
+ it('breaks a dependency cycle by falling back to registry order without throwing or spinning', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const out = orderChecksByDependencies([pair('a', ['b']), pair('b', ['a']), pair('c')]);
+ // c (independent) is placed; the cyclic a/b are flushed in registry order.
+ expect(ids(out).sort()).toEqual(['a', 'b', 'c']);
+ expect(out).toHaveLength(3);
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('returns a copy for trivial inputs and never mutates the caller array', () => {
+ expect(orderChecksByDependencies([])).toEqual([]);
+ const one = [pair('a')];
+ const out = orderChecksByDependencies(one);
+ expect(out).not.toBe(one);
+ expect(ids(out)).toEqual(['a']);
+ expect(orderChecksByDependencies(null)).toEqual([]);
+ });
+});
+
+// dependsOn shape is validated at registry load (#1627).
+describe('assertValidChecks — dependsOn shape (#1627)', () => {
+ const base = {
+ id: 'x.test', label: 'X', scope: 'series', kind: 'deterministic', category: 'c',
+ severityDefault: 'low', run: () => [], configSchema: z.object({}), sources: ['canon'],
+ };
+ it('accepts an absent or string-array dependsOn', () => {
+ expect(() => assertValidChecks([base])).not.toThrow();
+ expect(() => assertValidChecks([{ ...base, dependsOn: ['naming.dissimilar-names'] }])).not.toThrow();
+ });
+ it('rejects a non-array or non-string-element dependsOn', () => {
+ expect(() => assertValidChecks([{ ...base, dependsOn: 'a' }])).toThrow(/dependsOn must be an array/);
+ expect(() => assertValidChecks([{ ...base, dependsOn: [1] }])).toThrow(/dependsOn must be an array/);
+ expect(() => assertValidChecks([{ ...base, dependsOn: [''] }])).toThrow(/dependsOn must be an array/);
+ });
+ it('rejects a self-reference', () => {
+ expect(() => assertValidChecks([{ ...base, dependsOn: ['x.test'] }])).toThrow(/cannot depend on itself/);
+ });
+});
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index f67b43794a..f09d23199d 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -19,7 +19,7 @@ import { randomUUID, createHash } from 'crypto';
import { createSseRunner } from '../../../lib/sseUtils.js';
import { runStagedLLM, runInlineLLM, runStageScopedInlineLLM, resolveStageContext } from '../../../lib/stageRunner.js';
import { planManuscriptPass, fitContextToManuscriptFloor, estimateTokens, MANUSCRIPT_FLOOR_TOKENS } from '../../../lib/contextBudget.js';
-import { getEnabledChecks, getEnabledCheckRows, getAllChecks, applySeriesCheckConfig, buildCustomCheck, CUSTOM_CHECK_ID_PREFIX, EDITORIAL_SOURCES, comicLetteringIssues, proseStageIssues } from '../../../lib/editorial/index.js';
+import { getEnabledChecks, getEnabledCheckRows, getAllChecks, applySeriesCheckConfig, orderChecksByDependencies, buildCustomCheck, CUSTOM_CHECK_ID_PREFIX, EDITORIAL_SOURCES, comicLetteringIssues, proseStageIssues } from '../../../lib/editorial/index.js';
import { getSettings } from '../../settings.js';
import { getSeries } from '../series.js';
import { listIssuesForSeries } from '../issues.js';
@@ -316,6 +316,22 @@ function fingerprintForCheck(check, resolved) {
return sha256(segments.join(HASH_SEP));
}
+// Inter-check context sharing (#1627). Build the read-only `ctx.priorFindings` a
+// check sees: the stamped findings produced EARLIER this pass by the checks it
+// named in `dependsOn`. Scoped to declared deps so a non-declaring check always
+// gets the shared EMPTY array (fully order-independent — identical to pre-#1627
+// behavior), and a check can only couple to a prior check it explicitly depended
+// on. Frozen — the array AND each finding (shallow) — so a check reads but can't
+// mutate the shared accumulator or another check's already-seeded finding.
+const EMPTY_PRIOR_FINDINGS = Object.freeze([]);
+export function buildScopedPriorFindings(findings, dependsOn) {
+ const deps = Array.isArray(dependsOn) ? dependsOn : [];
+ if (!deps.length || !Array.isArray(findings) || !findings.length) return EMPTY_PRIOR_FINDINGS;
+ const want = new Set(deps);
+ const scoped = findings.filter((f) => want.has(f?.checkId)).map((f) => Object.freeze({ ...f }));
+ return scoped.length ? Object.freeze(scoped) : EMPTY_PRIOR_FINDINGS;
+}
+
// Output room reserved for an editorial check's findings JSON. Sized for the
// editorial output (a bounded findings list — far smaller than the completeness
// pass's full-page rewrites), NOT the 8_000-token contextBudget default: that
@@ -564,6 +580,11 @@ export async function runEditorialChecks(seriesId, options = {}) {
// resolved config. The `needs*` gates inside the builder read only `check`
// (config-independent); only the run loop consumes the merged config here.
const enabledResolved = applySeriesCheckConfig(enabled, series?.editorialCheckConfig);
+ // Order the pass so a check's declared dependencies (#1627) run before it — the
+ // runner injects each dependency's findings into the dependent's
+ // `ctx.priorFindings`, so they must already be in the `findings` accumulator.
+ // A pass where nothing declares `dependsOn` keeps the exact registry order.
+ const enabledOrdered = orderChecksByDependencies(enabledResolved);
const findings = [];
const perCheck = [];
@@ -578,7 +599,7 @@ export async function runEditorialChecks(seriesId, options = {}) {
// didn't run (which would silently clear an unrelated check's active pin).
const ranCheckIds = new Set();
let canceled = false;
- for (const { check, config, severityOverride } of enabledResolved) {
+ for (const { check, config, severityOverride } of enabledOrdered) {
if (signal?.aborted) { canceled = true; break; }
onProgress?.({ type: 'check:start', checkId: check.id, label: check.label });
// Run every check with its NATIVE default severity (#1596). A per-check
@@ -587,7 +608,22 @@ export async function runEditorialChecks(seriesId, options = {}) {
// preserved as `nativeSeverity` — which lets a later "reset to Default"
// restore the true native level on carried findings (even ones that don't
// re-surface).
- const ctx = { ...baseCtx, config, severityDefault: check.severityDefault };
+ // Inter-check context sharing (#1627): a check that declares `dependsOn` reads
+ // the findings its dependencies produced EARLIER this pass via
+ // `ctx.priorFindings` (scoped to declared deps only — a check with no
+ // `dependsOn` always gets the empty array and stays a pure function of its
+ // sources). `orderChecksByDependencies` above guarantees the deps already ran,
+ // so their stamped findings are in `findings`.
+ const priorFindings = buildScopedPriorFindings(findings, check.dependsOn);
+ const ctx = {
+ ...baseCtx,
+ config,
+ severityDefault: check.severityDefault,
+ priorFindings,
+ // Read a single dependency's findings by id — still scoped, so it returns []
+ // for a check NOT named in `dependsOn`, enforcing the explicit contract.
+ findingsByCheck: (checkId) => priorFindings.filter((f) => f.checkId === checkId),
+ };
// Boundary try/catch: a check's run() calls into arbitrary logic / LLM
// providers — one bad check must not abort the whole pass (mirrors the
// per-comment fix guard in seriesAutopilot.runEditorial).
@@ -727,7 +763,9 @@ export async function previewCustomCheck(seriesId, def, { providerOverride, mode
// Validate the (optional) per-run cap through the check's own config schema so
// an out-of-range value falls back to the default rather than flooding.
const config = check.configSchema.parse(Number.isInteger(maxFindings) ? { maxFindings } : {});
- const ctx = { ...baseCtx, config, severityDefault: check.severityDefault };
+ // A preview runs one check in isolation — there are no prior findings, but expose
+ // the same ctx shape (#1627) so a draft whose run() references them never crashes.
+ const ctx = { ...baseCtx, config, severityDefault: check.severityDefault, priorFindings: EMPTY_PRIOR_FINDINGS, findingsByCheck: () => [] };
if (typeof check.gate === 'function' && !check.gate(ctx)) {
return { findings: [], skipped: true, invalid: false };
diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.js
index c181f6a799..74a05e0308 100644
--- a/server/services/pipeline/editorial/checkRunner.test.js
+++ b/server/services/pipeline/editorial/checkRunner.test.js
@@ -76,7 +76,7 @@ vi.mock('../reverseOutline.js', () => ({ getReverseOutline: vi.fn(async () => ou
let editorialState = { characters: [] };
vi.mock('../editorialAnalysis.js', () => ({ getSeriesEditorial: vi.fn(async () => editorialState) }));
-const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, summarizeCheckErrors, previewCustomCheck } = await import('./checkRunner.js');
+const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, summarizeCheckErrors, previewCustomCheck, buildScopedPriorFindings } = await import('./checkRunner.js');
const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');
const { collectManuscriptSections } = await import('../arcPlanner.js');
const { getSeriesCanon } = await import('../seriesCanon.js');
@@ -1000,3 +1000,74 @@ describe('enabledChecksConsumeReverseOutline (#1349)', () => {
expect(enabledChecksConsumeReverseOutline(settings)).toBe(false);
});
});
+
+// Inter-check context sharing (#1627) — dependency-scoped prior findings in ctx.
+describe('buildScopedPriorFindings (#1627)', () => {
+ const findings = [
+ { checkId: 'a', problem: 'x' }, { checkId: 'b', problem: 'y' }, { checkId: 'a', problem: 'z' },
+ ];
+ it('returns the shared empty (frozen) array when no deps are declared', () => {
+ const out = buildScopedPriorFindings(findings, []);
+ expect(out).toEqual([]);
+ expect(Object.isFrozen(out)).toBe(true);
+ expect(buildScopedPriorFindings(findings, undefined)).toEqual([]);
+ });
+ it('returns only the findings produced by the declared dependency ids', () => {
+ const out = buildScopedPriorFindings(findings, ['a']);
+ expect(out.map((f) => f.problem)).toEqual(['x', 'z']);
+ expect(out.every((f) => f.checkId === 'a')).toBe(true);
+ });
+ it('freezes the array AND each finding so a check can not mutate the accumulator', () => {
+ const out = buildScopedPriorFindings(findings, ['a', 'b']);
+ expect(Object.isFrozen(out)).toBe(true);
+ expect(out.every((f) => Object.isFrozen(f))).toBe(true);
+ expect(() => { out.push({}); }).toThrow();
+ });
+ it('returns empty when the accumulator holds nothing from the declared deps', () => {
+ expect(buildScopedPriorFindings(findings, ['zzz'])).toEqual([]);
+ expect(buildScopedPriorFindings([], ['a'])).toEqual([]);
+ });
+});
+
+describe('runEditorialChecks — ctx.priorFindings injection (#1627)', () => {
+ // The runner resolves checks from the LIVE registry objects, so we temporarily
+ // attach `dependsOn` / replace `run` on a real check and restore in `finally`.
+ const captureCtxFor = async (id, { dependsOn } = {}) => {
+ const check = getCheck(id);
+ const originalRun = check.run;
+ const hadDeps = Object.prototype.hasOwnProperty.call(check, 'dependsOn');
+ const originalDeps = check.dependsOn;
+ let ctx = null;
+ if (dependsOn) check.dependsOn = dependsOn;
+ check.run = vi.fn((c) => { ctx = c; return []; });
+ try {
+ await runEditorialChecks('s1');
+ } finally {
+ check.run = originalRun;
+ if (hadDeps) check.dependsOn = originalDeps; else delete check.dependsOn;
+ }
+ return ctx;
+ };
+
+ it('feeds a declared dependency\'s findings to the dependent (ordered + scoped + frozen)', async () => {
+ // info-dumping (LLM) declares it depends on naming (deterministic). The topo
+ // sort runs naming first, so its Alina/Alana findings are visible here.
+ const ctx = await captureCtxFor('prose.info-dumping', { dependsOn: ['naming.dissimilar-names'] });
+ expect(ctx, 'dependent ran').toBeTruthy();
+ expect(Array.isArray(ctx.priorFindings)).toBe(true);
+ expect(ctx.priorFindings.length).toBeGreaterThan(0);
+ expect(ctx.priorFindings.every((f) => f.checkId === 'naming.dissimilar-names')).toBe(true);
+ expect(Object.isFrozen(ctx.priorFindings)).toBe(true);
+ // findingsByCheck is scoped to declared deps: the declared id resolves, an
+ // undeclared id returns [] even if that check ran.
+ expect(ctx.findingsByCheck('naming.dissimilar-names').length).toBe(ctx.priorFindings.length);
+ expect(ctx.findingsByCheck('some.undeclared')).toEqual([]);
+ });
+
+ it('gives a check with no dependsOn an empty priorFindings even when earlier checks found things', async () => {
+ const ctx = await captureCtxFor('prose.info-dumping');
+ expect(ctx).toBeTruthy();
+ expect(ctx.priorFindings).toEqual([]);
+ expect(ctx.findingsByCheck('naming.dissimilar-names')).toEqual([]);
+ });
+});