clearotron 0.7.0-beta.4 → 0.8.0-beta.0

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 (98) hide show
  1. package/THIRD-PARTY-NOTICES.md +71 -2
  2. package/build-info.json +2 -2
  3. package/demo/multi-country-focus-search/run/common-law-grid.json +1 -1
  4. package/docs/CLIENT-MCP.md +17 -0
  5. package/docs/assets/README.md +19 -3
  6. package/docs/assets/portal-clearance-report.jpg +0 -0
  7. package/docs/assets/portal-conflict-landscape.jpg +0 -0
  8. package/docs/assets/portal-new-clearance.png +0 -0
  9. package/driver/CHANGELOG.md +162 -0
  10. package/driver/config-inventory.mjs +15 -2
  11. package/driver/dev-portal.mjs +2 -0
  12. package/driver/effort-model.mjs +34 -4
  13. package/driver/engine/CONTRACT.md +8 -0
  14. package/driver/engine/anthropic-agent.mjs +74 -16
  15. package/driver/engine/jx-turn.mjs +11 -3
  16. package/driver/engine/openai-agent.mjs +33 -7
  17. package/driver/engine/run-choices.mjs +28 -7
  18. package/driver/engine/speed.mjs +107 -0
  19. package/driver/enqueue-schema.mjs +8 -0
  20. package/driver/enqueue.mjs +14 -2
  21. package/driver/jx-units.mjs +2 -2
  22. package/driver/jx.mjs +1 -1
  23. package/driver/knockout-plain-language.mjs +96 -0
  24. package/driver/ladder/attempt-record.mjs +14 -2
  25. package/driver/ladder/dispatch.mjs +2 -2
  26. package/driver/ladder/form-repair.mjs +1 -1
  27. package/driver/ladder/stage.mjs +7 -1
  28. package/driver/mark-logos.mjs +6 -1
  29. package/driver/order-receipt.mjs +184 -0
  30. package/driver/package.json +4 -1
  31. package/driver/picture-shrink-worker.mjs +21 -0
  32. package/driver/picture-thumbnail.mjs +132 -0
  33. package/driver/pipeline-knockout.mjs +14 -0
  34. package/driver/portal-confirmation.mjs +3 -0
  35. package/driver/portal-report.mjs +44 -1
  36. package/driver/portal-routes/run.mjs +19 -9
  37. package/driver/portal-runs.mjs +118 -63
  38. package/driver/portal-service.mjs +17 -2
  39. package/driver/predelivery-lint.mjs +3 -3
  40. package/driver/progress.mjs +33 -5
  41. package/driver/publish/column-queries.mjs +86 -0
  42. package/driver/publish/index.mjs +4 -4
  43. package/driver/publish/knockout.mjs +35 -8
  44. package/driver/publish/page-shell.mjs +5 -1
  45. package/driver/publish/read-document.mjs +3 -0
  46. package/driver/publish/render-knockout.mjs +61 -16
  47. package/driver/publish/render.mjs +171 -30
  48. package/driver/publish/search-depth.mjs +45 -1
  49. package/driver/publish/strings.mjs +23 -0
  50. package/driver/publish/templates/report.css +73 -0
  51. package/driver/research-answers.mjs +17 -6
  52. package/driver/research-checks.mjs +22 -4
  53. package/driver/research-records.mjs +81 -0
  54. package/driver/run-quote.mjs +3 -0
  55. package/driver/run-speed.mjs +89 -0
  56. package/driver/runner.mjs +50 -21
  57. package/driver/saved-register-pages.mjs +23 -22
  58. package/driver/stage-freshness.mjs +5 -0
  59. package/driver/stages.mjs +2 -2
  60. package/driver/steps/open-run.mjs +12 -1
  61. package/driver/suite-census.json +199 -37
  62. package/driver/tokens.mjs +3 -0
  63. package/driver/urgent-count.mjs +54 -0
  64. package/driver/usage-ledger.mjs +8 -2
  65. package/driver/web-pictures.mjs +532 -0
  66. package/mcp-server/CHANGELOG.md +22 -0
  67. package/mcp-server/lib/document-reads.mjs +28 -0
  68. package/mcp-server/lib/events.mjs +21 -12
  69. package/mcp-server/lib/findings.mjs +2 -1
  70. package/mcp-server/lib/knockout.mjs +3 -2
  71. package/mcp-server/lib/ops.mjs +103 -6
  72. package/mcp-server/lib/options.mjs +4 -0
  73. package/mcp-server/lib/plan.mjs +38 -4
  74. package/mcp-server/lib/result-shapes.mjs +66 -0
  75. package/mcp-server/lib/runs.mjs +46 -44
  76. package/mcp-server/lib/urgent.mjs +29 -0
  77. package/mcp-server/package.json +1 -1
  78. package/mcp-server/result-shapes.json +2978 -0
  79. package/mcp-server/server.mjs +67 -14
  80. package/package.json +4 -1
  81. package/portal-ui/dist/assets/{index-qNDhqCw9.js → index-DEkVU2FD.js} +1909 -766
  82. package/portal-ui/dist/assets/{index-CxAkJXIT.css → index-W6SAoDkS.css} +238 -1
  83. package/portal-ui/dist/index.html +2 -2
  84. package/portal-ui/package.json +1 -1
  85. package/providers/jx/src/turn-envelope.mjs +3 -1
  86. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  87. package/providers/oauth-mcp-bridge/package.json +1 -1
  88. package/providers/signa/src/core.js +54 -12
  89. package/scripts/README.md +3 -0
  90. package/scripts/e2e-first-time.mjs +2 -2
  91. package/scripts/mint-result-shapes.mjs +199 -0
  92. package/scripts/readme-pictures.mjs +227 -0
  93. package/scripts/render-check.mjs +4 -1
  94. package/scripts/report-sections-render-check.mjs +191 -0
  95. package/scripts/settings-render-check.mjs +68 -11
  96. package/shared/brand.mjs +8 -0
  97. package/skills/clearotron-account/SKILL.md +24 -0
  98. package/skills/clearotron-ops/SKILL.md +23 -9
@@ -0,0 +1,96 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ // knockout-plain-language.mjs — where a Knockout's default-visible lines break the plain-language rule, counted by
4
+ // rating group and by field, on the rating as saved and on the record as published. Recording only.
5
+ //
6
+ // The rule stays where it is: no default-visible sentence over the word limit, and none of the lawyer's vocabulary, both
7
+ // flagged for whoever fixes the run and never shown to a client, and never a reason to stop a delivery. The rating step
8
+ // carries it on its first pass, and nothing after it rewrites these lines. Whether a further turn per group would earn
9
+ // its cost is open, so each delivered Knockout records the counts that decide it: per group, how many sentences run long
10
+ // and how many words are the lawyer's, field by field, as the rating saved them and as the page published them; whether
11
+ // the group was sent to the correction step; and how many groups another turn would have had to touch.
12
+ //
13
+ // The counts are the lint's own (predelivery-lint.mjs: the same walk over the same fields, the same limit and the same
14
+ // vocabulary), so this record and the lint's flag cannot disagree about what a long line is.
15
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
16
+ import { knockoutVisibleProse } from "./predelivery-lint.mjs";
17
+ import { PLAIN_FORMS, SENTENCE_WORD_LIMIT, termMatcher } from "./plain-register.mjs";
18
+ import { knockoutAssessChunkFile } from "./knockout-assess-record.mjs";
19
+ import { paths } from "./run-record.mjs";
20
+ import { readRunChoices } from "./engine/run-choices.mjs";
21
+ import { runLog } from "./log.mjs";
22
+
23
+ /** A visible field's short name: the summary, a conflict sentence, the basis line, a factor, or the field itself. */
24
+ const FIELD = { "batch.executiveSummary": "summary", "findings.net": "conflict", basis: "basis", factors: "factors", counterFactors: "factors" };
25
+ const fieldOf = (at) => FIELD[at?.field] ?? String(at?.field ?? "other");
26
+
27
+ /**
28
+ * Counts over one record, field by field: `{ long: { <field>: n }, words: { <field>: n } }`. `long` counts sentences over
29
+ * the word limit, `words` the lawyer's terms. PURE.
30
+ */
31
+ export function plainLanguageByField(findings) {
32
+ const long = {}, words = {};
33
+ for (const { text, at } of knockoutVisibleProse(findings)) {
34
+ if (at?.engineOwned) continue; // the engine's own caveats are not a seat's to rewrite, and no turn would touch them
35
+ const f = fieldOf(at);
36
+ for (const sentence of text.split(/(?<=[.!?])\s+|\n+/))
37
+ if (sentence.trim().split(/\s+/).filter(Boolean).length > SENTENCE_WORD_LIMIT) long[f] = (long[f] ?? 0) + 1;
38
+ for (const [term] of PLAIN_FORMS) if (termMatcher(term).test(text)) words[f] = (words[f] ?? 0) + 1;
39
+ }
40
+ return { long, words };
41
+ }
42
+ const total = (byField) => Object.values(byField).reduce((n, v) => n + v, 0);
43
+ const any = (c) => total(c.long) + total(c.words) > 0;
44
+
45
+ /** The rating groups a run saved: `[{ group, record }]`, in order, from its own chunk files. */
46
+ function savedGroups(runDir) {
47
+ const out = [];
48
+ let names = [];
49
+ try { names = readdirSync(runDir); } catch { return out; }
50
+ const nums = names.map((n) => n.match(/^knockout-assess-(\d+)\.json$/)?.[1]).filter((n) => n != null).map(Number).sort((a, b) => a - b);
51
+ for (const n of nums) {
52
+ try { out.push({ group: n, record: JSON.parse(readFileSync(knockoutAssessChunkFile(runDir, n), "utf8")) }); } catch { /* a torn chunk is left out, and the count says how many were read */ }
53
+ }
54
+ return out;
55
+ }
56
+
57
+ /** The groups the review sent to the correction step, from the run's own correction work. */
58
+ function correctedGroups(runDir) {
59
+ const p = paths(runDir).knockoutCorrectionWork;
60
+ if (!existsSync(p)) return new Set();
61
+ try { return new Set((JSON.parse(readFileSync(p, "utf8"))?.defects ?? []).map((d) => d?.chunk).filter((c) => c != null).map(Number)); }
62
+ catch { return new Set(); }
63
+ }
64
+
65
+ /**
66
+ * The record for one delivered Knockout: per group, the counts as saved and as published, whether the group was sent to
67
+ * correction, and how many groups a further turn would have had to touch. `delivered` is the record handed to publish.
68
+ */
69
+ export function knockoutPlainLanguage({ runDir, delivered }) {
70
+ const corrected = correctedGroups(runDir);
71
+ const groups = savedGroups(runDir).map(({ group, record }) => {
72
+ const marks = (record?.marks ?? []).map((m) => String(m?.name ?? "")).filter(Boolean);
73
+ const saved = plainLanguageByField({ batch: { executiveSummary: record?.chunkSummary ?? record?.batch?.executiveSummary }, marks: record?.marks ?? [] });
74
+ const shown = plainLanguageByField({ marks: (delivered?.marks ?? []).filter((m) => marks.includes(String(m?.name ?? ""))) });
75
+ return { group, marks: marks.length, saved, published: shown, sentToCorrection: corrected.has(group) };
76
+ });
77
+ // The batch summary is published once for the whole order, so it is counted once, apart from the groups.
78
+ const summary = plainLanguageByField({ batch: delivered?.batch ?? {}, marks: [] });
79
+ return {
80
+ engine: readRunChoices(runDir).engine ?? null,
81
+ limit: SENTENCE_WORD_LIMIT,
82
+ groups,
83
+ publishedSummary: summary,
84
+ groupsWithAFlagAsSaved: groups.filter((g) => any(g.saved)).length,
85
+ groupsWithAFlagAsSavedAndNotSentToCorrection: groups.filter((g) => any(g.saved) && !g.sentToCorrection).length,
86
+ };
87
+ }
88
+
89
+ /** Write the record to the run's spine at delivery. Best-effort: a count never affects a delivery. */
90
+ export function stampKnockoutPlainLanguage(runDir, delivered) {
91
+ try {
92
+ const rec = knockoutPlainLanguage({ runDir, delivered });
93
+ runLog(runDir, { event: "knockout-plain-language", ...rec });
94
+ return rec;
95
+ } catch { return null; }
96
+ }
@@ -73,7 +73,15 @@ export function measureAttempt({ name, files, runDir }, { attempt, key, warm, tu
73
73
  return { wrote, reads, readsTruncated, quantity, noChange };
74
74
  }
75
75
 
76
- export function writeAttemptRow({ name, engine, agent, model, files, runDir, followup, bandSize, derivedLimit, auth },
76
+ /**
77
+ * THE SPEED ON EVERY ATTEMPT ROW: what the turn asked for and what the program reported serving (engine/speed.mjs). A
78
+ * turn that never started reported nothing, so its row carries the stage's request with an unknown served speed.
79
+ */
80
+ export function attemptSpeed(turn, requested = "standard") {
81
+ return turn?.speed ?? { requested, standardBecause: null, served: null, basis: "unknown", calls: null, state: null, disabledReason: null, notice: null };
82
+ }
83
+
84
+ export function writeAttemptRow({ name, engine, agent, model, speed, files, runDir, followup, bandSize, derivedLimit, auth },
77
85
  { lastUnion, lastCoverageUnion, lastPlacementUnion }, facts) {
78
86
  const { attempt, key, warm, warmEscalatedAt, effTimeout, dispatch, witnessed, wire, turn, cli, modelRequested,
79
87
  modelActual, modelBasis, modelSnapshot, modelMismatch, providerReported, timedOutBy, fail, formRepairsThisAttempt, rescued, quiescentMs,
@@ -111,6 +119,7 @@ export function writeAttemptRow({ name, engine, agent, model, files, runDir, fol
111
119
  // Written even on the rows where they are null, so "this engine cannot report" stays visibly
112
120
  // different from "this record predates the gauge".
113
121
  modelActual, modelBasis, modelSnapshot, modelMismatch, providerReported,
122
+ speed: attemptSpeed(turn, speed),
114
123
  cliVersion: cli.version, cliVersionProbe: cli.probe, ...(cli.why ? { cliVersionWhy: cli.why } : {}), cliSource: cli.source,
115
124
  cliFloor: cli.floor ?? null, cliBelowFloor: cli.belowFloor ?? null,
116
125
  // W3 billing telemetry: which engine ran + the RESOLVED billing mode (subscription vs api-key). This
@@ -259,7 +268,7 @@ export function writeAttemptRow({ name, engine, agent, model, files, runDir, fol
259
268
  });
260
269
  }
261
270
 
262
- export function writeAttemptEvent({ name, maxRetries, runDir, bandSize, derivedLimit, auth }, facts) {
271
+ export function writeAttemptEvent({ name, maxRetries, runDir, bandSize, derivedLimit, auth, model, speed }, facts) {
263
272
  const { attempt, warm, warmEscalatedAt, dispatch, wire, turn, cli, modelRequested, modelActual, modelBasis, modelSnapshot, modelMismatch,
264
273
  providerReported, timedOutBy, fail, formRepairsThisAttempt, rescued, quiescentMs, rescueRefused, rescueRefusedFile, rescueRefusedReason,
265
274
  attemptRefusals, attemptKilledWhile, wrote, quantity, noChange } = facts;
@@ -277,6 +286,9 @@ export function writeAttemptEvent({ name, maxRetries, runDir, bandSize, derivedL
277
286
  //: the spine carries the same pair as the per-stage log, or the two disagree about what
278
287
  // ran. `model` stays the requested resolution (its existing readers); `modelActual` is the wire.
279
288
  model: modelRequested, modelActual, modelBasis, modelSnapshot, modelMismatch, providerReported,
289
+ // The speed the turn asked for and was served, so a run's rollup counts every session from the spine alone
290
+ // (run-speed.mjs).
291
+ speed: attemptSpeed(turn, speed),
280
292
  cliVersion: cli.version, cliVersionProbe: cli.probe, ...(cli.why ? { cliVersionWhy: cli.why } : {}), cliSource: cli.source,
281
293
  cliFloor: cli.floor ?? null, cliBelowFloor: cli.belowFloor ?? null,
282
294
  wrote, warm: warm || undefined, warmEscalated: attempt === warmEscalatedAt || undefined,
@@ -59,7 +59,7 @@ export async function retryMode({ name }, { attempt, lastFail, lastJson, lastKil
59
59
  }
60
60
 
61
61
  export async function dispatchTurn(stage, { attempt, warm, timeoutWarm, vetoedResume, lastFail, lastKey, lastSessionRef, warmEscalatedAt, effTimeout }) {
62
- const { name, engine, stageHome, agent, message, refreshMessage, model, thinking, sessionKey, stallSec, files, maxRetries, runDir, followup, adds,
62
+ const { name, engine, stageHome, agent, message, refreshMessage, model, thinking, speed, sessionKey, stallSec, files, maxRetries, runDir, followup, adds,
63
63
  supplementalLane, gatherAllowedTools, gatherSeatWrites, turnOutput, engineSkillsDir, engineSkillsGrantRoots, engineResolveSkill, turnConfig } = stage;
64
64
  // Snapshot each expected artifact at THIS attempt's start. TWO readers, one base — so they can never
65
65
  // disagree about what this dispatch emitted:
@@ -135,7 +135,7 @@ export async function dispatchTurn(stage, { attempt, warm, timeoutWarm, vetoedRe
135
135
  // already holds them, and its message names none. The dispatch record and the witness above keep the composed text.
136
136
  const wire = warm || timeoutWarm ? { text: effMessage, inlined: [], missing: [] }
137
137
  : inlineManuals(effMessage, { resolve: engineResolveSkill, skillsDir: engineSkillsDir });
138
- const turn = await engine.runTurn({ agent, sessionKey: key, message: wire.text, grantDispatch: base, model, thinking, timeoutSec: effTimeout, resumeRef: warm ? lastSessionRef : undefined, stageHome, mcpConfig, allowedTools: gatherAllowedTools, builtinTools: builtinToolsFor(name), output: turnOutput, seatWrites: gatherSeatWrites, skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
138
+ const turn = await engine.runTurn({ agent, sessionKey: key, message: wire.text, grantDispatch: base, model, thinking, speed, timeoutSec: effTimeout, resumeRef: warm ? lastSessionRef : undefined, stageHome, mcpConfig, allowedTools: gatherAllowedTools, builtinTools: builtinToolsFor(name), output: turnOutput, seatWrites: gatherSeatWrites, skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
139
139
  progressFiles: files, // the no-progress watchdog's artifact-advance signal (anthropic-agent; other adapters ignore it)
140
140
  // The raw stream of this session, beside its dispatch record (engine/session-record.mjs). The engines
141
141
  // keep it while the disk has room and say on the tuple's `stream` what landed.
@@ -93,7 +93,7 @@ export async function repairFormInDispatch(stage, { judgeArtifacts }, { attempt,
93
93
  // — AND THE OUTPUT RULE IS THE STAGE'S, on both engines. A recording stage's form repair is a record call, so the turn
94
94
  // keeps that stage's rule (engine/common.mjs, outputRule). It is read from the declaration, so the grant decided above
95
95
  // is not touched.
96
- const rt = await engine.runTurn({ agent, sessionKey: key, message: repairMessage, model, thinking, output: turnOutput,
96
+ const rt = await engine.runTurn({ agent, sessionKey: key, message: repairMessage, model, thinking, speed: stage.speed, output: turnOutput,
97
97
  timeoutSec: effTimeout, resumeRef: repairRef, stageHome, mcpConfig: turnConfig(effTimeout), allowedTools: gatherAllowedTools, builtinTools: builtinToolsFor(name),
98
98
  skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
99
99
  progressFiles: files, streamFile: streamFilePath(runDir, name, attempt, formRepairsUsed + 1) });
@@ -9,6 +9,8 @@ import { config } from "../driver.config.mjs";
9
9
  import { withSendUntil, declaredStageOfLabel } from "../engine/mcp/gather-config.mjs";
10
10
  import { sendReserveMs } from "../../providers/_shared/send-until.mjs"; // each turn's plan calls stop sending ahead of its deadline
11
11
  import { resolveAuthMode } from "../engine/auth.mjs";
12
+ import { turnSpeed } from "../engine/speed.mjs";
13
+ import { urgentForRun } from "../engine/run-choices.mjs";
12
14
  import { REGISTER_ENUMERATE_TOOL } from "../stages.mjs";
13
15
  import { stageTools } from "./stage-tools.mjs";
14
16
  import { STAGE_DECLARATIONS, declaredStageOf, replyIsOutput, turnOutputOf } from "../stage-declarations.mjs";
@@ -72,7 +74,11 @@ export function stageOf(name, opts, stageHome, engine) {
72
74
  // EACH TURN'S OWN COPY of the stage's tool config, carrying that turn's time to stop sending: ahead of the turn's
73
75
  // deadline by the reserve, so a plan call returns what it holds while the turn can still write it (send-until.mjs).
74
76
  const turnConfig = (sec) => withSendUntil(gatherMcpConfig, Date.now() + sec * 1000 - sendReserveMs(sec));
75
- return { name, engine, stageHome, agent, message, refreshMessage, model, thinking, sessionKey, timeoutSec, stallSec, files, validate,
77
+ // THE STAGE'S SPEED, fixed for the ladder: fast on every stage of a run recorded Urgent, standard otherwise
78
+ // (engine/speed.mjs). Every attempt, warm resume and repair below asks for it, so none pays for its context twice; the
79
+ // adapter sends it only where the stage's model has a faster setting, and the attempt's record says so where not.
80
+ const speed = turnSpeed({ urgent: urgentForRun(runDir) });
81
+ return { name, engine, stageHome, agent, message, refreshMessage, model, thinking, speed, sessionKey, timeoutSec, stallSec, files, validate,
76
82
  maxRetries, runDir, followup, bandSize, derivedLimit, adds, supplementalLane, auth, gatherAllowedTools, gatherSeatWrites: seatWrites,
77
83
  declaration: declared, turnOutput: turnOutputOf(declared ?? STAGE_DECLARATIONS[declaredStageOfLabel(name)] ?? null), engineSkillsDir, engineSkillsGrantRoots, engineResolveSkill, turnConfig };
78
84
  }
@@ -198,7 +198,12 @@ export async function markLogos(runDir, { findingsPath = null, registerRecordsPa
198
198
  const registerRecords = read(registerRecordsPath);
199
199
  // The page's own rule for which filings a name's table shows, loaded only for a Knockout, with the run's own rated names
200
200
  // unless the caller names another file: left to each caller, a pass run by hand that forgot them asked about nothing.
201
- const shown = registerRecordsPath ? (await import("./publish/render-knockout.mjs")).shownFilings : null;
201
+ // A Knockout's filing cards draw their filing's logo too (owner, 2026-11-25), so the logo step asks about the filings
202
+ // the cards draw beside the table's rows: at most three more a name. The card's own rule, with the run's frozen ladder.
203
+ const ko = registerRecordsPath ? await import("./publish/render-knockout.mjs") : null;
204
+ let ladder = null;
205
+ if (ko) { try { ladder = (await import("./framework.mjs")).parseFrameworkManifest(JSON.parse(readFileSync(paths(runDir).framework, "utf8"))); } catch { ladder = null; } }
206
+ const shown = ko ? (entry, m) => [...(ko.shownFilings(entry, m) ?? []), ...ko.cardFilings(registerRecords, m, ladder)] : null;
202
207
  const namesPath = knockoutFindingsPath ?? (registerRecordsPath ? (await import("./stages-knockout.mjs")).koPaths(runDir).findings : null);
203
208
  // A clearance card's own rule for which registrations it draws, over the records the run saved, as the page reads them.
204
209
  // A registration past the card's eighth is left out; one the run holds no record of stays, and asks nothing, as before.
@@ -0,0 +1,184 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ // order-receipt.mjs — what became of an accepted order, looked up by the reference its door returned, for the account
4
+ // that placed it. Internal: nothing here sends a notice, and no door shows it yet.
5
+ //
6
+ // WHY A LOOKUP AND NOT A NEW RECORD. Everything a receipt needs is already on disk, in the queue directory, under the
7
+ // order's own reference (`<id>`, the queue file's name, which every door returns):
8
+ //
9
+ // <id>.json accepted, waiting for a worker
10
+ // <id>.processing.claimed-<tok> a worker took it and stopped mid-claim; it is reclaimed under the same reference
11
+ // <id>.processing claimed, its pre-start checks under way
12
+ // <id>.processing.meta written at dispatch, AFTER those checks passed: the run's identity is minted
13
+ // <id>.postponed (+ .meta) parked, by a provider cap or our own recovery backoff; it resumes by itself
14
+ // <id>.failed + .failed.reason refused at the claim, before any run existed (failAtIntake)
15
+ // <id>.duplicate + .reason refused as the same matter as an earlier order (parkDuplicate)
16
+ // <id>.{done,failed,cancelled}.result the run's own outcome, with its run directory
17
+ //
18
+ // Nothing in the driver or the scripts deletes a terminal marker or its `.reason` / `.result`, so they last as long
19
+ // as the queue directory does. Reading them is therefore the durable receipt; a second store would be a second answer
20
+ // to the same question.
21
+ //
22
+ // THREE ANSWERS, NOT TWO, as `accountUsage` keeps them: `found`, `not-found`, and `could-not-look` (a queue directory
23
+ // that would not open is not "no such order"). An order that belongs to another account answers `not-found`, exactly
24
+ // as one that does not exist: neither its existence nor its reason is anybody else's to learn.
25
+ import { readdirSync, readFileSync, existsSync, statSync } from "node:fs";
26
+ import { join, basename, dirname } from "node:path";
27
+ import { deriveSlug } from "./phase0.mjs";
28
+ import { stopReason } from "../shared/stop-reason.mjs"; // a cancelled order says it was stopped, never a blank reason
29
+
30
+ /**
31
+ * The reference an order is known by: its queue file's name. The connector's start_run admits exactly these ids, so a
32
+ * reference outside this set names no order, and is refused before it reaches a path. Mirrors start_run's validator.
33
+ */
34
+ export const ORDER_REF_MAX = 128;
35
+ export const ORDER_REF_RE = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._@-]{0,${ORDER_REF_MAX - 1}}$`);
36
+
37
+ /** The states an order can be in, in the words the receipt uses. */
38
+ export const RECEIPT_STATES = Object.freeze({
39
+ waiting: "accepted and waiting for a worker",
40
+ checking: "taken by a worker; its checks before starting are under way",
41
+ running: "passed its checks; its run has started",
42
+ resumable: "parked, and will resume by itself",
43
+ refused: "refused before a run started",
44
+ failed: "its run stopped before delivering",
45
+ delivered: "its run finished",
46
+ cancelled: "stopped on request",
47
+ });
48
+ const TERMINAL = new Set(["refused", "failed", "delivered", "cancelled"]);
49
+
50
+ /**
51
+ * May this caller see this order? The scope `checkRunCaps` counts a lane by: the job's account, and for Generic the
52
+ * organisation it was filed under. A job that names no account (an email order before its claim) is visible only to
53
+ * a caller who sees everything. PURE.
54
+ */
55
+ export function orderInScope(job, scope) {
56
+ if (scope?.everything === true) return true;
57
+ const account = scope?.account ?? null;
58
+ if (!account || !job || (job.profileKey ?? null) !== account) return false;
59
+ return account !== "generic" || (job.tenant ?? null) === (scope?.organisation ?? null);
60
+ }
61
+
62
+ const readJsonSafe = (p) => { try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; } };
63
+ const readTextSafe = (p) => { try { return readFileSync(p, "utf8"); } catch { return null; } };
64
+
65
+ /** A refusal's reason as the runner wrote it, without its own bookkeeping line ("notify: …"). */
66
+ function reasonFrom(text) {
67
+ if (text == null) return null;
68
+ const lines = String(text).split("\n").map((l) => l.trim()).filter((l) => l && !/^notify:/i.test(l));
69
+ return lines.length ? lines.join("\n") : null;
70
+ }
71
+
72
+ /** The canonical run id, `<slug>-<date>-<codename>`, from a run directory (`…/<slug>/<date>-<codename>`). */
73
+ const runIdFromDir = (runDir) => (runDir ? `${basename(dirname(runDir))}-${basename(runDir)}` : null);
74
+
75
+ /** The run id a dispatch minted, from the job and its `.meta`, before any `.result` exists. */
76
+ function runIdFromMeta(job, meta) {
77
+ if (!meta?.codename || !meta?.dateISO) return null;
78
+ try { return `${deriveSlug(job)}-${meta.dateISO}-${meta.codename}`; } catch { return null; }
79
+ }
80
+
81
+ /** The marker files for one reference in one queue directory, by the name they carry. */
82
+ function markersFor(qdir, names, ref) {
83
+ const own = names.filter((n) => n === `${ref}.json` || n.startsWith(`${ref}.`));
84
+ const has = (s) => own.includes(`${ref}.${s}`);
85
+ const claimed = own.find((n) => n.startsWith(`${ref}.processing.claimed-`) && !/\.(pid|meta|skips|tmp)$/.test(n)) ?? null;
86
+ return { own, has, claimed };
87
+ }
88
+
89
+ /**
90
+ * Read one order's receipt out of one queue directory, or null when the directory holds nothing for this reference.
91
+ * The job is read from whichever marker carries it; `.result` decides before `.meta`, so a refusal after dispatch reads
92
+ * as a refusal, and a run directory holding a park sentinel reads as resumable whatever the queue marker says.
93
+ */
94
+ export function receiptIn(qdir, ref, names) {
95
+ const { has, claimed } = markersFor(qdir, names, ref);
96
+ const at = (s) => join(qdir, `${ref}.${s}`);
97
+ const terminal = ["done", "failed", "cancelled", "duplicate"].find((s) => has(s)) ?? null;
98
+ const live = has("postponed") ? "postponed" : has("processing") ? "processing" : claimed ? "claimed" : has("json") ? "json" : null;
99
+ if (!terminal && !live) return null;
100
+ const markerPath = terminal ? at(terminal) : live === "claimed" ? join(qdir, claimed) : at(live);
101
+ const job = readJsonSafe(markerPath);
102
+ let updatedAt = null;
103
+ try { updatedAt = statSync(markerPath).mtime.toISOString(); } catch { /* the marker moved under us; the next read sees it */ }
104
+ const base = { reference: ref, job, updatedAt };
105
+
106
+ if (terminal) {
107
+ const result = readJsonSafe(at(`${terminal}.result`));
108
+ const reason = reasonFrom(readTextSafe(at(`${terminal}.reason`)));
109
+ // A CANCELLED ORDER SAYS IT WAS STOPPED: the stop's own recorded reason, or, where none was written (an order taken
110
+ // off the queue before it started), the shared stop sentence with nothing invented (shared/stop-reason.mjs).
111
+ if (terminal === "cancelled") return { ...base, state: "cancelled", reason: result?.reason ?? stopReason(), runId: runIdFromDir(result?.runDir) };
112
+ // A DUPLICATE'S RECORDED REASON NAMES THE EARLIER ORDER it matched (its message id), and that order may be another
113
+ // account's: the matter signature does not include the account. Only its first line, which says what happened,
114
+ // is the receipt's. Pointing to the earlier order is for a later increment, which can ask whether this caller may see it.
115
+ if (terminal === "duplicate") return { ...base, state: "refused", reason: reason ? reason.split("\n")[0] : null, runId: null, kind: "duplicate" };
116
+ if (terminal === "done") return { ...base, state: "delivered", reason: null, runId: runIdFromDir(result?.runDir) };
117
+ // `.failed`: refused at the claim (a reason, no result), refused at dispatch (a pre-run result), or a run that
118
+ // stopped. A run directory still holding a park sentinel is a run that will come back, not a failure.
119
+ const runDir = result?.runDir ?? null;
120
+ if (runDir && (existsSync(join(runDir, ".postponed")) || existsSync(join(runDir, ".resuming")))) {
121
+ return { ...base, state: "resumable", reason: null, runId: runIdFromDir(runDir) };
122
+ }
123
+ const beforeStart = !result || result.failedStage === "pre-run" || !runDir;
124
+ const why = reason ?? result?.reason ?? (result?.failedStage ? `stopped at ${result.failedStage}` : null);
125
+ return beforeStart
126
+ ? { ...base, state: "refused", reason: why, runId: null }
127
+ : { ...base, state: "failed", reason: why, runId: runIdFromDir(runDir) };
128
+ }
129
+ if (live === "postponed") {
130
+ const meta = readJsonSafe(at("postponed.meta"));
131
+ return { ...base, state: "resumable", reason: null, runId: runIdFromDir(meta?.runDir) ?? runIdFromMeta(job, meta) };
132
+ }
133
+ if (live === "processing") {
134
+ // CLAIMING IS NOT PASSING: `.meta` lands only at dispatch, after the checks. Without it the order is still being
135
+ // checked, and nothing here says it started.
136
+ const meta = readJsonSafe(at("processing.meta"));
137
+ return meta?.codename
138
+ ? { ...base, state: "running", reason: null, runId: runIdFromMeta(job, meta) }
139
+ : { ...base, state: "checking", reason: null, runId: null };
140
+ }
141
+ if (live === "claimed") return { ...base, state: "checking", reason: null, runId: null };
142
+ return { ...base, state: "waiting", reason: null, runId: null };
143
+ }
144
+
145
+ /**
146
+ * The receipt for `reference`, as `scope` may see it.
147
+ *
148
+ * scope { account, organisation } for a company's caller, or { everything: true } for one who sees every order.
149
+ *
150
+ * Returns one of:
151
+ * { found: true, receipt: { reference, state, stateText, terminal, reason, runId, account, organisation, updatedAt } }
152
+ * { found: false, basis: "not-found" } no order by that reference that this caller may see
153
+ * { found: false, basis: "invalid-reference" } not a reference any door issues
154
+ * { found: false, basis: "could-not-look", unreadable } a queue directory would not open: not an answer
155
+ * { found: false, basis: "ambiguous" } two queue directories hold it; neither is picked
156
+ */
157
+ export function orderReceipt({ queueDirs, reference, scope } = {}) {
158
+ const ref = String(reference ?? "");
159
+ if (!ORDER_REF_RE.test(ref) || ref.includes("..")) return { found: false, basis: "invalid-reference" };
160
+ const dirs = (Array.isArray(queueDirs) ? queueDirs : []).filter((d) => typeof d === "string" && d);
161
+ const hits = [];
162
+ let unreadable = 0;
163
+ for (const qdir of dirs) {
164
+ let names;
165
+ try { names = readdirSync(qdir); }
166
+ catch (e) { if (e?.code !== "ENOENT") unreadable++; continue; }
167
+ const r = receiptIn(qdir, ref, names);
168
+ if (r) hits.push(r);
169
+ }
170
+ const visible = hits.filter((r) => orderInScope(r.job, scope));
171
+ if (visible.length > 1) return { found: false, basis: "ambiguous" };
172
+ if (visible.length === 1) {
173
+ const r = visible[0];
174
+ return { found: true, receipt: {
175
+ reference: r.reference, state: r.state, stateText: RECEIPT_STATES[r.state], terminal: TERMINAL.has(r.state),
176
+ reason: r.reason ?? null, runId: r.runId ?? null, ...(r.kind ? { kind: r.kind } : {}),
177
+ account: r.job?.profileKey ?? null, ...(r.job?.profileKey === "generic" ? { organisation: r.job?.tenant ?? null } : {}),
178
+ updatedAt: r.updatedAt,
179
+ } };
180
+ }
181
+ // Not found by this caller. A directory that would not open makes that a floor, not an answer.
182
+ if (unreadable) return { found: false, basis: "could-not-look", unreadable };
183
+ return { found: false, basis: "not-found" };
184
+ }
@@ -2,7 +2,7 @@
2
2
  "name": "clearotron-driver",
3
3
  "private": true,
4
4
  "type": "module",
5
- "version": "0.7.0-beta.4",
5
+ "version": "0.8.0-beta.0",
6
6
  "license": "AGPL-3.0-only",
7
7
  "description": "Deterministic driver for the trademark clearance workflow: orchestration in code (fan-out, fan-in barrier, gating, retries); the model does judgment leaves only, through a reasoning CLI spawned per stage.",
8
8
  "engines": {
@@ -14,6 +14,9 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "exceljs": "^4.4.0",
17
+ "jpeg-js": "^0.4.4",
18
+ "omggif": "^1.0.10",
19
+ "pngjs": "^7.0.0",
17
20
  "undici": "^7.29.1"
18
21
  }
19
22
  }
@@ -0,0 +1,21 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // picture-shrink-worker.mjs — brings one web picture down to its box, off the main thread (web-pictures.mjs).
5
+ //
6
+ // Decoding holds the thread that does it. Run here, it leaves the picture step's own clock free to end the step at its
7
+ // limit: the step stops this worker there, and a picture still being shrunk is recorded as not shrunk in time.
8
+ import { parentPort } from "node:worker_threads";
9
+ import { thumbnailOf, declaredSize } from "./picture-thumbnail.mjs";
10
+ import { imageTypeOf } from "./mark-logos.mjs";
11
+
12
+ parentPort.on("message", ({ id, bytes }) => {
13
+ const t0 = performance.now();
14
+ const picture = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
15
+ const served = declaredSize(picture, imageTypeOf(picture)?.type);
16
+ const t = thumbnailOf(picture);
17
+ const ms = Math.round(performance.now() - t0);
18
+ if (t.refused) { parentPort.postMessage({ id, ms, served, refused: t.refused }); return; }
19
+ const out = new Uint8Array(t.bytes);
20
+ parentPort.postMessage({ id, ms, served, contentType: t.contentType, width: t.width, height: t.height, kept: t.kept, bytes: out }, [out.buffer]);
21
+ });
@@ -0,0 +1,132 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // picture-thumbnail.mjs — a web picture brought down to what its box on the report needs, on this machine.
5
+ //
6
+ // A site's preview picture is served for a social card, often 1200 pixels wide and hundreds of kilobytes, and the report
7
+ // draws it in a box of PICTURE_BOX CSS pixels. Embedded as served, the pictures of two measured clearances grew their
8
+ // reports from 316 KB to 3,765 KB and from 267 KB to 686 KB (measured in testing, 2026-11-26). So each picture is decoded
9
+ // here, scaled down by averaging every source pixel it covers, kept in proportion, laid on the white its box shows, and
10
+ // written as a JPEG. No service and no AI program is asked.
11
+ //
12
+ // THE BYTES COME FROM ANY SITE. A picture's width and height are read before it is decoded, and one above
13
+ // PICTURE_MAX_PIXELS is not decoded at all: a few megabytes can declare a picture that would take gigabytes to hold.
14
+ // JPEG, PNG and GIF (its first frame) are decoded. A WebP is not, as the engine ships no WebP decoder: it is kept as
15
+ // served only where it is already as small as SERVED_WEBP_MAX_BYTES, and is otherwise not shown. Nothing here throws.
16
+ import jpeg from "jpeg-js";
17
+ import pngjs from "pngjs";
18
+ import omggif from "omggif";
19
+ import { imageTypeOf } from "./mark-logos.mjs";
20
+
21
+ // The box a web picture is drawn in: `.rr-lg img` in the report's stylesheet, 94 by 72, less its padding and border.
22
+ export const PICTURE_BOX = Object.freeze({ width: 82, height: 60 });
23
+ export const PICTURE_PIXEL_RATIO = 3; // pixels per CSS pixel: sharp on a phone's screen and on paper
24
+ export const PICTURE_MAX_PIXELS = 25_000_000; // a picture larger than this is not decoded
25
+ export const SERVED_WEBP_MAX_BYTES = 48 * 1024; // a WebP no larger than this is kept as served
26
+ const JPEG_QUALITY = 82;
27
+
28
+ /** The width and height a picture's header declares, without decoding it; null where it cannot be read. PURE. */
29
+ export function declaredSize(bytes, type) {
30
+ const b = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? []);
31
+ if (type === "image/png" && b.length >= 24 && b.subarray(12, 16).toString("latin1") === "IHDR") return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
32
+ if (type === "image/gif" && b.length >= 10) return { width: b.readUInt16LE(6), height: b.readUInt16LE(8) };
33
+ if (type === "image/jpeg") {
34
+ for (let i = 2; i + 9 < b.length;) {
35
+ if (b[i] !== 0xff) return null;
36
+ const marker = b[i + 1];
37
+ if (marker === 0xff) { i++; continue; }
38
+ const length = b.readUInt16BE(i + 2);
39
+ // Every start-of-frame marker but the three that are not frames (DHT, JPG, DAC) carries the size.
40
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { width: b.readUInt16BE(i + 7), height: b.readUInt16BE(i + 5) };
41
+ i += 2 + length;
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+
47
+ function decodeRgba(bytes, type) {
48
+ if (type === "image/jpeg") {
49
+ const img = jpeg.decode(bytes, { formatAsRGBA: true, useTArray: true, maxResolutionInMP: PICTURE_MAX_PIXELS / 1e6, maxMemoryUsageInMB: 512 });
50
+ return { width: img.width, height: img.height, data: img.data };
51
+ }
52
+ if (type === "image/png") { const img = pngjs.PNG.sync.read(bytes); return { width: img.width, height: img.height, data: img.data }; }
53
+ if (type === "image/gif") {
54
+ const gif = new omggif.GifReader(new Uint8Array(bytes));
55
+ const data = new Uint8Array(gif.width * gif.height * 4);
56
+ gif.decodeAndBlitFrameRGBA(0, data);
57
+ return { width: gif.width, height: gif.height, data };
58
+ }
59
+ return null;
60
+ }
61
+
62
+ /** The size a picture is drawn at: within the box at PICTURE_PIXEL_RATIO, in proportion, never enlarged. PURE. */
63
+ export function fittedSize(width, height, box = PICTURE_BOX, ratio = PICTURE_PIXEL_RATIO) {
64
+ const scale = Math.min((box.width * ratio) / width, (box.height * ratio) / height, 1);
65
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
66
+ }
67
+
68
+ // Each target pixel is the average of the source pixels it covers, a pixel cut by its edge counted by the part inside.
69
+ // Run along each row, then down each column. The picture is laid on white first, as its box shows it.
70
+ function spans(from, to) {
71
+ const k = from / to, first = new Int32Array(to), count = new Int32Array(to), weights = [];
72
+ for (let d = 0; d < to; d++) {
73
+ const a = d * k, z = (d + 1) * k, lo = Math.floor(a), hi = Math.min(from, Math.ceil(z));
74
+ first[d] = lo; count[d] = hi - lo;
75
+ for (let s = lo; s < hi; s++) weights.push((Math.min(z, s + 1) - Math.max(a, s)) / k);
76
+ }
77
+ return { first, count, weight: Float32Array.from(weights) };
78
+ }
79
+
80
+ function downscaleOnWhite({ width: sw, height: sh, data }, dw, dh) {
81
+ const xs = spans(sw, dw), ys = spans(sh, dh);
82
+ const rgb = new Float32Array(sw * 3);
83
+ const rows = new Float32Array(dw * sh * 3);
84
+ for (let y = 0; y < sh; y++) {
85
+ for (let x = 0, i = y * sw * 4; x < sw; x++, i += 4) {
86
+ const a = data[i + 3] / 255, white = 255 - data[i + 3];
87
+ rgb[x * 3] = data[i] * a + white; rgb[x * 3 + 1] = data[i + 1] * a + white; rgb[x * 3 + 2] = data[i + 2] * a + white;
88
+ }
89
+ for (let x = 0, w = 0; x < dw; x++) {
90
+ let r = 0, g = 0, b = 0;
91
+ for (let s = xs.first[x], n = xs.count[x]; n > 0; s++, n--, w++) { const f = xs.weight[w], j = s * 3; r += rgb[j] * f; g += rgb[j + 1] * f; b += rgb[j + 2] * f; }
92
+ const o = (y * dw + x) * 3; rows[o] = r; rows[o + 1] = g; rows[o + 2] = b;
93
+ }
94
+ }
95
+ const out = new Uint8ClampedArray(dw * dh * 4); // rounds and clamps each channel as it is written
96
+ for (let y = 0, w = 0; y < dh; y++) {
97
+ const acc = new Float32Array(dw * 3);
98
+ for (let s = ys.first[y], n = ys.count[y]; n > 0; s++, n--, w++) {
99
+ const f = ys.weight[w], base = s * dw * 3;
100
+ for (let j = 0; j < dw * 3; j++) acc[j] += rows[base + j] * f;
101
+ }
102
+ for (let x = 0; x < dw; x++) { const o = (y * dw + x) * 4; out[o] = acc[x * 3]; out[o + 1] = acc[x * 3 + 1]; out[o + 2] = acc[x * 3 + 2]; out[o + 3] = 255; }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /**
108
+ * The picture as the report embeds it: `{ bytes, contentType, width, height, kept }`, where `kept` is "as served" when the
109
+ * picture already fitted its box and was no larger than a thumbnail of it, and "thumbnail" otherwise; or `{ refused }`
110
+ * with the reason it is not shown. Never throws. PURE.
111
+ */
112
+ export function thumbnailOf(bytes) {
113
+ const type = imageTypeOf(bytes)?.type ?? null;
114
+ if (!type) return { refused: "not a PNG, JPEG, GIF or WebP" };
115
+ if (type === "image/webp") {
116
+ return bytes.length <= SERVED_WEBP_MAX_BYTES ? { bytes, contentType: type, width: null, height: null, kept: "as served" }
117
+ : { refused: `a WebP larger than ${SERVED_WEBP_MAX_BYTES / 1024} KB, which is not decoded here` };
118
+ }
119
+ const declared = declaredSize(bytes, type);
120
+ if (!declared || !declared.width || !declared.height) return { refused: "its size cannot be read" };
121
+ if (declared.width * declared.height > PICTURE_MAX_PIXELS) return { refused: `larger than ${PICTURE_MAX_PIXELS / 1e6} million pixels` };
122
+ let img;
123
+ try { img = decodeRgba(bytes, type); } catch (e) { return { refused: `it does not decode: ${String(e?.message ?? e).slice(0, 80)}` }; }
124
+ if (!img?.width || !img?.height) return { refused: "it does not decode" };
125
+ const size = fittedSize(img.width, img.height);
126
+ let out;
127
+ try { out = jpeg.encode({ width: size.width, height: size.height, data: downscaleOnWhite(img, size.width, size.height) }, JPEG_QUALITY).data; }
128
+ catch (e) { return { refused: `it could not be written: ${String(e?.message ?? e).slice(0, 80)}` }; }
129
+ const fits = img.width <= PICTURE_BOX.width * PICTURE_PIXEL_RATIO && img.height <= PICTURE_BOX.height * PICTURE_PIXEL_RATIO;
130
+ if (fits && bytes.length <= out.length) return { bytes, contentType: type, width: img.width, height: img.height, kept: "as served" };
131
+ return { bytes: out, contentType: "image/jpeg", width: size.width, height: size.height, kept: "thumbnail" };
132
+ }
@@ -36,6 +36,7 @@ import { endTheDeliveredRun, runShell } from "./run-shell.mjs"; // — the run
36
36
  import { logTurnaroundReconciliation } from "./run-quote.mjs";
37
37
  import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel, stopsWithTheRun } from "./cancel.mjs"; // stop-by-user: never the failure lane below
38
38
  import { attachFramework } from "./run-attachments.mjs"; // the one framework freeze, both products'
39
+ import { stampKnockoutPlainLanguage } from "./knockout-plain-language.mjs";
39
40
  import { KO_STAGES, KO_STEPS, KO_STEP_REGISTER_COUNT, koSteps, koPaths, kebab, knockoutGridSpec, KNOCKOUT_WEB, KNOCKOUT_MINUTES_BAR, knockoutBarVerdict, koChunks, groupRecordsDoc, filingsOnce, expandFilingsOnce, sameRecord, calibrationExcerptOf, readerProviderDoc } from "./stages-knockout.mjs";
40
41
  import { workedExamplesFor } from "./framework.mjs"; // which worked examples the rating's calibration comes from
41
42
  import { familiesDefect } from "./knockout-frame-record.mjs";
@@ -603,6 +604,14 @@ function checkedFamilies(runDir, rows, plan) {
603
604
  if (defect) { runLog(runDir, { event: "knockout-families-refused", defect: defect.slice(0, 300) }); return null; }
604
605
  return families;
605
606
  }
607
+ /**
608
+ * The readers that did not finish, in reader order rather than the order they settled in, sorted in place. The failure
609
+ * rethrown, the note and the run log's cause then name the lowest-numbered reader, so two runs of one order record the
610
+ * same one.
611
+ */
612
+ export function inReaderOrder(failures) { // @internal — driven by its test
613
+ return failures.sort((a, b) => a.c - b.c);
614
+ }
606
615
  function orderFamilies(runDir, names, plan) {
607
616
  const groups = koChunks(names, checkedFamilies(runDir, names, plan));
608
617
  runLog(runDir, { event: "knockout-families", source: plan?.batch?.families ? "intake" : "none", groups: groups.map((g) => g.length) });
@@ -681,6 +690,7 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
681
690
  } });
682
691
  } catch (e) { readerFailures.push({ c, e }); }
683
692
  }, { stop: () => readerFailures.some((f) => rateLimited(f) || f.e instanceof RunCancelled) });
693
+ inReaderOrder(readerFailures);
684
694
  const hard = readerFailures.find((f) => rateLimited(f) || f.e instanceof RunCancelled);
685
695
  if (hard) throw hard.e;
686
696
  // A STOP RECORDED WHILE THE READERS RAN ends the run here as a stop: a reader it cut short is not a reading that failed.
@@ -1105,6 +1115,8 @@ export async function knockoutInner(ctx, job, opts = {}) {
1105
1115
  // for reconcile-runs' exact liveness test. The stepper and the identity are separate calls now.
1106
1116
  ...identitySeed(),
1107
1117
  stepIndex: 0, stepLabel: STEPS[0], stepN: 1, stepTotal: STEPS.length,
1118
+ // Every step this run walks, by name and in order, as the clearance seed writes its own.
1119
+ steps: [...STEPS],
1108
1120
  review: null, url: null, failedStage: null, reason: null, deliveredAt: null,
1109
1121
  // A5/A3: a re-run of a previously-terminal knockout may reopen the state ONLY because the resume
1110
1122
  // guard cleared the sentinel (ctx.stateReset threads that authority); startedAt is no longer
@@ -1658,6 +1670,8 @@ export async function knockoutInner(ctx, job, opts = {}) {
1658
1670
  });
1659
1671
  sentinel(run.runDir, ".published", published);
1660
1672
  runLog(run.runDir, { event: "knockout-published", url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), overall, marks: merged.marks.length });
1673
+ // The plain-language counts by rating group and field, as saved and as published (knockout-plain-language.mjs).
1674
+ stampKnockoutPlainLanguage(run.runDir, merged);
1661
1675
  }
1662
1676
  // The knockout lane put its token total in the PUBLISHED ARTIFACT but never stamped the run itself,
1663
1677
  // so `status.json.tokens` was empty for every Stage-0 run however it ended (fixed 2026-07-28) — and
@@ -20,6 +20,9 @@ export function jobHashOf(job) {
20
20
  marks: JSON.stringify(marks), markName: String(job.markName ?? "").toLowerCase(),
21
21
  classes: JSON.stringify([...(job.classes ?? [])].sort()), goods: String(job.goods ?? ""),
22
22
  product: job.product ?? null, recipeKey: job.recipeKey ?? null,
23
+ // An Urgent order counts twice, so a review confirmed at Standard must not start it. Present only when true,
24
+ // so every Standard job hashes exactly as it did before the field existed.
25
+ ...(job.urgent === true ? { urgent: true } : {}),
23
26
  })).digest("base64url");
24
27
  }
25
28
  export function mintConfirmation({ secret, account, email, jobHash, now = Date.now(), ttlMs = 10 * 60 * 1000 }) {