clearotron 0.5.0 → 0.5.1-beta.1

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 (129) hide show
  1. package/CONTRIBUTING.md +2 -2
  2. package/INSTALL.md +351 -308
  3. package/QUICKSTART.md +12 -4
  4. package/README.md +12 -7
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +14 -11
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +73 -25
  9. package/bin/example.mjs +4 -2
  10. package/bin/onboard.mjs +647 -352
  11. package/bin/start.mjs +213 -66
  12. package/bin/update.mjs +26 -13
  13. package/build-info.json +2 -2
  14. package/docs/CLIENT-MCP.md +1 -1
  15. package/docs/PORTAL.md +2 -2
  16. package/docs/architecture/02-architecture.md +3 -3
  17. package/docs/architecture/04-configuration-reference.md +2 -3
  18. package/docs/architecture/05-config-governance.md +1 -1
  19. package/docs/architecture/06-operations-runbook.md +1 -1
  20. package/driver/CHANGELOG.md +91 -0
  21. package/driver/README.md +2 -2
  22. package/driver/config-inventory.mjs +20 -11
  23. package/driver/contract-e3-backlog.mjs +27 -27
  24. package/driver/contract-e3-baseline.json +2 -2
  25. package/driver/contract-vocabulary.mjs +1 -1
  26. package/driver/degraded-parts.mjs +67 -3
  27. package/driver/dev-portal.mjs +1 -1
  28. package/driver/digest-queue.mjs +5 -5
  29. package/driver/driver.config.mjs +9 -9
  30. package/driver/engine/CONTRACT.md +1 -1
  31. package/driver/engine/anthropic-agent.mjs +4 -2
  32. package/driver/engine/jx-turn.mjs +10 -2
  33. package/driver/engine/mcp/band-server.mjs +1 -21
  34. package/driver/engine/mcp/clarivate-propose-tool.mjs +26 -0
  35. package/driver/engine/mcp/clarivate-server.mjs +2 -18
  36. package/driver/engine/mcp/fixture-register-server.mjs +33 -0
  37. package/driver/engine/mcp/gather-config.mjs +48 -7
  38. package/driver/engine/mcp/recording-server.mjs +206 -14
  39. package/driver/engine/mcp/supplemental.mjs +4 -2
  40. package/driver/engine/openai-agent.mjs +3 -1
  41. package/driver/engine/probe.mjs +10 -0
  42. package/driver/filing-goods.mjs +95 -0
  43. package/driver/findings-model.mjs +3 -0
  44. package/driver/gateway.mjs +42 -40
  45. package/driver/how-it-runs.mjs +103 -0
  46. package/driver/knockout-assess-record.mjs +54 -4
  47. package/driver/knockout-correction-record.mjs +342 -0
  48. package/driver/knockout-frame-record.mjs +4 -2
  49. package/driver/knockout-register-read.mjs +705 -0
  50. package/driver/knockout-register-record.mjs +222 -0
  51. package/driver/knockout-review-record.mjs +96 -25
  52. package/driver/narrative-refutation-record.mjs +87 -1
  53. package/driver/order-tables.mjs +23 -0
  54. package/driver/owner-use-check.mjs +5 -2
  55. package/driver/package.json +1 -1
  56. package/driver/partial-payload-baseline.json +8 -0
  57. package/driver/pipeline-knockout.mjs +506 -313
  58. package/driver/pipeline.mjs +179 -86
  59. package/driver/portal-local-auth.mjs +7 -1
  60. package/driver/portal-service.mjs +99 -9
  61. package/driver/progress.mjs +2 -2
  62. package/driver/publish/index.mjs +18 -21
  63. package/driver/publish/knockout.mjs +40 -18
  64. package/driver/publish/render-knockout.mjs +40 -27
  65. package/driver/publish/report-dates.mjs +43 -0
  66. package/driver/recall-reconciliation.mjs +2 -2
  67. package/driver/record-goods.mjs +50 -9
  68. package/driver/register-count.mjs +12 -59
  69. package/driver/register-fixture-marker.mjs +22 -0
  70. package/driver/register-plan.mjs +48 -0
  71. package/driver/register-records.mjs +84 -266
  72. package/driver/register-taint.mjs +2 -2
  73. package/driver/repair-composers.mjs +15 -8
  74. package/driver/result-noun-fields.mjs +6 -2
  75. package/driver/run-requirements.mjs +111 -37
  76. package/driver/runner.mjs +9 -16
  77. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  78. package/driver/skills/knockout-assess/SKILL.md +101 -100
  79. package/driver/skills/knockout-frame/SKILL.md +3 -1
  80. package/driver/skills/knockout-register-read/SKILL.md +77 -0
  81. package/driver/stages-knockout.mjs +159 -98
  82. package/driver/stages.mjs +4 -2
  83. package/driver/suite-census.json +435 -81
  84. package/driver/systemd/README.md +2 -2
  85. package/driver/unit-environment.mjs +19 -0
  86. package/driver/verify-knockout.mjs +175 -39
  87. package/driver/verify.mjs +10 -9
  88. package/mcp-server/CHANGELOG.md +8 -0
  89. package/mcp-server/CONNECT.md +4 -0
  90. package/mcp-server/demo-mode.mjs +6 -0
  91. package/mcp-server/lib/demo-texts.mjs +38 -0
  92. package/mcp-server/lib/http-handler.mjs +7 -1
  93. package/mcp-server/lib/knockout.mjs +3 -2
  94. package/mcp-server/lib/options.mjs +3 -1
  95. package/mcp-server/lib/plan.mjs +6 -1
  96. package/mcp-server/lib/runs.mjs +7 -2
  97. package/mcp-server/mint-token.mjs +1 -1
  98. package/mcp-server/package.json +1 -1
  99. package/mcp-server/serve.mjs +11 -0
  100. package/mcp-server/server.mjs +13 -5
  101. package/package.json +1 -1
  102. package/portal-ui/dist/assets/{index-D2wrw9cH.css → index-AtB9ZpDH.css} +29 -0
  103. package/portal-ui/dist/assets/{index-DcLbvFmQ.js → index-fPqAU0sx.js} +237 -231
  104. package/portal-ui/dist/index.html +2 -2
  105. package/portal-ui/package.json +4 -4
  106. package/providers/README.md +4 -4
  107. package/providers/_shared/execute-plan.mjs +45 -1
  108. package/providers/_shared/term-shape.mjs +1 -1
  109. package/providers/clarivate/src/capabilities.js +7 -6
  110. package/providers/clarivate/src/core.js +11 -7
  111. package/providers/clarivate/src/wider-list.js +104 -0
  112. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  113. package/providers/oauth-mcp-bridge/package.json +1 -1
  114. package/providers/signa/src/capabilities.js +0 -9
  115. package/scripts/e2e-first-time.mjs +8 -7
  116. package/scripts/freeze-example-run.mjs +2 -2
  117. package/scripts/settings-render-check.mjs +5 -3
  118. package/scripts/test-run.mjs +8 -2
  119. package/shared/client-door.mjs +11 -8
  120. package/shared/connect-clients.mjs +10 -4
  121. package/shared/demo-connection.mjs +43 -0
  122. package/shared/demo-start-args.mjs +7 -2
  123. package/shared/invocation.mjs +18 -3
  124. package/shared/permanent-install.mjs +24 -0
  125. package/shared/scope.mjs +8 -1
  126. package/shared/server-units.mjs +37 -1
  127. package/shared/stdio-connect.mjs +43 -21
  128. package/shared/trigger-lane.mjs +7 -0
  129. package/shared/tty-style.mjs +21 -5
@@ -72,7 +72,7 @@ export const TOOL_WRITTEN_ARTIFACTS = new Map([
72
72
  // CALL: the seat's grant carries no Write, so a ladder handing it the write form would order a
73
73
  // hand-write it cannot perform, on a stage whose failure is deliberately quiet.
74
74
  ["knockout-review.json", { tool: "record_knockout_review", what: "your rewrites of the lines a reader sees first",
75
- refusals: (runDir) => knockoutReviewRefusalsFor(runDir) }],
75
+ refusals: (runDir) => knockoutReviewRefusalsFor(runDir) }], ["knockout-register.json", { tool: "record_knockout_register_read", what: "what you carried forward, set aside and did not ask", refusals: (runDir) => knockoutRegisterRefusalsFor(runDir) }],
76
76
  [BLIND_FRAME_MODEL_FILE, { tool: "record_blind_frame", what: "the threat model" }],
77
77
  [SKEPTIC_FLAGS_FILE, { tool: "record_skeptic", what: "your flags and escalation decisions" }],
78
78
  ["senior-eye-review.md", { tool: "record_narrative_refutation", what: "your verdict and typed flags" }],
@@ -201,6 +201,8 @@ export const TOOL_WRITTEN_PATTERNS = Object.freeze([
201
201
  what: "this chunk's rated assessment",
202
202
  sample: basename(knockoutAssessChunkFile("", 0)),
203
203
  }),
204
+ Object.freeze({ re: KNOCKOUT_CORRECTION_RE, tool: "record_knockout_correction", what: "your answer to each defect, and what you repaired", sample: basename(knockoutCorrectionFile("", 0)) }),
205
+ Object.freeze({ re: KNOCKOUT_RECHECK_RE, tool: "record_knockout_review", what: "your second look at the corrected record", sample: basename(knockoutReviewFile("", 1)) }),
204
206
  ]);
205
207
 
206
208
  /**
@@ -234,11 +236,11 @@ export { everyToolCallRefused };
234
236
  import { unitRefusalsFor } from "./register-unit-record.mjs";
235
237
  // The chunk artifact's name shape, IMPORTED from the module that constructs the path — never restated
236
238
  // here. See TOOL_WRITTEN_PATTERNS below for why this table reads a pattern instead of owning one.
237
- import { KNOCKOUT_ASSESS_CHUNK_RE, knockoutAssessChunkFile } from "./knockout-assess-record.mjs";
239
+ import { KNOCKOUT_ASSESS_CHUNK_RE, knockoutAssessChunkFile } from "./knockout-assess-record.mjs"; import { KNOCKOUT_CORRECTION_RE, knockoutCorrectionFile } from "./knockout-correction-record.mjs";
238
240
  // The frame transport's refusal reader, so a missing plan or note can be told apart from a stage that
239
241
  // never called its tool — the distinction, which its sibling stage still lacks.
240
- import { frameRefusalsFor } from "./knockout-frame-record.mjs";
241
- import { knockoutReviewRefusalsFor } from "./knockout-review-record.mjs";
242
+ import { frameRefusalsFor } from "./knockout-frame-record.mjs"; import { knockoutRegisterRefusalsFor } from "./knockout-register-record.mjs";
243
+ import { KNOCKOUT_RECHECK_RE, knockoutReviewFile, knockoutReviewRefusalsFor } from "./knockout-review-record.mjs";
242
244
  import { profilesStoreDir } from "./profiles.mjs";
243
245
  // The supplemental lane's single source (stages.mjs). The import is acyclic — stages.mjs reads
244
246
  // verify/coverage-ledger/config/framework and never reaches back here.
@@ -460,18 +462,18 @@ export function tokensPerSec(usage, wall) {
460
462
  return Math.round((out / w) * 100) / 100;
461
463
  }
462
464
 
463
- // #5b — stop a warm/followup resume after ONE attempt when it ran to the HARD WALL. A followup (escalation,
464
- // envelope close, frame-reopen "enumerate to exhaustion" sweep) resumes an already-loaded session; if it
465
- // SIGKILLed at the full timeout+60 wall (signals.hardWall, NOT a 0-token stall), the same work re-issued at a
466
- // 1.5× extension just burns another full wall — so break and let the caller record the coverage-limited
467
- // deferral. The signal is `followup` (or a `warm` content-retry): NOTE `warm` ALONE never fires here on a
468
- // timeout — warmEligible() excludes `timeout`, so `warm` is always false on a timeout chain. That is exactly
469
- // the dead-code bug this predicate fixes: before threading `followup`, a hard-wall followup burned TWO attempts
470
- // (~2.5× the wall) instead of ONE (~1×). A STALL (no hardWall) is NOT stopped here — it keeps the normal
471
- // one-extended-shot retry, since a transient stall can clear. PURE + exported for test (the live hard-wall path
472
- // needs a 60s wall-clock kill, untestable in the offline suite — this predicate IS the policy under test).
473
- export function followupHardWallStop({ fail, warm, followup, signals }) {
474
- return fail === "timeout" && (Boolean(warm) || Boolean(followup)) && Boolean(signals?.hardWall);
465
+ // #5b — stop a WARM attempt after ONE try when it ran to the HARD WALL. The warm patch is the one rung that resumes
466
+ // a session: it is passed the session that just produced a content failure. If that resumed turn was SIGKILLed at
467
+ // the full timeout+60 wall (signals.hardWall, NOT a 0-token stall), break and let the caller record the
468
+ // coverage-limited deferral. A warm attempt can itself time out; warmEligible() only stops the attempt AFTER a
469
+ // timeout from being warm. A FOLLOWUP IS NOT STOPPED HERE. It is a new stage() call, attempt 1, with no resumeRef,
470
+ // so it is a fresh session with its own wall. This rule used to stop it too, on the premise that it resumed an
471
+ // already-loaded session, and that premise was false; it now gets the one extended retry any fresh dispatch gets.
472
+ // Measured 2026-11-05 over saved runs: no follow-up attempt and no warm attempt had timed out, so neither form of
473
+ // the rule had decided a run. A STALL (no hardWall) is NOT stopped here: it keeps its one retry at the same budget,
474
+ // since a transient stall can clear. PURE + exported for test: the live path needs a wall-clock kill.
475
+ export function warmHardWallStop({ fail, warm, signals }) {
476
+ return fail === "timeout" && Boolean(warm) && Boolean(signals?.hardWall);
475
477
  }
476
478
 
477
479
  // D3 — Anthropic overload (HTTP 529 / overloaded_error). Through claude -p a 529 surfaces as a FAILED
@@ -479,8 +481,8 @@ export function followupHardWallStop({ fail, warm, followup, signals }) {
479
481
  // generically it looked like `nonzero_exit_1` and the ladder re-attempted INSTANTLY, hammering an API
480
482
  // that just said "go away" (and burning the retry budget in seconds — the 04:30 restart-window shape).
481
483
  // Detect it and reclassify to `status_overloaded`, the token the normalized --json envelope already
482
- // produces for the same condition: FALLBACK_ELIGIBLE routes it to the chain's model cascade,
483
- // TRANSIENT_RE routes an exhausted chain to the recovery park (.postponed + escalating backoff) — the
484
+ // produces for the same condition: the stage fails on its one model (there is no model cascade), and
485
+ // TRANSIENT_RE routes that failure to the recovery park (.postponed + escalating backoff) — the
484
486
  // existing machinery owns the re-attempt; runStage breaks its own ladder on it (mirrors lane_wedge).
485
487
  // The 529 match is deliberately ANCHORED (api error / http prefix, or overload vocabulary within the
486
488
  // same line) so a stray "529" in ordinary output never misroutes a real content failure. PURE + exported.
@@ -883,9 +885,9 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
883
885
  validate,
884
886
  maxRetries = config.maxRetries,
885
887
  runDir,
886
- followup = false, // #5b: this run is a warm-resume / followup (escalation, envelope close, frame-reopen
887
- // sweep) — a hard-wall timeout breaks after ONE attempt (a 1.5× extension can't fit
888
- // an already-over-budget resume; the caller records the coverage-limited deferral).
888
+ followup = false, // the caller's word that this dispatch is a followup: a FRESH session (attempt 1, no
889
+ // resumeRef), journalled on every row beside `warm`. At its hard wall it takes the same
890
+ // one extended retry as any fresh dispatch (warmHardWallStop stops only a warm attempt).
889
891
  excludeTools, bandSize, derivedLimit = null, // copper-lattice re-route: tool names dropped from this stage's allowedTools
890
892
  // THE CORRECTION THIS DISPATCH IS, when it is one: `{positions}`, the excluded positions its flags name. Its save may
891
893
  // add a finding for them, and its retries say so (`patchRows`); every other dispatch carries none.
@@ -1608,18 +1610,18 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1608
1610
  // a wedge is a `timeout` fail that breaks the ladder immediately, so no later attempt exists to judge.
1609
1611
  if (killClass) killSeen = true;
1610
1612
  // Lane-wedge reclassification (see isLaneWedge): a 0-token timeout is a saturated command lane, not a slow
1611
- // model. Becoming `lane_wedge` makes the retry policy skip the wasteful extended shot; the chain (pipeline.mjs)
1612
- // cascades providers on it and retries the whole chain if EVERY provider wedges (a shared lane is not
1613
- // provider-specific). teal-bastion 2026-06-15.
1613
+ // model. Becoming `lane_wedge` makes the retry policy skip the wasteful extended shot; stage() (pipeline.mjs)
1614
+ // waits for the lane to clear and dispatches the stage again on its one model (a shared lane is not
1615
+ // model-specific). teal-bastion 2026-06-15.
1614
1616
  // See classifyWedge: a 0-token timeout is a saturated-lane wedge UNLESS it's a hard-wall over-budget kill.
1615
1617
  fail = classifyWedge(fail, usage, turn.signals);
1616
1618
  // D3: an Anthropic 529/overload hides inside the generic transport tokens (nonzero_exit_1 through
1617
1619
  // claude -p) — reclassify to status_overloaded so it stops the same-model ladder below and rides the
1618
- // chain cascade / recovery park instead. Only the transport shapes are eligible: a timeout/wedge has
1620
+ // recovery park instead. Only the transport shapes are eligible: a timeout/wedge has
1619
1621
  // its own policy, and a content failure must never be laundered into a transient by a stray match.
1620
1622
  if (fail && /^(nonzero_exit_|status_error$|unparseable_json$)/.test(fail) && isOverloaded({ json, stdout: turn.stdout, stderr })) fail = "status_overloaded";
1621
1623
  // Rate-limit / session-cap (429): the standalone engine maps EVERY tier to the one Claude subscription, so
1622
- // the fallback cascade is futile — classify distinctly (NOT in FALLBACK_ELIGIBLE) and carry resetsAt so the
1624
+ // a re-run on any tier is futile — classify distinctly (NOT in FALLBACK_ELIGIBLE) and carry resetsAt so the
1623
1625
  // pipeline POSTPONES the run to resetsAt instead of failing it. (Overrides the nonzero_exit_1 a 429 shows as.)
1624
1626
  // Guarded on `fail`: a turn whose finished, validated artifact was just accepted (the exit-1 rescue above)
1625
1627
  // stays accepted — the NEXT stage's first turn hits the same cap at 0 tokens spent and postpones cleanly.
@@ -1950,8 +1952,8 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1950
1952
  }
1951
1953
 
1952
1954
  // sessionKey = the key that actually SUCCEEDED (attempt 1 = base key; a retry = `${base}-rerunN`). Callers
1953
- // that re-run a stage as a follow-up must resume THIS key, not the base key — else they resume a failed
1954
- // attempt's empty/partial session and lose the warm cache (winning-key hardening).
1955
+ // that re-run a stage as a follow-up pass THIS key, so the follow-up's records sit beside the attempt that
1956
+ // won (winning-key hardening). No engine resumes by key: resumeRef is the only continuity a turn has.
1955
1957
  if (!fail) return { ok: true, json, attempts: attempt, modelWire: lastModelWire, modelUsed: lastModelUsed, text: payloadText(json), sessionKey: key, attemptFails: [...attemptFails], warmEscalated: warmEscalatedAt > 0 || undefined, reads, readsTruncated, warm, wrote, formRepairs: formRepairsUsed };
1956
1958
  attemptFails.push(fail);
1957
1959
  lastFail = fail;
@@ -1969,7 +1971,7 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1969
1971
  // repeat-signature terminal) owns what happens next, with proper accounting — that lane's single
1970
1972
  // fresh sample replaces the blind third attempt this used to buy. Scoped to the content classes
1971
1973
  // (missing_file / invalid_file / max_tokens_no_output — same stage, same validator string); every
1972
- // transport class keeps its own policy (timeout's single extended shot, the chain cascade, the
1974
+ // transport class keeps its own policy (timeout's single extended shot, and the
1973
1975
  // wedge/overload breaks above and below).
1974
1976
  //
1975
1977
  // BUILD 2 — A4's PREMISE FAILS ON EXACTLY ONE ATTEMPT, AND IT IS THE ONE IT USUALLY FIRES ON.
@@ -2139,8 +2141,8 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
2139
2141
  }
2140
2142
 
2141
2143
  // Lane-wedge: the turn never got a command lane (0 tokens). The extended ×1.5 shot can't help (it produced
2142
- // nothing), and switching models can't fix a SHARED lane — so stop here and let the chain cascade fast. The
2143
- // chain-level lane-wedge retry (stage() in pipeline.mjs) waits for the lane to clear and retries the chain.
2144
+ // nothing), and another attempt on a SHARED lane cannot help — so stop here and hand it on fast. The
2145
+ // lane-wedge retry in stage() (pipeline.mjs) waits for the lane to clear and dispatches the stage again.
2144
2146
  if (fail === "lane_wedge") break;
2145
2147
  //: a model mismatch is a CONFIGURATION fault, not a transient. The next attempt sends the same
2146
2148
  // argv to the same provider and gets the same substitution, so retrying only buys the wrong model
@@ -2166,8 +2168,8 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
2166
2168
  }
2167
2169
  // D3: overload (529 / status_overloaded) — stop the ladder here: an in-ladder re-attempt hammers an
2168
2170
  // API that just said it is overloaded, seconds apart, on the SAME model. Breaking hands the failure
2169
- // to the existing machinery: the chain cascades models (FALLBACK_ELIGIBLE) and an exhausted chain
2170
- // parks the run for recovery with escalating backoff (TRANSIENT_RE → .postponed).
2171
+ // to the existing machinery: the stage fails on its one model (there is no model cascade), and that
2172
+ // failure parks the run for recovery with escalating backoff (TRANSIENT_RE → .postponed).
2171
2173
  if (fail === "status_overloaded") break;
2172
2174
  // Rate-limit: do NOT retry (every retry hits the same capped subscription) and do NOT fall back — return
2173
2175
  // immediately so the pipeline can postpone + auto-resume after the window. resetsAt rides the result.
@@ -2175,13 +2177,13 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
2175
2177
  // Timeout-aware retry: a genuinely over-budget/hung stage will just re-time-out on an identical
2176
2178
  // attempt (the v14 delivery burned 3 × 600s). Give it exactly ONE longer shot, then stop.
2177
2179
  if (fail === "timeout") {
2178
- // A warm-resume / followup (frame-reopen sweep, escalation, envelope close) that ran to its HARD WALL
2179
- // won't fit a 1.5× extension — break after this one attempt and let the caller record the coverage-limited
2180
- // DEFERRAL (which the gate clamps CLEAR→CONDITIONAL). See followupHardWallStop: the live signal is
2181
- // `followup` (threaded from stageOnce), NOT `warm` — `warm` is always false on a timeout chain, which is
2182
- // why this was dead code before the thread (a hard-wall followup burned ~2.5× the wall instead of ~1×).
2183
- if (followupHardWallStop({ fail, warm, followup, signals: turn.signals })) {
2184
- note(`[${name}] warm/followup hit the hard wall — breaking (a 1.5× extension won't fit; recording the deferral)`);
2180
+ // A WARM attempt, the one rung that resumes a session, that ran to its HARD WALL breaks after this attempt,
2181
+ // and the caller records the coverage-limited DEFERRAL (which the gate clamps CLEAR→CONDITIONAL). A
2182
+ // FOLLOWUP is a fresh session and is not stopped here: it takes the one extended retry below, as any fresh
2183
+ // dispatch does. Until 2026-11-05 a followup stopped here too, on the false premise that it resumed a loaded
2184
+ // session. See warmHardWallStop.
2185
+ if (warmHardWallStop({ fail, warm, signals: turn.signals })) {
2186
+ note(`[${name}] warm attempt hit the hard wall — breaking (recording the deferral)`);
2185
2187
  break;
2186
2188
  }
2187
2189
  if (timeoutRetriesUsed >= 1) {
@@ -0,0 +1,103 @@
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
+ // how-it-runs.mjs — how the process refusing an order runs, as the remedy it names needs it.
4
+ //
5
+ // An install that cannot search refuses an order, and three places tell the person who runs it what to do: the
6
+ // portal, the run's refusal in the operator's log, and `clearotron start`. What to do depends on the
7
+ // configuration the refusing process actually uses and on how it is reloaded (the owner's words, composed in
8
+ // driver/run-requirements.mjs, `remedyFor`). This reads that, once, for the portal and the runner alike:
9
+ //
10
+ // launcher a user unit among the product's units, which are byte for byte what `clearotron start
11
+ // --background` writes, with no server unit it does not manage beside them. They read
12
+ // `unitEnvPath()`, and that command adds a line the file lacks and never replaces one.
13
+ // units a user unit among the product's units, otherwise. Their `EnvironmentFile=` lines name one file.
14
+ // service run by systemd, and not one of the above: a system unit, another unit, or units that name no one
15
+ // file. Nothing here can name its configuration or its restart.
16
+ // start a child of a foreground `clearotron start`, which hands it the file it read as a flag.
17
+ // hand started some other way: it reads its own settings file, or none.
18
+ //
19
+ // READS ONLY: files, the process's own cgroup and its own environment. No `systemctl`, no process. Every input is
20
+ // a parameter, so a test drives each state over a machine of its own and never this machine's units.
21
+ import { existsSync, readFileSync } from "node:fs";
22
+ import { join, dirname } from "node:path";
23
+ import { homedir } from "node:os";
24
+ import { fileURLToPath } from "node:url";
25
+ import { SERVER_INSTALL_SET, SERVER_UNITS, aBackgroundStartRefreshes } from "../shared/server-units.mjs";
26
+ import { mergeEnvFile } from "../shared/env-file-merge.mjs";
27
+ import { unitEnvPath, activeEnvPath, envFileRead } from "../shared/env-local.mjs";
28
+ import { environmentFilesOf } from "./unit-environment.mjs";
29
+ import { startEnvFileOf } from "./run-requirements.mjs";
30
+
31
+ const INSTALL_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
32
+ const readText = (path) => readFileSync(path, "utf8");
33
+ const readOrNull = (read, path) => { try { return read(path); } catch { return null; } };
34
+ const readCgroup = () => readOrNull(readText, "/proc/self/cgroup");
35
+
36
+ /**
37
+ * This process's own systemd unit and the manager that runs it, from the text of `/proc/self/cgroup`, or null.
38
+ * cgroup v2 writes one line, `0::<path>`; v1 writes one per controller, and systemd's is `N:name=systemd:<path>`.
39
+ * A path through `user@<uid>.service` is the user's manager, and one under `/system.slice/` is the system's.
40
+ * Null when no line names a service unit under either. PURE.
41
+ */
42
+ export function ownUnit(cgroupText) {
43
+ for (const line of String(cgroupText ?? "").split("\n")) {
44
+ const m = /^\d+:(?:name=systemd)?:(\/\S*)$/.exec(line.trim());
45
+ if (!m) continue;
46
+ const unit = /\/([^/]+\.service)$/.exec(m[1])?.[1];
47
+ if (!unit) continue;
48
+ if (/\/user@\d+\.service\//.test(m[1])) return { manager: "user", unit };
49
+ if (m[1].startsWith("/system.slice/")) return { manager: "system", unit };
50
+ }
51
+ return null;
52
+ }
53
+
54
+ /** A unit's declared systemd Type, lowercased; `simple` when the text says none. */
55
+ const unitType = (text) => (String(text ?? "").match(/^Type=(\w+)/m)?.[1] ?? "simple").toLowerCase();
56
+
57
+ /**
58
+ * How this process runs. `missing` is the order-time rows the install lacks (run-requirements.mjs). Returns one
59
+ * of the states in this file's header:
60
+ * { kind: "launcher", file, units, noLineYet, launcherFile } `noLineYet`: no missing setting has a line in
61
+ * `file`, by the merge's own rule, under which a `NAME=` line counts as present even when empty.
62
+ * `launcherFile` is the install's settings file a background start adds from, or null when there is none
63
+ * separate from `file`: then that start adds from the environment it runs in.
64
+ * { kind: "units", file, units }
65
+ * { kind: "service" }
66
+ * { kind: "start" }
67
+ * { kind: "hand", file } `file` is the settings file this process reads, or null when it reads none.
68
+ * `units` is the installed product units that run continuously, the ones to restart.
69
+ */
70
+ export function howItRuns({ missing = [], env = process.env, argv = process.argv, home = homedir(), repoRoot = INSTALL_ROOT,
71
+ cgroup = readCgroup, readFile = envFileRead, exists = existsSync, read = readText,
72
+ template = (u) => readOrNull(readText, join(repoRoot, "driver", "systemd", u)) } = {}) {
73
+ if (String(env?.INVOCATION_ID ?? "").trim()) {
74
+ const own = ownUnit(cgroup());
75
+ const unitDir = join(home, ".config", "systemd", "user");
76
+ const installed = [...new Set([...SERVER_INSTALL_SET, ...SERVER_UNITS])].filter((u) => exists(join(unitDir, u)));
77
+ if (own?.manager !== "user" || !installed.includes(own.unit)) return { kind: "service" };
78
+ const texts = Object.fromEntries(installed.map((u) => [u, readOrNull(read, join(unitDir, u))]));
79
+ const units = installed.filter((u) => unitType(texts[u]) !== "oneshot");
80
+ const launcher = aBackgroundStartRefreshes(SERVER_UNITS.filter((u) => installed.includes(u)))
81
+ && installed.filter((u) => SERVER_INSTALL_SET.includes(u))
82
+ .every((u) => texts[u] !== null && texts[u] === template(u));
83
+ if (launcher) {
84
+ const file = unitEnvPath({ home });
85
+ let text = "";
86
+ let known = true;
87
+ try { text = read(file); } catch (e) { if (e?.code !== "ENOENT") known = false; }
88
+ const names = missing.flatMap((r) => r.anyOf ?? [r.name]);
89
+ const noLineYet = known && names.every((n) => mergeEnvFile(text, { [n]: "x" }).added.includes(n));
90
+ const settings = activeEnvPath({ repoRoot, home });
91
+ return { kind: "launcher", file, units, noLineYet, launcherFile: settings !== file && exists(settings) ? settings : null };
92
+ }
93
+ const files = new Set();
94
+ for (const u of installed) {
95
+ const named = texts[u] === null ? null : environmentFilesOf(texts[u], home);
96
+ if (!named || named.length !== 1) return { kind: "service" };
97
+ files.add(named[0]);
98
+ }
99
+ return files.size === 1 ? { kind: "units", file: [...files][0], units } : { kind: "service" };
100
+ }
101
+ if (startEnvFileOf(argv)) return { kind: "start" };
102
+ return { kind: "hand", file: readFile() ?? null };
103
+ }
@@ -59,14 +59,14 @@
59
59
  // CHECK membership. Derive identity FROM the marks and the membership guard becomes the decision: a seat
60
60
  // that rates the wrong marks no longer fails a check — it writes to a different chunk file and passes.
61
61
  // That is the guard and the thing it guards collapsing into each other.
62
- import { mkdirSync, writeFileSync, readFileSync } from "node:fs";
62
+ import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
63
63
  import { captureCall, stampVerdict } from "./call-capture.mjs";
64
64
  import { join } from "node:path";
65
65
  import { driverDir } from "../shared/driver-dir.mjs";
66
66
  import { refuseUndeclared as refuseUndeclaredShared, keepIfAbsent, lastAccepted, acceptedEnvelope } from "./preserve-merge.mjs";
67
67
  // THE VALIDATOR'S OWN PREDICATE, imported rather than restated. Two spellings of one closed set is how
68
68
  // the call and the stage come to disagree about what is legal, which is the defect this check closes.
69
- import { normalizeKnockoutQualifier, KNOCKOUT_RATING_QUALIFIERS } from "./verify-knockout.mjs";
69
+ import { normalizeKnockoutQualifier, KNOCKOUT_RATING_QUALIFIERS, heldCitationsOnly, classGroupsDefect, frozenLadder, validators } from "./verify-knockout.mjs";
70
70
  // A FINDING'S KEYS, likewise: the validator's one list, so a key the call records is a key the stage accepts.
71
71
  import { KNOCKOUT_FINDING_KEYS } from "./findings-model.mjs";
72
72
 
@@ -139,7 +139,7 @@ const DECLARED = Object.freeze({
139
139
  batch: ["productContext", "standardCaveats"],
140
140
  marks: [
141
141
  "ref", "name", "classesSearched", "beltAndBraces", "contextFraming", "rating", "ratingQualifier",
142
- "classesDriving", "bullets", "purpleNotes", "registerEstimate", "parodyNote", "crowdedField",
142
+ "classesDriving", "classGroups", "bullets", "purpleNotes", "registerEstimate", "parodyNote", "crowdedField",
143
143
  "findings", "negatives", "degraded",
144
144
  // the typed read — required by the validator, absent from the doctrine's own shape block
145
145
  "basis", "factors", "counterFactors", "mitigation", "assessment",
@@ -168,6 +168,7 @@ const DECLARED = Object.freeze({
168
168
  // and records the framework's inputs, as a finding does (verify-knockout.mjs checkRegisterReadInputs).
169
169
  "marks.registerReads": ["recordId", "read", "band", "inputs"],
170
170
  "marks.setAside": ["url", "ground"],
171
+ "marks.classGroups": ["band", "ratingQualifier", "classes"],
171
172
  "marks.negatives": ["term", "source", "note"],
172
173
  });
173
174
 
@@ -369,6 +370,20 @@ export function recordKnockoutAssess(runDir, received, { boundOrdinal = null, no
369
370
  const verdict = acceptKnockoutAssess(call, { boundOrdinal });
370
371
  if (!verdict.ok)
371
372
  return { written: null, refused: verdict.reason, captured: closeCapture({ ok: false, refused: verdict.reason }), capture_failed: captureFailed };
373
+ // Answered in the turn, not after it: the ladder is the run's, so this check cannot sit in the pure verdict above.
374
+ const groupsDefect = verdict.model.marks.map((m) => classGroupsDefect(m, frozenLadder(dir))).find(Boolean);
375
+ if (groupsDefect)
376
+ return { written: null, refused: groupsDefect, captured: closeCapture({ ok: false, refused: groupsDefect }), capture_failed: captureFailed };
377
+ // The check that reads the run's citations. What it refuses is left out and named, and the rest of the call is kept, so the model
378
+ // hears it in the turn and has no chunk to send again (verify-knockout.mjs). The stored call is cleaned too, so a later
379
+ // call that merges onto it does not bring a refused row back.
380
+ const kept = verdict.model.marks.map((m) => heldCitationsOnly(dir, m));
381
+ const notKept = kept.flatMap((k) => k.notKept);
382
+ const defects = kept.flatMap((k) => k.sourceDefects);
383
+ if (notKept.length) {
384
+ verdict.model.marks = kept.map((k) => k.mark);
385
+ call.marks = (Array.isArray(call.marks) ? call.marks : []).map((m) => heldCitationsOnly(dir, m).mark);
386
+ }
372
387
 
373
388
  const at = knockoutAssessChunkFile(dir, chunkNo);
374
389
  try {
@@ -377,21 +392,56 @@ export function recordKnockoutAssess(runDir, received, { boundOrdinal = null, no
377
392
  // The shared envelope, so every transport writes the same shape. The chunk is not restated in it —
378
393
  // it is the directory this file sits in.
379
394
  writeFileSync(paths.accepted, acceptedEnvelope(call, now()));
395
+ writeSourceDefects(dir, chunkNo, verdict.model, defects);
380
396
  } catch (e) {
381
397
  return { written: null, refused: null, write_failed: String(e?.message ?? e).slice(0, 200),
382
398
  captured: closeCapture({ ok: false, write_failed: true }), capture_failed: captureFailed };
383
399
  }
384
400
 
401
+ // THE STAGE'S OWN CHECK, HEARD WHILE THE MODEL CAN STILL ANSWER IT. A call can pass here and be refused when the turn ends, and that
402
+ // costs the whole attempt: measured 2026-11-05 at 62k generated tokens, on findings left with no citation after their sources went.
403
+ let stillRefused = null;
404
+ try { const stage = validators.knockoutAssessChunk(at, JSON.stringify(verdict.model)); if (!stage.ok) stillRefused = stage.reason; } catch { stillRefused = null; }
405
+
385
406
  return {
386
407
  written: at,
387
408
  refused: null,
388
409
  chunk: chunkNo,
389
410
  marks: verdict.model.marks.length,
390
- captured: closeCapture({ ok: true }),
411
+ ...(stillRefused ? { still_refused: stillRefused } : {}),
412
+ ...(notKept.length ? { not_kept: notKept } : {}),
413
+ captured: closeCapture({ ok: true, ...(notKept.length ? { not_kept: notKept } : {}) }),
391
414
  capture_failed: captureFailed,
392
415
  };
393
416
  }
394
417
 
418
+ const sourceDefectsPath = (runDir, chunkNo) => join(knockoutAssessCallPaths(String(runDir ?? ""), chunkNo).dir, "source-defects.json");
419
+
420
+ /**
421
+ * The findings of this chunk whose source was left out. A row is `answered` once the finding comes back with its claim amended or new
422
+ * held support, or goes, for the check to read against the problem. An unchanged resend answers nothing, and an open row goes to the
423
+ * correction. A row never leaves on its own account: the claim may survive a finding dropped or renamed, and only an accepted read settles it.
424
+ */
425
+ export function knockoutAssessSourceDefects(runDir, chunkNo) {
426
+ try { return JSON.parse(readFileSync(sourceDefectsPath(runDir, chunkNo), "utf8")); } catch { return []; }
427
+ }
428
+
429
+ // CODE DOES NOT JUDGE THE CLAIM. It reads whether the finding changed, and leaves whether that answers the problem to the check.
430
+ function writeSourceDefects(runDir, chunkNo, chunk, defects) {
431
+ const key = (d) => JSON.stringify([nameKey(d?.mark), nameKey(d?.name), nameKey(d?.owner)]);
432
+ const current = new Map((chunk?.marks ?? []).flatMap((m) => (m?.findings ?? []).map((f) => [key({ mark: m?.name, name: f?.name, owner: f?.owner }), f])));
433
+ const stored = knockoutAssessSourceDefects(runDir, chunkNo).flatMap((d) => {
434
+ const f = current.get(key(d));
435
+ if (!f) return [{ ...d, state: "answered", removed: true }];
436
+ const amended = f.net !== d.was?.net || f.basis !== d.was?.basis || (f.evidence ?? []).some((u) => !(d.was?.evidence ?? []).includes(u)) || (f.weighedFilings ?? []).some((id) => !(d.was?.weighed ?? []).includes(id));
437
+ return [{ ...d, state: amended ? "answered" : "open" }];
438
+ });
439
+ // A source cited again and left out again is this call's row, whatever became of the claim.
440
+ const again = new Set(defects.map((d) => JSON.stringify([key(d), d.cited])));
441
+ const open = [...stored.filter((d) => !again.has(JSON.stringify([key(d), d.cited]))), ...defects.map((d) => ({ ...d, state: "open" }))];
442
+ if (open.length || existsSync(sourceDefectsPath(runDir, chunkNo))) writeFileSync(sourceDefectsPath(runDir, chunkNo), JSON.stringify(open, null, 2) + "\n");
443
+ }
444
+
395
445
  /** Was this chunk written through the typed transport? The ruled discriminator. */
396
446
  export function knockoutAssessWasRecorded(runDir, chunkNo) {
397
447
  try { readFileSync(knockoutAssessCallPaths(String(runDir ?? ""), chunkNo).payload, "utf8"); return true; }