clearotron 0.7.0-beta.2 → 0.7.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/INSTALL.md +5 -5
  2. package/QUICKSTART.md +4 -4
  3. package/README.md +2 -2
  4. package/bin/README.md +3 -4
  5. package/bin/clearotron.mjs +1 -1
  6. package/bin/onboard.mjs +28 -40
  7. package/bin/status.mjs +11 -0
  8. package/build-info.json +2 -2
  9. package/docs/DELIVERY.md +30 -6
  10. package/docs/architecture/04-configuration-reference.md +1 -0
  11. package/driver/CHANGELOG.md +34 -0
  12. package/driver/compose-read.mjs +4 -3
  13. package/driver/contract-arm2-baseline.json +1 -2
  14. package/driver/contract-dictation-registry.mjs +7 -48
  15. package/driver/contract-e3-backlog.mjs +55 -52
  16. package/driver/contract-e3-baseline.json +22 -7
  17. package/driver/contract-vocabulary.mjs +4 -2
  18. package/driver/coverage-form.mjs +4 -0
  19. package/driver/coverage-rows-run.mjs +68 -4
  20. package/driver/engine/anthropic-agent.mjs +10 -13
  21. package/driver/engine/common.mjs +34 -22
  22. package/driver/engine/health.mjs +251 -0
  23. package/driver/engine/jx-turn.mjs +2 -1
  24. package/driver/engine/mcp/codex-config.mjs +16 -1
  25. package/driver/engine/mcp/crowd-note.mjs +1 -1
  26. package/driver/engine/mcp/gather-config.mjs +34 -9
  27. package/driver/engine/mcp/perplexity-server.mjs +33 -23
  28. package/driver/engine/mcp/recording-server.mjs +67 -58
  29. package/driver/engine/mcp/unit-note-server.mjs +2 -0
  30. package/driver/engine/openai-agent.mjs +9 -24
  31. package/driver/engine/probe.mjs +24 -7
  32. package/driver/findings-model.mjs +54 -0
  33. package/driver/jx-units.mjs +139 -30
  34. package/driver/knockout-assess-record.mjs +2 -2
  35. package/driver/knockout-correction-check.mjs +119 -0
  36. package/driver/knockout-correction-record.mjs +1 -1
  37. package/driver/knockout-frame-record.mjs +24 -10
  38. package/driver/knockout-review-record.mjs +35 -430
  39. package/driver/ladder/dispatch.mjs +4 -2
  40. package/driver/ladder/form-repair.mjs +5 -5
  41. package/driver/ladder/form-sync.mjs +4 -6
  42. package/driver/ladder/next-rung.mjs +10 -0
  43. package/driver/ladder/repair-messages.mjs +37 -65
  44. package/driver/ladder/stage.mjs +3 -3
  45. package/driver/ladder/turn-signals.mjs +4 -14
  46. package/driver/manual-paragraphs.mjs +22 -2
  47. package/driver/mark-logos.mjs +25 -9
  48. package/driver/package.json +1 -1
  49. package/driver/pipeline-knockout.mjs +2 -2
  50. package/driver/predelivery-lint.mjs +39 -7
  51. package/driver/product-fault.mjs +53 -0
  52. package/driver/publish/knockout.mjs +2 -1
  53. package/driver/publish/register-record-html.mjs +7 -9
  54. package/driver/publish/register-record.mjs +0 -1
  55. package/driver/publish/render.mjs +16 -10
  56. package/driver/publish/strings.mjs +0 -1
  57. package/driver/publish/templates/knockout.css +1 -1
  58. package/driver/publish/templates/report.css +2 -4
  59. package/driver/recording-agreement.mjs +6 -4
  60. package/driver/register-band-run.mjs +2 -2
  61. package/driver/register-digest-record.mjs +31 -9
  62. package/driver/register-unit-record.mjs +10 -1
  63. package/driver/repair-composers.mjs +12 -11
  64. package/driver/repair-contract.mjs +6 -6
  65. package/driver/repair-targets.mjs +7 -6
  66. package/driver/run-outcome.mjs +8 -0
  67. package/driver/runner.mjs +42 -3
  68. package/driver/skills/README.md +5 -4
  69. package/driver/skills/blind-frame/SKILL.md +1 -1
  70. package/driver/skills/case-law-citation/SKILL.md +1 -1
  71. package/driver/skills/clearance-common-law/SKILL.md +6 -423
  72. package/driver/skills/clearance-common-law/grid.md +272 -0
  73. package/driver/skills/clearance-common-law/meaning.md +142 -0
  74. package/driver/skills/clearance-common-law/perplexity-prompts.md +4 -2
  75. package/driver/skills/clearance-register/SKILL.md +7 -174
  76. package/driver/skills/clearance-register/digest.md +89 -25
  77. package/driver/skills/clearance-register/providers/clarivate-questions.md +154 -0
  78. package/driver/skills/clearance-register/providers/clarivate.md +5 -149
  79. package/driver/skills/clearance-register/providers/signa-questions.md +120 -0
  80. package/driver/skills/clearance-register/providers/signa.md +3 -114
  81. package/driver/skills/clearance-register/providers/uspto-local.md +3 -3
  82. package/driver/skills/clearance-register/register-recipes.md +10 -10
  83. package/driver/skills/clearance-register/status-rules.md +2 -2
  84. package/driver/skills/clearance-register/unit.md +96 -54
  85. package/driver/skills/clearance-search/delivery-contract.md +11 -49
  86. package/driver/skills/clearance-search/firm-wide-reasoning.md +10 -13
  87. package/driver/skills/clearance-search/look-at-what-you-have.md +7 -0
  88. package/driver/skills/clearance-search/phase2-execution.md +12 -117
  89. package/driver/skills/clearance-search/report-card-rules.md +2 -2
  90. package/driver/skills/clearance-search/report-prose.md +30 -23
  91. package/driver/skills/clearance-search/synthesis-rules.md +27 -69
  92. package/driver/skills/clearance-search/worked-examples.md +11 -16
  93. package/driver/skills/clearance-variants/SKILL.md +7 -7
  94. package/driver/skills/clearance-variants/transliteration-scripts.md +2 -2
  95. package/driver/skills/frame-diff/SKILL.md +1 -1
  96. package/driver/skills/knockout-assess/SKILL.md +54 -41
  97. package/driver/skills/knockout-frame/SKILL.md +13 -12
  98. package/driver/skills/knockout-register-read/SKILL.md +2 -10
  99. package/driver/skills/matter-frame/SKILL.md +2 -2
  100. package/driver/skills/narrative-refutation/SKILL.md +7 -6
  101. package/driver/skills/placement-inquiry/SKILL.md +3 -3
  102. package/driver/skills/skeptic/SKILL.md +111 -0
  103. package/driver/skills/whatif-memo/SKILL.md +5 -2
  104. package/driver/stage-declarations.mjs +6 -0
  105. package/driver/stages-knockout.mjs +36 -38
  106. package/driver/stages.mjs +69 -64
  107. package/driver/steps/delivery.mjs +6 -4
  108. package/driver/steps/open-run.mjs +2 -0
  109. package/driver/steps/overview-and-cards.mjs +2 -2
  110. package/driver/steps/register-sweep.mjs +20 -1
  111. package/driver/steps/synthesis.mjs +28 -11
  112. package/driver/suite-census.json +217 -61
  113. package/driver/synthesis-record.mjs +24 -2
  114. package/driver/verify-knockout.mjs +23 -3
  115. package/driver/whatif-memo-run.mjs +39 -10
  116. package/driver/whatif-queue.mjs +53 -7
  117. package/mcp-server/CHANGELOG.md +8 -0
  118. package/mcp-server/lib/ops.mjs +19 -10
  119. package/mcp-server/lib/whatif.mjs +7 -6
  120. package/mcp-server/package.json +1 -1
  121. package/mcp-server/server.mjs +55 -19
  122. package/package.json +1 -1
  123. package/portal-ui/package.json +1 -1
  124. package/providers/clarivate/src/adapter.js +3 -0
  125. package/providers/jx/src/nativeread.js +5 -3
  126. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  127. package/providers/oauth-mcp-bridge/package.json +1 -1
  128. package/providers/perplexity/src/core.js +7 -2
  129. package/providers/signa/src/adapter.js +3 -0
  130. package/scripts/e2e-first-time.mjs +2 -2
  131. package/shared/brand.mjs +0 -2
  132. package/shared/connector-signin-probe.mjs +1 -1
  133. package/shared/names-in-force.mjs +1 -0
  134. package/skills/clearotron-account/SKILL.md +21 -11
  135. package/skills/clearotron-client/SKILL.md +15 -15
  136. package/skills/clearotron-ops/COURIER.md +5 -1
  137. package/skills/clearotron-ops/SKILL.md +21 -14
@@ -45,7 +45,7 @@
45
45
  import { writeFileSync, appendFileSync, mkdirSync, readFileSync, existsSync, renameSync, rmSync } from "node:fs";
46
46
  import { captureCall, stampVerdict } from "./call-capture.mjs";
47
47
  import { join, dirname } from "node:path";
48
- import { parseFindingsJson, COVERAGE_AREA_STATES, topKeysForVersion, validateFindingForSave, isUseCheckNoResult, findingOrdinalInvalid } from "./findings-model.mjs";
48
+ import { parseFindingsJson, COVERAGE_AREA_STATES, topKeysForVersion, validateFindingForSave, isUseCheckNoResult, findingOrdinalInvalid, FINDINGS_SCHEMA_VERSION } from "./findings-model.mjs";
49
49
  import { heldResearchAnswers, isResearchAnswer, questionKey, NO_SEARCH_RESULT } from "./research-answers.mjs"; // a "no result" names a question that completed
50
50
  import { writeResearchChecks } from "./research-checks.mjs"; // the research behind the use checks, written for the review
51
51
  import { normalizeRecordUri } from "./registry-fidelity.mjs"; // the duty's own reading of a record uri
@@ -1118,6 +1118,28 @@ export function synthesisDutyForRun(runDir) {
1118
1118
  * `correction` is the positions a correction's flags name, as the driver handed them to the tool's server for that
1119
1119
  * correction's dispatch; absent on every other call, which adds no finding (`correctionPositions`).
1120
1120
  */
1121
+ /**
1122
+ * A NEWLY WRITTEN RECORD IS AT THE CURRENT VERSION, EXACTLY. A call carrying a whole findings document, a first call or
1123
+ * a full replacement, at any other version is refused in the turn, so the writer repairs its first answer in its own
1124
+ * session: one at 4 to 6 would read under its own version's rules, with the later versions' checks off, and one above
1125
+ * FINDINGS_SCHEMA_VERSION was written to no version this parser knows. Below it the token says stale; above it, or with
1126
+ * no whole-number version at all, it says mismatch, which assumes no direction. A patch keeps
1127
+ * the version of the record it patches (`registerPatchOf` refuses any other envelope), so a record accepted at an
1128
+ * earlier version keeps it on resume and under a repair that only patches it. Nothing here re-stamps a version. PURE.
1129
+ */
1130
+ export const VERSION_STALE_TOKEN = "synthesis_schema_version_stale";
1131
+ export const VERSION_MISMATCH_TOKEN = "synthesis_schema_version_mismatch";
1132
+ export function staleVersionRefusal(call) {
1133
+ const doc = call?.findings;
1134
+ if (!isPlainObject(doc) || !Array.isArray(doc.findings)) return null;
1135
+ const sv = doc.schema_version;
1136
+ if (sv === FINDINGS_SCHEMA_VERSION) return null;
1137
+ const token = Number.isInteger(sv) && sv < FINDINGS_SCHEMA_VERSION ? VERSION_STALE_TOKEN : VERSION_MISMATCH_TOKEN;
1138
+ return `${token}:${String(sv ?? "none").slice(0, 20)} — a newly written findings record is "schema_version": ${FINDINGS_SCHEMA_VERSION}. `
1139
+ + `Send the whole record again at ${FINDINGS_SCHEMA_VERSION}, with the fields that version requires. `
1140
+ + "A correction to a record already accepted is sent as a patch and keeps that record's version.";
1141
+ }
1142
+
1121
1143
  export function recordSynthesis(runDir, received, opts = {}) {
1122
1144
  const dir0 = String(runDir ?? "");
1123
1145
  // The driver's reads default to the RUN's, and stay overridable for tests. A call site that had to
@@ -1189,7 +1211,7 @@ export function recordSynthesis(runDir, received, opts = {}) {
1189
1211
  };
1190
1212
 
1191
1213
  // A PATCH THE RECORD CANNOT TAKE FOR ITS ROWS is refused for the row, and the accepted record stands (`rejectedRow`).
1192
- const rejected = asRegisters === null ? rejectedRow(stored, call, { positions }) : null;
1214
+ const rejected = (asRegisters === null ? rejectedRow(stored, call, { positions }) : null) ?? staleVersionRefusal(call);
1193
1215
  if (rejected) {
1194
1216
  noteRefusal(rejected);
1195
1217
  recordReading(false);
@@ -101,7 +101,7 @@ export function knockoutCitedUrls(f) {
101
101
  * content bears on the name is the model's to explain and the check's to read, and a source's presence supports nothing by itself.
102
102
  * A URL only in raw web results, or any other file the step was not given as evidence, stays outside.
103
103
  */
104
- export const PERMITTED_SOURCES = "a recorded research payload for this batch, a filing held for this batch, or a recorded owner check linked to a held filing";
104
+ export const PERMITTED_SOURCES = "a recorded research payload for this order, a filing held for this order, or a recorded owner check linked to a held filing";
105
105
  export const urlNotHeld = (mark, url) => `knockout_url_unreceipted:${mark}: "${url}" is not traceable to ${PERMITTED_SOURCES}. Cite a source from that held evidence.`;
106
106
  const OWNER_PAYLOAD = /^owner-.+-[0-9a-f]{10}\.md$/; // the name `ownerPayloadFile` gives a check's answer
107
107
  export function urlHeldFor(runDir) {
@@ -510,6 +510,24 @@ export function batchUseKindDefect(useKind) {
510
510
  return typeof useKind === "string" && useKind.trim() ? null : `batch.useKind is required (task 2c). ${USE_PHRASE}`;
511
511
  }
512
512
 
513
+ /**
514
+ * THE FAMILIES, DEFINED ONCE (design, 2026-11-24). A plan that left the field out was accepted and every name was then rated
515
+ * alone, so a family of variations could be lost with no refusal. A fresh plan now states every name's group, singletons
516
+ * included; a held answer from before keeps what it framed. The grouping line, the tool's field note, the manual and the
517
+ * refusals all state it in these words.
518
+ */
519
+ export const FAMILIES_RULE = "Put every submitted name in exactly one group. List unrelated names as groups of one.";
520
+ export function familiesMissingDefect(families) {
521
+ return families == null ? `batch.families is required to complete the plan. ${FAMILIES_RULE}` : null;
522
+ }
523
+
524
+ /**
525
+ * THE REPAIR RULE, DEFINED ONCE (design, 2026-11-24). A refused call saves nothing, so a repair that sent only the corrected
526
+ * names after a refused first call lost every other name; after a save, a sent name replaces its whole row. The message,
527
+ * the tool's description and the refusal all state it in these words.
528
+ */
529
+ export const FRAME_REPAIR_RULE = "Until the tool confirms it saved the plan, send the complete corrected plan. After confirmation, send only changed batch fields and complete changed name rows.";
530
+
513
531
  export function useKindDefect(name, useKind) {
514
532
  const refusal = `mark "${name}": useKind is required: one to three words, the kind of use this name is searched for (task 2c)`;
515
533
  return typeof useKind === "string" && useKind.trim() ? null : refusal;
@@ -675,8 +693,10 @@ export const validators = {
675
693
  // degraded parity vs the DISK truth (the sweep's payload/.failed sentinels), both directions:
676
694
  // a mark without a payload can never be rated as researched, and a mark WITH one can't hide
677
695
  // behind a degraded flag (fresh evidence must be assessed, e.g. after a resume re-sweep).
696
+ // `true` exactly, the value the report's left-open list reads (publish/knockout-left-open.mjs): any
697
+ // other value on a mark with no payload would pass a truthiness test here and be missed there.
678
698
  const payloadExists = existsSync(join(runDir, "research", `${kebab(m.name)}.md`));
679
- if (!payloadExists && !m.degraded)
699
+ if (!payloadExists && m.degraded !== true)
680
700
  return { ok: false, reason: `mark "${m.name}": the driver holds NO research payload for this mark — the row must carry degraded:true (null-results doctrine; a degraded mark can never be silently clean)` };
681
701
  if (payloadExists && m.degraded)
682
702
  return { ok: false, reason: `mark "${m.name}": a research payload exists but the row claims degraded — assess the held evidence` };
@@ -969,7 +989,7 @@ export function validateMergedFindings(runDir, merged, plan) {
969
989
  // payload/.failed sentinels are the driver's ground truth, never the model's echo)
970
990
  for (const m of marks) {
971
991
  const payloadExists = existsSync(join(runDir, "research", `${kebab(m.name)}.md`));
972
- if (!payloadExists && !m.degraded) failures.push(`mark "${m.name}" has no research payload but is not flagged degraded — a degraded mark can never be silently clean`);
992
+ if (!payloadExists && m.degraded !== true) failures.push(`mark "${m.name}" has no research payload but is not flagged degraded — a degraded mark can never be silently clean`);
973
993
  if (payloadExists && m.degraded) failures.push(`mark "${m.name}" has a research payload but is flagged degraded — held evidence must be assessed`);
974
994
  }
975
995
  // PR-5 — permission-prose backstop over the MERGED text (chunk files can predate the per-chunk check
@@ -33,6 +33,8 @@ import { join, dirname } from "node:path";
33
33
  import { fileURLToPath } from "node:url";
34
34
  import { composeMemo } from "./whatif-memo.mjs";
35
35
  import { DRIVER_DIR, paths as runPaths } from "./run-record.mjs"; // the subtree name from its one definition, never a literal
36
+ import { MEMO_EVIDENCE_FILE, memoEligibility } from "./whatif-queue.mjs"; // the file a memo reads, and which runs it is written over
37
+ import { FROZEN_METHOD_FILE } from "./framework-method.mjs";
36
38
 
37
39
  export const SKILL_ROOT = join(dirname(fileURLToPath(import.meta.url)), "skills");
38
40
 
@@ -42,6 +44,7 @@ export const MEMO_FAILS = Object.freeze({
42
44
  NO_RUN: "memo_run_unresolved",
43
45
  NO_ASSUMPTION: "memo_assumption_missing",
44
46
  NO_EVIDENCE: "memo_parent_has_no_findings",
47
+ NOT_ELIGIBLE: "memo_parent_not_eligible",
45
48
  NOT_WIRED: "memo_reasoning_not_wired",
46
49
  PARENT_MOVED: "memo_parent_artifacts_moved",
47
50
  COMPOSE_REFUSED: "memo_compose_refused",
@@ -122,6 +125,21 @@ export function splitMemoFootprint(moved = []) {
122
125
  return { own, foreign };
123
126
  }
124
127
 
128
+ /**
129
+ * The framework the PARENT froze: its bands, highest to lowest, and its rating table where it states one. The run freezes
130
+ * these two and not the framework's text, so the memo is handed what was archived and told that the text is not among it
131
+ * (design, 2026-11-24). null where the run froze no framework.
132
+ */
133
+ export function parentFramework(runDir, { read = readFileSync } = {}) {
134
+ let bands = [];
135
+ try { bands = (JSON.parse(read(runPaths(runDir).framework, "utf8"))?.bands ?? []).map((b) => String(b?.label ?? "").trim()).filter(Boolean); }
136
+ catch { return null; }
137
+ let method = null;
138
+ try { method = JSON.parse(read(join(runDir, DRIVER_DIR, FROZEN_METHOD_FILE), "utf8")); }
139
+ catch { method = null; } // a framework that states no table rates by its band definitions
140
+ return bands.length ? { bands, method } : null;
141
+ }
142
+
125
143
  /** The profile key the PARENT rated under — read from its frozen sidecar, never re-resolved. */
126
144
  export function parentRatedUnder(runDir, { read = readFileSync } = {}) {
127
145
  try { return JSON.parse(read(runPaths(runDir).profile, "utf8"))?.profileKey ?? null; }
@@ -141,7 +159,7 @@ export function parentRatedUnder(runDir, { read = readFileSync } = {}) {
141
159
  * The reply is a FILE the seat writes and this validates, not prose scraped from a transcript — the
142
160
  * typed-transport pattern, chosen here before it could bite rather than after.
143
161
  */
144
- export async function seatReason({ runDir, runId, assumption, ratedUnder, findings }, deps = {}) {
162
+ export async function seatReason({ runDir, runId, assumption, ratedUnder, findings, framework = null }, deps = {}) {
145
163
  const {
146
164
  runStage = null,
147
165
  read = readFileSync,
@@ -157,7 +175,7 @@ export async function seatReason({ runDir, runId, assumption, ratedUnder, findin
157
175
  const replyPath = join(runDir, MEMO_DIR, `reply-${sha(`${runId}${assumption}`).slice(0, 10)}.json`);
158
176
  mkdirSync(join(runDir, MEMO_DIR), { recursive: true });
159
177
  const r = await dispatch("whatif-memo", {
160
- message: composeMemoMessage({ assumption, findings, ratedUnder, skill, replyPath }),
178
+ message: composeMemoMessage({ assumption, findings, ratedUnder, framework, skill, replyPath }),
161
179
  model,
162
180
  // A BOUNDED READING, and the ceiling says so. This re-reads evidence already gathered; a memo that
163
181
  // needed the clearance's own ceiling would not be the cheap thing the plan promised the reader.
@@ -235,7 +253,10 @@ export function validateMemoReply(raw) {
235
253
  // composing — so a forgotten field is caught there. It stops being safe the moment a dispatch path calls
236
254
  // this composer alone: the seat would be instructed "house default" with no artifact refusal behind it,
237
255
  // because no artifact would be composed. A caller that dispatches without composing owes its own check.
238
- export function composeMemoMessage({ assumption, findings, ratedUnder = null, skill = "", replyPath = null } = {}) {
256
+ /** The memo's limit, in design's approved words (2026-11-24): the message and the memo's manual both state it. */
257
+ export const MEMO_RULES_LINE = "Use the original report's findings and the rating rules supplied here. If a band change depends on a rule that is missing, keep the reported band and explain the limit.";
258
+
259
+ export function composeMemoMessage({ assumption, findings, ratedUnder = null, framework = null, skill = "", replyPath = null } = {}) {
239
260
  return [
240
261
  skill.trim(),
241
262
  "",
@@ -247,7 +268,12 @@ export function composeMemoMessage({ assumption, findings, ratedUnder = null, sk
247
268
  "",
248
269
  ratedUnder
249
270
  ? `${ratedUnder} — assess under this one, not the house default.`
250
- : "This run froze no customer profile, so it was assessed under the house default. Stay with it.",
271
+ // A missing profile record does not show the house default was used, so the memo is not told it was (design, 2026-11-24).
272
+ : "This run kept no record of the customer profile it was rated under.",
273
+ ...(framework?.bands?.length ? ["", `Its bands, highest to lowest: ${framework.bands.join(" · ")}.`] : []),
274
+ ...(framework?.method ? ["", "Its rating table:", "", "```json", JSON.stringify(framework.method, null, 2), "```"] : []),
275
+ "",
276
+ MEMO_RULES_LINE,
251
277
  "",
252
278
  "## The findings this report delivered",
253
279
  "",
@@ -266,7 +292,7 @@ export function composeMemoMessage({ assumption, findings, ratedUnder = null, sk
266
292
  // one document and left a retried stage on the parent run's ledger — an INVESTIGATE line on a report
267
293
  // that had already been delivered clean.
268
294
  replyPath
269
- ? `Write it to this ABSOLUTE path (create parent dirs if needed): ${replyPath}`
295
+ ? `Write your reply to this ABSOLUTE path (create parent dirs if needed): ${replyPath}`
270
296
  : "Write the JSON object the skill dictates, and nothing else.",
271
297
  replyPath ? "Write the JSON object the skill dictates, and nothing else." : null,
272
298
  ].filter((l) => l !== null).join("\n");
@@ -303,10 +329,12 @@ export async function askArchivedRun({ runId, question, requestedBy = null } = {
303
329
  if (!run?.runDir) return { ok: false, fail: MEMO_FAILS.NO_RUN, detail: `run "${runId}" did not resolve` };
304
330
 
305
331
  // The evidence must exist before anything is asked of it. A memo over a run with no findings would
306
- // reason from nothing and say so in the voice of a document that had read something.
307
- const findingsPath = join(run.runDir, "findings.json");
308
- if (!existsSync(findingsPath))
309
- return { ok: false, fail: MEMO_FAILS.NO_EVIDENCE, detail: `${runId} carries no findings.json to reason over` };
332
+ // reason from nothing and say so in the voice of a document that had read something. The same check the plan and the
333
+ // queue asked, so a memo they offered is one the worker writes (design, 2026-11-24).
334
+ const findingsPath = join(run.runDir, MEMO_EVIDENCE_FILE);
335
+ const ineligible = memoEligibility(run, { exists: existsSync, read });
336
+ if (ineligible)
337
+ return { ok: false, fail: ineligible.fail === "unreadable" ? MEMO_FAILS.NO_EVIDENCE : MEMO_FAILS.NOT_ELIGIBLE, detail: `${runId}: ${ineligible.reason}` };
310
338
 
311
339
  if (typeof reason !== "function")
312
340
  return { ok: false, fail: MEMO_FAILS.NOT_WIRED,
@@ -314,11 +342,12 @@ export async function askArchivedRun({ runId, question, requestedBy = null } = {
314
342
 
315
343
  const before = digestRunDir(run.runDir);
316
344
  const ratedUnder = parentRatedUnder(run.runDir, { read });
345
+ const framework = parentFramework(run.runDir, { read });
317
346
 
318
347
  let reading;
319
348
  try {
320
349
  reading = await reason({
321
- runDir: run.runDir, runId: run.runId, assumption, ratedUnder,
350
+ runDir: run.runDir, runId: run.runId, assumption, ratedUnder, framework,
322
351
  findings: JSON.parse(read(findingsPath, "utf8")),
323
352
  });
324
353
  } catch (e) {
@@ -44,10 +44,11 @@
44
44
  // re-running a CLEARANCE twice costs a second billable search and a second report to a lawyer. The
45
45
  // cheaper failure buys a much simpler protocol, and the asymmetry is the whole reason to state it.
46
46
 
47
- import { existsSync, mkdirSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
47
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
48
48
  import { join } from "node:path";
49
49
  import { randomUUID } from "node:crypto";
50
- import { readJson } from "./run-record.mjs";
50
+ import { readJson, paths as runPaths } from "./run-record.mjs";
51
+ import { PRODUCTS } from "./products.mjs";
51
52
 
52
53
  // ── WHICH RUNS A WHAT-IF MAY TOUCH — ONE DECLARATION, TWO READERS ───────────────────────────────────
53
54
  //
@@ -75,7 +76,50 @@ export const WHATIF_REFUSED_MARKERS = Object.freeze([".delivered", ".cancelled",
75
76
  * drift: the MCP door knows `location`/`state`, the worker knows which marker files are on disk, and
76
77
  * both get the same sentence for the same run.
77
78
  */
78
- export function whatIfRefusal({ location = null, state = null, markers = [], kind = "stage" } = {}) {
79
+ // ── WHICH RUNS A MEMO IS WRITTEN OVER ──────────────────────────────────────────────────────────────
80
+ //
81
+ // A delivered clearance report whose findings can be read, and nothing else (design, 2026-11-24). A live run's findings
82
+ // file is an intermediate one; a run archived or cancelled without being delivered never completed; and a Knockout is not
83
+ // a product a memo is written for, though it has findings of its own. A memo was planned on a delivered Knockout and then
84
+ // refused by the worker after the asker had been told it would run (reproduced offline, 2026-11-24), so this one check
85
+ // is asked by the plan, the queue, the run and the worker alike, before any session starts.
86
+ //
87
+ // DELIVERED IS READ FROM POSITIVE EVIDENCE: the run's state, or its delivery marker. Sitting in the archive is not
88
+ // evidence, because a stopped or failed run is archived too.
89
+ export const MEMO_EVIDENCE_FILE = "findings.json";
90
+ const KNOCKOUT_FILES = Object.freeze(["knockout-findings.json", "knockout-plan.json", "knockout-frame.md"]);
91
+ const MEMO_STOPPED = "this run was stopped before its evidence was complete, so a memo over it would reason from a record the run itself never finished";
92
+
93
+ /** Is this run a Knockout? Its frozen product where it has one, else the files only a Knockout writes. */
94
+ function isKnockout(runDir, { exists, read }) {
95
+ try {
96
+ const level = JSON.parse(read(runPaths(runDir).searchPolicy, "utf8"))?.level;
97
+ const product = PRODUCTS.find((p) => p.id === level);
98
+ if (product) return product.pipeline === "knockout";
99
+ } catch { /* no frozen product on this run: the files decide */ }
100
+ return KNOCKOUT_FILES.some((f) => exists(join(runDir, f)));
101
+ }
102
+
103
+ /**
104
+ * Why no memo may be written over this run, or null when one may. `{ fail, reason }`: `fail` is a stable word for the
105
+ * worker's code, `reason` the sentence every door returns. `run` is a resolved run: its directory and recorded state.
106
+ */
107
+ export function memoEligibility(run, { exists = existsSync, read = readFileSync } = {}) {
108
+ const dir = String(run?.runDir ?? "");
109
+ const has = (f) => Boolean(dir) && exists(join(dir, f));
110
+ if (run?.state === "cancelled" || has(".cancelled") || has(".cancel")) return { fail: "stopped", reason: MEMO_STOPPED };
111
+ if (!(run?.state === "delivered" || has(".delivered")))
112
+ return { fail: "not_delivered", reason: "a memo reads a delivered clearance report, and this search has not been delivered" };
113
+ if (isKnockout(dir, { exists, read }))
114
+ return { fail: "knockout", reason: "memos are offered on delivered clearance reports only, and this search is a Knockout" };
115
+ try { JSON.parse(read(join(dir, MEMO_EVIDENCE_FILE), "utf8")); }
116
+ catch { return { fail: "unreadable", reason: "this report's findings could not be read, so no memo can be written over it" }; }
117
+ return null;
118
+ }
119
+ /** The sentence alone, or null: what the plan, the queue and the run return. */
120
+ export const memoRefusal = (run, io) => memoEligibility(run, io)?.reason ?? null;
121
+
122
+ export function whatIfRefusal({ location = null, state = null, markers = [], kind = "stage", memoOffered = false } = {}) {
79
123
  const has = (m) => markers.includes(m);
80
124
  const finished = location === "archive" || state === "delivered" || has(".delivered");
81
125
  // — A MEMO IS NOT A RE-RUN, AND THE FINISHED STATE IS WHY IT EXISTS.
@@ -92,12 +136,14 @@ export function whatIfRefusal({ location = null, state = null, markers = [], kin
92
136
  //
93
137
  // CANCELLED STAYS REFUSED FOR BOTH. A run its owner stopped has evidence that was never completed, and
94
138
  // reasoning over a half-gathered record is how a memo comes to say more than the run ever knew.
139
+ // THE REFUSAL NAMES THE MEMO where one can be written, so a re-run refused on a delivered report points at the answer
140
+ // that exists rather than ending the question (design, 2026-11-24). Where no memo can be read, it does not offer one.
95
141
  if (finished && kind !== "memo")
96
- return "this run is delivered or archived — what-if runs on live runs only; read it with trace or read_artifact instead";
142
+ return memoOffered
143
+ ? "this search is delivered, so no step of it re-runs; to ask what changes under an assumption, plan a memo instead: kind \"memo\", with the assumption in instructions"
144
+ : "this run is delivered or archived — what-if runs on live runs only; read it with trace or read_artifact instead";
97
145
  if (state === "cancelled" || has(".cancelled") || has(".cancel"))
98
- return kind === "memo"
99
- ? "this run was stopped before its evidence was complete, so a memo over it would reason from a record the run itself never finished"
100
- : "this run was stopped, so there is nothing here to re-run";
146
+ return kind === "memo" ? MEMO_STOPPED : "this run was stopped, so there is nothing here to re-run";
101
147
  return null;
102
148
  }
103
149
 
@@ -1,5 +1,13 @@
1
1
  # trademark-artifacts-mcp
2
2
 
3
+ ## 0.7.0-beta.4
4
+
5
+ No changes in this release.
6
+
7
+ ## 0.7.0-beta.3
8
+
9
+ No changes in this release.
10
+
3
11
  ## 0.7.0-beta.2
4
12
 
5
13
  ### Patch Changes
@@ -16,7 +16,7 @@ import { validateJob } from "../../driver/enqueue-schema.mjs";
16
16
  import { doorGates } from "../../driver/door-gates.mjs"; // the resolved-product checks every door runs
17
17
  import { probeQueueWatch, unwatchedQueueWarning } from "../../driver/queue-watch-probe.mjs"; //
18
18
  import { resolveRun, runAccountKey } from "./runs.mjs";
19
- import { assertAccountAccess, attributionOf, grantsGeneric, GENERIC_NOT_GRANTED } from "../../shared/scope.mjs";
19
+ import { accountVisible, assertAccountAccess, attributionOf, grantsGeneric, GENERIC_NOT_GRANTED } from "../../shared/scope.mjs";
20
20
  import { requestCancel, isCancelled } from "../../driver/cancel.mjs"; // one marker shape, shared with the engine
21
21
  import { readEngineChild, engineChildIsLive, endEngineChild } from "../../driver/engine/child-record.mjs"; //
22
22
  import { killEscalateMs } from "../../driver/engine/common.mjs"; // the watchdogs' grace, reused by an immediate stop
@@ -60,6 +60,15 @@ export function enqueuedViaFor(scope) {
60
60
  return String(scope?.sub ?? "") === PORTAL_TOKEN_SUB ? "portal/start_run" : "mcp/start_run";
61
61
  }
62
62
 
63
+ // THE QUEUE ID'S RULE, STATED WHOLE IN THE REFUSAL. The id becomes a queue file name, so it is held to a slug
64
+ // of at most this many characters that starts with a letter or digit. The refusal named only the characters, and an assistant whose id was
65
+ // too long read it as a bad character, changed nothing that mattered, and lost the order's first call on
66
+ // three mornings before it made one up that fit. stop_run's queue form holds a queued id to the same rule.
67
+ const QUEUE_ID_MAX = 128;
68
+ const QUEUE_ID_RE = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._@-]{0,${QUEUE_ID_MAX - 1}}$`);
69
+ const queueIdRefusal = (id) => `id ${JSON.stringify(id)}: Use an ID of 1–${QUEUE_ID_MAX} characters. Start with an ASCII letter or digit. `
70
+ + `The remaining characters may also include a dot, underscore, @ or hyphen.${id.length > QUEUE_ID_MAX ? ` This one has ${id.length} characters.` : ""}`;
71
+
63
72
  export function buildJob(args = {}, { scope } = {}) {
64
73
  // marks[] (search-depth spine): a knockout BATCH is ONE job carrying every mark — accept an explicit
65
74
  // marks array ({name, classes?, ref?} each) as the batch form; markName remains the single-mark form
@@ -72,8 +81,7 @@ export function buildJob(args = {}, { scope } = {}) {
72
81
  const id = String(args.id || `mcp-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`);
73
82
  // Input hardening: the id becomes a QUEUE FILENAME (join(qdir, `${id}.json`)) — a
74
83
  // path-shaped id would escape the queue directory. Slug-validated unconditionally, every caller.
75
- if (id !== basename(id) || id.includes("..") || !/^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$/.test(id))
76
- throw new Error(`id ${JSON.stringify(id)} must be a bare filename slug ([A-Za-z0-9._@-], no path separators)`);
84
+ if (id !== basename(id) || id.includes("..") || !QUEUE_ID_RE.test(id)) throw new Error(queueIdRefusal(id));
77
85
  const classes = Array.isArray(args.classes) ? args.classes.map(Number).filter(Number.isFinite) : undefined;
78
86
  // `||` not `??`: markName "" is falsy-but-not-nullish and must fall through to the
79
87
  // first batch mark, never enqueue an empty display name.
@@ -314,8 +322,7 @@ export async function stopRun(args = {}, { scope, endTurn = endEngineChild } = {
314
322
  const qdir = queueDir(agent);
315
323
  // same filename hardening as start_run — the id is joined into the queue path
316
324
  const sid = String(args.id);
317
- if (sid !== basename(sid) || sid.includes("..") || !/^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$/.test(sid))
318
- throw new Error(`stop_run: id ${JSON.stringify(sid)} must be a bare filename slug ([A-Za-z0-9._@-], no path separators)`);
325
+ if (sid !== basename(sid) || sid.includes("..") || !QUEUE_ID_RE.test(sid)) throw new Error(`stop_run: ${queueIdRefusal(sid)}`);
319
326
  const f = join(qdir, `${String(args.id)}.json`);
320
327
  const NOT_FOUND = { ok: false, action: "not-found", id: args.id, note: "No queued job with that id (already run, or never queued)." };
321
328
  // ACCOUNT GATE: the runId form is gated at the dispatch chokepoint, but a QUEUED job
@@ -561,9 +568,10 @@ export function getDeliveryPacket(args = {}) {
561
568
  // courier never SAW this event and cannot be misled into thinking it routed one it did not. Leaving
562
569
  // the file on disk is the point — the full-grant courier still picks it up.
563
570
  //
564
- // Fail closed on every unknown: a packet with no runId (an intake rejection filed before any run
565
- // exists), an unreadable file, or a run with no account tag all resolve to "not in your grant" for a
566
- // scoped session — exactly how assertAccountAccess already treats an untagged run everywhere else.
571
+ // Fail closed on every unknown: an unreadable file, a run with no account tag, or a notice filed before
572
+ // any run exists whose order named no account all resolve to "not in your grant" for a scoped session —
573
+ // exactly how assertAccountAccess already treats an untagged run everywhere else. A notice with no run
574
+ // is judged on the account its order named (runner.mjs noticeAccount), as list_outbox_events judges it.
567
575
  export function ackEvent(args = {}, { scope } = {}) {
568
576
  const file = String(args.file || "");
569
577
  if (!file) throw new Error("ack_event: file is required (from list_outbox_events)");
@@ -584,12 +592,13 @@ export function ackEvent(args = {}, { scope } = {}) {
584
592
  // is a refusal, never a pass.
585
593
  function ackVisible(path, file, scope) {
586
594
  let runId = null;
595
+ let packet = null;
587
596
  try {
588
597
  const raw = readFileSync(path, "utf8");
589
- try { runId = JSON.parse(raw).runId ?? null; }
598
+ try { packet = JSON.parse(raw); runId = packet?.runId ?? null; }
590
599
  catch { runId = file.replace(/\.pending$/, ""); } // legacy delivered marker: agent-id text body, runId in the name
591
600
  } catch { return false; } // unreadable — fail CLOSED
592
- if (!runId) return false;
601
+ if (!runId) return packet ? accountVisible(scope, packet.account ?? null, packet.organisation ?? null) : false;
593
602
  const run = resolveRun(String(runId));
594
603
  if (!run) return false;
595
604
  try { assertAccountAccess(scope, runAccountKey(run), `outbox event "${file}"`); return true; }
@@ -26,7 +26,7 @@ import { join, basename } from "node:path";
26
26
  // — the SHARED eligibility composer. A leaf module (fs/path/crypto only), so a
27
27
  // static import here costs the read-only surface nothing and buys the one thing three copies of this
28
28
  // question could not give: the same answer at the door and at the worker.
29
- import { whatIfRefusal } from "../../driver/whatif-queue.mjs";
29
+ import { whatIfRefusal, memoRefusal } from "../../driver/whatif-queue.mjs";
30
30
  import { driverDir, paths, readJson } from "../../driver/run-record.mjs";
31
31
 
32
32
  // ── — THE NOTE SAYS WHAT IS TRUE, AND IT IS THE STRONGER SENTENCE ────────
@@ -91,7 +91,7 @@ export function whatIfPlan({ run, stage, axis = null, instructions = null, model
91
91
  // prior telemetry to quote (this stage never ran). Carrying those keys with null values would tell a
92
92
  // reader the questions had been asked and answered "none", which is not what happened.
93
93
  if (kind === "memo") {
94
- const refusal = whatIfRefusal({ location: run.location, state: run.state, kind: "memo" });
94
+ const refusal = memoRefusal(run); // the one eligibility the queue, the run and the worker ask too
95
95
  if (refusal) return { runnable: false, reason: `Run ${run.runId}: ${refusal}.` };
96
96
  const assumption = String(instructions ?? "").trim();
97
97
  if (!assumption)
@@ -120,7 +120,7 @@ export function whatIfPlan({ run, stage, axis = null, instructions = null, model
120
120
  } else if (axis) {
121
121
  axis = null; // axis only applies to register-unit; ignore it elsewhere
122
122
  }
123
- const refusal = whatIfRefusal({ location: run.location, state: run.state });
123
+ const refusal = whatIfRefusal({ location: run.location, state: run.state, memoOffered: !memoRefusal(run) });
124
124
  if (refusal) return { runnable: false, reason: `Run ${run.runId}: ${refusal}.` };
125
125
  const resolvedModel = resolveModel(model ?? (axis ? axisTier(axis).model : STAGES[stage].model));
126
126
  const ord = stageOrdinal(stage);
@@ -196,7 +196,8 @@ export async function whatIfEnqueue({ run, confirmationToken, requestedBy = null
196
196
  throw new Error(`whatIfEnqueue: this confirmationToken is for run "${op.runId}", not "${run.runId}" — plan the what-if on the run you mean to change.`);
197
197
  // — the KIND decides what "finished" means here: a stage re-run on a delivered
198
198
  // run is refused, and a memo over one is the whole point.
199
- const refusal = whatIfRefusal({ location: run.location, state: run.state, kind: op.kind ?? "stage" });
199
+ const refusal = op.kind === "memo" ? memoRefusal(run)
200
+ : whatIfRefusal({ location: run.location, state: run.state, kind: op.kind ?? "stage", memoOffered: !memoRefusal(run) });
200
201
  if (refusal) throw new Error(`whatIfEnqueue: run ${run.runId}: ${refusal}.`);
201
202
  const enqueue = deps.enqueueWhatIf ?? (await import("../../driver/whatif-queue.mjs")).enqueueWhatIf;
202
203
  const job = enqueue(run.runDir, { op, requestedBy, account });
@@ -244,8 +245,8 @@ export async function whatIfRun({ confirmationToken } = {}, deps = {}) {
244
245
  // use for. The lazy import is the same discipline as runExperiment's below — this module keeps
245
246
  // driver/ out of its module scope so the remote surfaces never pull the engine in.
246
247
  if (op.kind === "memo") {
247
- const memoRefusal = whatIfRefusal({ location: run.location, state: run.state, kind: "memo" });
248
- if (memoRefusal) throw new Error(`whatIfRun: run ${runId}: ${memoRefusal}.`);
248
+ const refused = memoRefusal(run);
249
+ if (refused) throw new Error(`whatIfRun: run ${runId}: ${refused}.`);
249
250
  const askArchivedRun = deps.askArchivedRun
250
251
  ?? (await import("../../driver/whatif-memo-run.mjs")).askArchivedRun;
251
252
  // askArchivedRun answers {ok:true, memoPath, memoId, parentRunId, assumption, ratedUnder,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trademark-artifacts-mcp",
3
- "version": "0.7.0-beta.2",
3
+ "version": "0.7.0-beta.4",
4
4
  "license": "AGPL-3.0-only",
5
5
  "private": true,
6
6
  "description": "MCP server to interrogate clearotron trademark-clearance runs — list/read artifacts, trace the full decision flow, telemetry/cost, coverage, single-run search, and a gated single-step what-if. Imports the clearotron-driver read-only; touches no driver/template/deploy files.",