harness-reflex 0.0.0-stage → 0.3.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 (164) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +266 -2
  3. package/USER_GUIDE.md +639 -0
  4. package/dist/adapters/agy.d.ts +8 -0
  5. package/dist/adapters/agy.js +80 -0
  6. package/dist/adapters/agy.js.map +1 -0
  7. package/dist/adapters/claude.d.ts +13 -0
  8. package/dist/adapters/claude.js +46 -0
  9. package/dist/adapters/claude.js.map +1 -0
  10. package/dist/adapters/codex.d.ts +139 -0
  11. package/dist/adapters/codex.js +368 -0
  12. package/dist/adapters/codex.js.map +1 -0
  13. package/dist/backend/defaults.d.ts +31 -0
  14. package/dist/backend/defaults.js +32 -0
  15. package/dist/backend/defaults.js.map +1 -0
  16. package/dist/backend/factory.d.ts +11 -0
  17. package/dist/backend/factory.js +40 -0
  18. package/dist/backend/factory.js.map +1 -0
  19. package/dist/backend/jev.d.ts +524 -0
  20. package/dist/backend/jev.js +1486 -0
  21. package/dist/backend/jev.js.map +1 -0
  22. package/dist/backend/mock.d.ts +26 -0
  23. package/dist/backend/mock.js +320 -0
  24. package/dist/backend/mock.js.map +1 -0
  25. package/dist/backend/route-prompt.d.ts +37 -0
  26. package/dist/backend/route-prompt.js +42 -0
  27. package/dist/backend/route-prompt.js.map +1 -0
  28. package/dist/backend/simple-jev.d.ts +35 -0
  29. package/dist/backend/simple-jev.js +273 -0
  30. package/dist/backend/simple-jev.js.map +1 -0
  31. package/dist/backend/types.d.ts +270 -0
  32. package/dist/backend/types.js +5 -0
  33. package/dist/backend/types.js.map +1 -0
  34. package/dist/cli/index.d.ts +2 -0
  35. package/dist/cli/index.js +278 -0
  36. package/dist/cli/index.js.map +1 -0
  37. package/dist/core/calibrate.d.ts +56 -0
  38. package/dist/core/calibrate.js +144 -0
  39. package/dist/core/calibrate.js.map +1 -0
  40. package/dist/core/closing.d.ts +90 -0
  41. package/dist/core/closing.js +111 -0
  42. package/dist/core/closing.js.map +1 -0
  43. package/dist/core/evidence.d.ts +119 -0
  44. package/dist/core/evidence.js +209 -0
  45. package/dist/core/evidence.js.map +1 -0
  46. package/dist/core/gate.d.ts +25 -0
  47. package/dist/core/gate.js +114 -0
  48. package/dist/core/gate.js.map +1 -0
  49. package/dist/core/judge.d.ts +221 -0
  50. package/dist/core/judge.js +251 -0
  51. package/dist/core/judge.js.map +1 -0
  52. package/dist/core/ledger.d.ts +67 -0
  53. package/dist/core/ledger.js +173 -0
  54. package/dist/core/ledger.js.map +1 -0
  55. package/dist/core/orchestrate-closing.d.ts +237 -0
  56. package/dist/core/orchestrate-closing.js +250 -0
  57. package/dist/core/orchestrate-closing.js.map +1 -0
  58. package/dist/core/orchestrate-correction.d.ts +209 -0
  59. package/dist/core/orchestrate-correction.js +141 -0
  60. package/dist/core/orchestrate-correction.js.map +1 -0
  61. package/dist/core/orchestrate-host.d.ts +225 -0
  62. package/dist/core/orchestrate-host.js +80 -0
  63. package/dist/core/orchestrate-host.js.map +1 -0
  64. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  65. package/dist/core/orchestrate-stagnation.js +270 -0
  66. package/dist/core/orchestrate-stagnation.js.map +1 -0
  67. package/dist/core/orchestrate.d.ts +357 -0
  68. package/dist/core/orchestrate.js +418 -0
  69. package/dist/core/orchestrate.js.map +1 -0
  70. package/dist/core/policy.d.ts +122 -0
  71. package/dist/core/policy.js +102 -0
  72. package/dist/core/policy.js.map +1 -0
  73. package/dist/core/prune-plan.d.ts +141 -0
  74. package/dist/core/prune-plan.js +390 -0
  75. package/dist/core/prune-plan.js.map +1 -0
  76. package/dist/core/prune.d.ts +30 -0
  77. package/dist/core/prune.js +73 -0
  78. package/dist/core/prune.js.map +1 -0
  79. package/dist/core/route.d.ts +35 -0
  80. package/dist/core/route.js +39 -0
  81. package/dist/core/route.js.map +1 -0
  82. package/dist/core/score.d.ts +40 -0
  83. package/dist/core/score.js +49 -0
  84. package/dist/core/score.js.map +1 -0
  85. package/dist/core/screen.d.ts +22 -0
  86. package/dist/core/screen.js +117 -0
  87. package/dist/core/screen.js.map +1 -0
  88. package/dist/core/stagnation.d.ts +23 -0
  89. package/dist/core/stagnation.js +93 -0
  90. package/dist/core/stagnation.js.map +1 -0
  91. package/dist/core/text.d.ts +36 -0
  92. package/dist/core/text.js +66 -0
  93. package/dist/core/text.js.map +1 -0
  94. package/dist/hook/cli.d.ts +9 -0
  95. package/dist/hook/cli.js +52 -0
  96. package/dist/hook/cli.js.map +1 -0
  97. package/dist/hook/contract.d.ts +125 -0
  98. package/dist/hook/contract.js +159 -0
  99. package/dist/hook/contract.js.map +1 -0
  100. package/dist/hook/decision.d.ts +97 -0
  101. package/dist/hook/decision.js +955 -0
  102. package/dist/hook/decision.js.map +1 -0
  103. package/dist/hook/memory-store.d.ts +81 -0
  104. package/dist/hook/memory-store.js +157 -0
  105. package/dist/hook/memory-store.js.map +1 -0
  106. package/dist/hook/payload.d.ts +55 -0
  107. package/dist/hook/payload.js +129 -0
  108. package/dist/hook/payload.js.map +1 -0
  109. package/dist/hook/run.d.ts +48 -0
  110. package/dist/hook/run.js +218 -0
  111. package/dist/hook/run.js.map +1 -0
  112. package/dist/hook/store-port.d.ts +72 -0
  113. package/dist/hook/store-port.js +2 -0
  114. package/dist/hook/store-port.js.map +1 -0
  115. package/dist/index.d.ts +18 -0
  116. package/dist/index.js +19 -0
  117. package/dist/index.js.map +1 -0
  118. package/dist/mcp/server.d.ts +12 -0
  119. package/dist/mcp/server.js +368 -0
  120. package/dist/mcp/server.js.map +1 -0
  121. package/dist/ports/audit.d.ts +18 -0
  122. package/dist/ports/audit.js +11 -0
  123. package/dist/ports/audit.js.map +1 -0
  124. package/dist/ports/clock.d.ts +14 -0
  125. package/dist/ports/clock.js +11 -0
  126. package/dist/ports/clock.js.map +1 -0
  127. package/dist/ports/decision.d.ts +75 -0
  128. package/dist/ports/decision.js +2 -0
  129. package/dist/ports/decision.js.map +1 -0
  130. package/dist/ports/index.d.ts +14 -0
  131. package/dist/ports/index.js +2 -0
  132. package/dist/ports/index.js.map +1 -0
  133. package/dist/ports/log.d.ts +22 -0
  134. package/dist/ports/log.js +12 -0
  135. package/dist/ports/log.js.map +1 -0
  136. package/dist/ports/state.d.ts +46 -0
  137. package/dist/ports/state.js +13 -0
  138. package/dist/ports/state.js.map +1 -0
  139. package/dist/state/clock.d.ts +40 -0
  140. package/dist/state/clock.js +43 -0
  141. package/dist/state/clock.js.map +1 -0
  142. package/dist/state/file-store.d.ts +340 -0
  143. package/dist/state/file-store.js +849 -0
  144. package/dist/state/file-store.js.map +1 -0
  145. package/dist/state/paths.d.ts +41 -0
  146. package/dist/state/paths.js +73 -0
  147. package/dist/state/paths.js.map +1 -0
  148. package/docs/USER_GUIDE.en.md +721 -0
  149. package/docs/claude-code.md +281 -0
  150. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  151. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  152. package/docs/dsh-plugin.md +578 -0
  153. package/docs/reflex-ui-regression-2026-10-20.md +34 -0
  154. package/docs/release-checklist-v0.1.0.md +315 -0
  155. package/docs/release-handbook-porting-notes.md +106 -0
  156. package/docs/release-handbook.md +393 -0
  157. package/docs/release-notes-v0.1.0.md +63 -0
  158. package/docs/release-notes-v0.3.0.md +152 -0
  159. package/docs/research/claude-code-harness.md +607 -0
  160. package/docs/research/pi-harness.md +621 -0
  161. package/experiments/data/calibration_sample.json +14 -0
  162. package/experiments/index.ts +29 -0
  163. package/experiments/runner.ts +156 -0
  164. package/package.json +82 -4
@@ -0,0 +1,173 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ export class DecisionLedger {
4
+ static instance;
5
+ entries = [];
6
+ /** Append-only JSONL sink; `null` keeps the ledger purely in process memory. */
7
+ logPath;
8
+ /**
9
+ * @param customPath - JSONL file to append to and replay from startup.
10
+ * Omit for the default `<cwd>/.reflex/ledger.jsonl`; pass `null` for an
11
+ * in-memory-only ledger that never touches the filesystem (embedded Hosts).
12
+ */
13
+ constructor(customPath) {
14
+ const dir = path.join(process.cwd(), '.reflex');
15
+ this.logPath = customPath === null ? null : customPath || path.join(dir, 'ledger.jsonl');
16
+ if (this.logPath)
17
+ this.loadFromDisk();
18
+ }
19
+ /** The JSONL sink this ledger appends to, or `null` when memory-only. */
20
+ getLogPath() {
21
+ return this.logPath;
22
+ }
23
+ /**
24
+ * Move the JSONL sink to another file without losing the entries already seen.
25
+ *
26
+ * A config-only save can change `ledgerPath` while the activation keeps
27
+ * running. The migration strategy is merge-and-rewrite: entries already in the
28
+ * new file are merged into memory first (by id, so replaying the file cannot
29
+ * duplicate them), then every in-memory entry is written to the new file. The
30
+ * new sink therefore starts with the complete in-process history — including
31
+ * entries recorded before the switch — and the old file is simply no longer
32
+ * written to (there are no held file handles to release; every record opens,
33
+ * appends and closes).
34
+ * @param customPath - new JSONL file, or `null` for in-memory only.
35
+ * @returns whether the sink changed.
36
+ */
37
+ switchLogPath(customPath) {
38
+ const next = customPath === null ? null : customPath || path.join(process.cwd(), '.reflex', 'ledger.jsonl');
39
+ if (next === this.logPath)
40
+ return false;
41
+ if (next) {
42
+ // Merge what the new file already holds, so switching between two
43
+ // populated sinks does not drop either side's history.
44
+ try {
45
+ if (fs.existsSync(next)) {
46
+ const known = new Set(this.entries.map((entry) => entry.id));
47
+ for (const line of fs.readFileSync(next, 'utf8').split('\n')) {
48
+ if (!line.trim())
49
+ continue;
50
+ const entry = JSON.parse(line);
51
+ if (!known.has(entry.id)) {
52
+ this.entries.push(entry);
53
+ known.add(entry.id);
54
+ }
55
+ }
56
+ }
57
+ }
58
+ catch {
59
+ // An unreadable target still becomes the sink; its old content is left alone.
60
+ }
61
+ try {
62
+ const dir = path.dirname(next);
63
+ if (!fs.existsSync(dir))
64
+ fs.mkdirSync(dir, { recursive: true });
65
+ // Rewrite, not append: the new file must contain the full in-memory
66
+ // history exactly once, which the merge above has already deduplicated.
67
+ fs.writeFileSync(next, this.entries.map((entry) => JSON.stringify(entry)).join('\n') + (this.entries.length > 0 ? '\n' : ''), 'utf8');
68
+ }
69
+ catch {
70
+ // non-fatal in restricted or readonly filesystems
71
+ }
72
+ }
73
+ this.logPath = next;
74
+ return true;
75
+ }
76
+ static getInstance() {
77
+ if (!DecisionLedger.instance) {
78
+ DecisionLedger.instance = new DecisionLedger();
79
+ }
80
+ return DecisionLedger.instance;
81
+ }
82
+ loadFromDisk() {
83
+ if (!this.logPath)
84
+ return;
85
+ try {
86
+ if (fs.existsSync(this.logPath)) {
87
+ const lines = fs.readFileSync(this.logPath, 'utf8').split('\n');
88
+ for (const line of lines) {
89
+ if (line.trim()) {
90
+ this.entries.push(JSON.parse(line));
91
+ }
92
+ }
93
+ }
94
+ }
95
+ catch {
96
+ // ignore read errors
97
+ }
98
+ }
99
+ record(entry) {
100
+ const fullEntry = {
101
+ id: `ref_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
102
+ timestamp: new Date().toISOString(),
103
+ ...entry
104
+ };
105
+ this.entries.push(fullEntry);
106
+ if (this.logPath) {
107
+ try {
108
+ const dir = path.dirname(this.logPath);
109
+ if (!fs.existsSync(dir)) {
110
+ fs.mkdirSync(dir, { recursive: true });
111
+ }
112
+ fs.appendFileSync(this.logPath, JSON.stringify(fullEntry) + '\n', 'utf8');
113
+ }
114
+ catch {
115
+ // non-fatal in restricted or readonly filesystems
116
+ }
117
+ }
118
+ return fullEntry;
119
+ }
120
+ getEntries() {
121
+ return [...this.entries];
122
+ }
123
+ getSummary() {
124
+ let totalTokensSaved = 0;
125
+ let totalLatency = 0;
126
+ let stagnationAlerts = 0;
127
+ let gatePassedCount = 0;
128
+ let gateFailedCount = 0;
129
+ const callsByType = {};
130
+ for (const e of this.entries) {
131
+ callsByType[e.type] = (callsByType[e.type] || 0) + 1;
132
+ totalTokensSaved += e.tokensSaved || 0;
133
+ totalLatency += e.latencyMs;
134
+ if (e.type === 'stagnation' && e.isStuck) {
135
+ stagnationAlerts++;
136
+ }
137
+ if (e.type === 'gate') {
138
+ if (e.passed)
139
+ gatePassedCount++;
140
+ else
141
+ gateFailedCount++;
142
+ }
143
+ }
144
+ const totalCalls = this.entries.length;
145
+ const avgLatencyMs = totalCalls > 0 ? Math.round(totalLatency / totalCalls) : 0;
146
+ // Assume average input cost $3.00 per million tokens ($0.000003 per token)
147
+ const estimatedCostSavedUsd = Number(((totalTokensSaved * 3.0) / 1_000_000).toFixed(4));
148
+ return {
149
+ totalCalls,
150
+ callsByType,
151
+ totalTokensSaved,
152
+ avgLatencyMs,
153
+ estimatedCostSavedUsd,
154
+ stagnationAlerts,
155
+ gatePassedCount,
156
+ gateFailedCount
157
+ };
158
+ }
159
+ clear() {
160
+ this.entries = [];
161
+ if (!this.logPath)
162
+ return;
163
+ try {
164
+ if (fs.existsSync(this.logPath)) {
165
+ fs.unlinkSync(this.logPath);
166
+ }
167
+ }
168
+ catch {
169
+ // ignore
170
+ }
171
+ }
172
+ }
173
+ //# sourceMappingURL=ledger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger.js","sourceRoot":"","sources":["../../src/core/ledger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAoC7B,MAAM,OAAO,cAAc;IACjB,MAAM,CAAC,QAAQ,CAAiB;IAChC,OAAO,GAAkB,EAAE,CAAC;IACpC,gFAAgF;IACxE,OAAO,CAAgB;IAE/B;;;;OAIG;IACH,YAAY,UAA0B;QACpC,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,SAAS,CAAC,CAAC;QAChD,IAAI,CAAC,OAAO,GAAG,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QACzF,IAAI,IAAI,CAAC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e;YACf,eAAe;SAChB,CAAC;IACJ,CAAC;IAED,KAAK;QACH,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAC1B,IAAI,CAAC;YACH,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;gBAChC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;QAAC,MAAM,CAAC;YACP,SAAS;QACX,CAAC;IACH,CAAC;CACF","sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\n\nexport interface LedgerEntry {\n id: string;\n timestamp: string;\n /**\n * `route` ranks generic candidates (tools, skills); `model-route` is the\n * dedicated audit record of one virtual→physical model routing decision\n * (candidate pool, chosen target, latency, reason); `effort-decision` is one\n * per-turn adaptive reasoning-effort decision (decided level, effort actually\n * dispatched, projection outcome, evidence).\n */\n type: 'gate' | 'prune' | 'stagnation' | 'route' | 'choice' | 'model-route' | 'effort-decision';\n backend: string;\n latencyMs: number;\n tokensSaved?: number;\n originalTokens?: number;\n prunedTokens?: number;\n passed?: boolean;\n isStuck?: boolean;\n skipReason?: string;\n shadow?: boolean;\n details?: Record<string, any>;\n}\n\nexport interface LedgerSummary {\n totalCalls: number;\n callsByType: Record<string, number>;\n totalTokensSaved: number;\n avgLatencyMs: number;\n estimatedCostSavedUsd: number;\n stagnationAlerts: number;\n gatePassedCount: number;\n gateFailedCount: number;\n}\n\nexport class DecisionLedger {\n private static instance: DecisionLedger;\n private entries: LedgerEntry[] = [];\n /** Append-only JSONL sink; `null` keeps the ledger purely in process memory. */\n private logPath: string | null;\n\n /**\n * @param customPath - JSONL file to append to and replay from startup.\n * Omit for the default `<cwd>/.reflex/ledger.jsonl`; pass `null` for an\n * in-memory-only ledger that never touches the filesystem (embedded Hosts).\n */\n constructor(customPath?: string | null) {\n const dir = path.join(process.cwd(), '.reflex');\n this.logPath = customPath === null ? null : customPath || path.join(dir, 'ledger.jsonl');\n if (this.logPath) this.loadFromDisk();\n }\n\n /** The JSONL sink this ledger appends to, or `null` when memory-only. */\n getLogPath(): string | null {\n return this.logPath;\n }\n\n /**\n * Move the JSONL sink to another file without losing the entries already seen.\n *\n * A config-only save can change `ledgerPath` while the activation keeps\n * running. The migration strategy is merge-and-rewrite: entries already in the\n * new file are merged into memory first (by id, so replaying the file cannot\n * duplicate them), then every in-memory entry is written to the new file. The\n * new sink therefore starts with the complete in-process history — including\n * entries recorded before the switch — and the old file is simply no longer\n * written to (there are no held file handles to release; every record opens,\n * appends and closes).\n * @param customPath - new JSONL file, or `null` for in-memory only.\n * @returns whether the sink changed.\n */\n switchLogPath(customPath?: string | null): boolean {\n const next = customPath === null ? null : customPath || path.join(process.cwd(), '.reflex', 'ledger.jsonl');\n if (next === this.logPath) return false;\n if (next) {\n // Merge what the new file already holds, so switching between two\n // populated sinks does not drop either side's history.\n try {\n if (fs.existsSync(next)) {\n const known = new Set(this.entries.map((entry) => entry.id));\n for (const line of fs.readFileSync(next, 'utf8').split('\\n')) {\n if (!line.trim()) continue;\n const entry = JSON.parse(line) as LedgerEntry;\n if (!known.has(entry.id)) {\n this.entries.push(entry);\n known.add(entry.id);\n }\n }\n }\n } catch {\n // An unreadable target still becomes the sink; its old content is left alone.\n }\n try {\n const dir = path.dirname(next);\n if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n // Rewrite, not append: the new file must contain the full in-memory\n // history exactly once, which the merge above has already deduplicated.\n fs.writeFileSync(next, this.entries.map((entry) => JSON.stringify(entry)).join('\\n') + (this.entries.length > 0 ? '\\n' : ''), 'utf8');\n } catch {\n // non-fatal in restricted or readonly filesystems\n }\n }\n this.logPath = next;\n return true;\n }\n\n static getInstance(): DecisionLedger {\n if (!DecisionLedger.instance) {\n DecisionLedger.instance = new DecisionLedger();\n }\n return DecisionLedger.instance;\n }\n\n private loadFromDisk(): void {\n if (!this.logPath) return;\n try {\n if (fs.existsSync(this.logPath)) {\n const lines = fs.readFileSync(this.logPath, 'utf8').split('\\n');\n for (const line of lines) {\n if (line.trim()) {\n this.entries.push(JSON.parse(line));\n }\n }\n }\n } catch {\n // ignore read errors\n }\n }\n\n record(entry: Omit<LedgerEntry, 'id' | 'timestamp'>): LedgerEntry {\n const fullEntry: LedgerEntry = {\n id: `ref_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,\n timestamp: new Date().toISOString(),\n ...entry\n };\n\n this.entries.push(fullEntry);\n\n if (this.logPath) {\n try {\n const dir = path.dirname(this.logPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.appendFileSync(this.logPath, JSON.stringify(fullEntry) + '\\n', 'utf8');\n } catch {\n // non-fatal in restricted or readonly filesystems\n }\n }\n\n return fullEntry;\n }\n\n getEntries(): LedgerEntry[] {\n return [...this.entries];\n }\n\n getSummary(): LedgerSummary {\n let totalTokensSaved = 0;\n let totalLatency = 0;\n let stagnationAlerts = 0;\n let gatePassedCount = 0;\n let gateFailedCount = 0;\n const callsByType: Record<string, number> = {};\n\n for (const e of this.entries) {\n callsByType[e.type] = (callsByType[e.type] || 0) + 1;\n totalTokensSaved += e.tokensSaved || 0;\n totalLatency += e.latencyMs;\n if (e.type === 'stagnation' && e.isStuck) {\n stagnationAlerts++;\n }\n if (e.type === 'gate') {\n if (e.passed) gatePassedCount++;\n else gateFailedCount++;\n }\n }\n\n const totalCalls = this.entries.length;\n const avgLatencyMs = totalCalls > 0 ? Math.round(totalLatency / totalCalls) : 0;\n // Assume average input cost $3.00 per million tokens ($0.000003 per token)\n const estimatedCostSavedUsd = Number(((totalTokensSaved * 3.0) / 1_000_000).toFixed(4));\n\n return {\n totalCalls,\n callsByType,\n totalTokensSaved,\n avgLatencyMs,\n estimatedCostSavedUsd,\n stagnationAlerts,\n gatePassedCount,\n gateFailedCount\n };\n }\n\n clear(): void {\n this.entries = [];\n if (!this.logPath) return;\n try {\n if (fs.existsSync(this.logPath)) {\n fs.unlinkSync(this.logPath);\n }\n } catch {\n // ignore\n }\n }\n}\n"]}
@@ -0,0 +1,237 @@
1
+ /**
2
+ * The shared orchestration of the closing check.
3
+ *
4
+ * The fourth and last lift: {@link ./orchestrate} owns when a result is reduced,
5
+ * {@link ./orchestrate-stagnation} owns when a call is refused and when a step is
6
+ * corrected, {@link ./orchestrate-correction} owns what happens to a result that
7
+ * failed — and this one owns what happens when a turn is about to *close* while
8
+ * its own words claim success the evidence does not support.
9
+ *
10
+ * ```
11
+ * agent/turn-stopping
12
+ * → off, or the host is not serving this capability → nothing at all
13
+ * → the turn said nothing, or no evidence is a failure → not suspicious, nothing at all
14
+ * → no candidate sentence → nothing at all
15
+ * → already latched for this turn → duplicate-intervention
16
+ * → the turn's action allowance is spent → intervention-cap
17
+ * → the caller's signal is aborted → nothing at all
18
+ * → assemble the evidence; truncation is NOTED and the decision continues
19
+ * → buy the classification (turn/session budgets inside)
20
+ * → the classifier could not answer → closing-claim-unavailable (fail open, locally)
21
+ * → nothing really claims completion → closing-no-claim (and the charge is kept)
22
+ * → buy the verification (same judgment, second request)
23
+ * → nothing contradicted → closing-undecided / closing-unconfirmed / closing-evidence-consistent
24
+ * → latch the turn, book the action, conclude
25
+ * → [the host steers the objection into the turn, in active mode only]
26
+ * → a failure anywhere after that → planning-error (fail open)
27
+ * ```
28
+ *
29
+ * ## What is shared and what is not
30
+ *
31
+ * Shared here: the order above, every skip reason, the budget rules, the two
32
+ * per-turn latches, the shape of the audit detail, and the decision that active
33
+ * mode asks its host to steer.
34
+ *
35
+ * *Not* shared here: the act of steering (that is `HostClosingPort#steer`), the
36
+ * wording the model reads (`#describe`), the storage of the evidence counters
37
+ * (`#noteEvidence`), and the accumulation of the turn's own words — a host that
38
+ * reads them from a stream and a host that reads them from a transcript both hand
39
+ * over the same string.
40
+ *
41
+ * ## The two judgments are one decision
42
+ *
43
+ * The closing check buys **two** requests from one capability: a classification
44
+ * of the turn's candidate sentences, and a verification of the claims that
45
+ * classification accepted. They are one logical judgment — the classification
46
+ * decides *whether* anything is worth verifying — so both are charged against the
47
+ * single slot the turn budget allowed, and both are billed as one
48
+ * {@link ClosingJudgment}. That fold is why this port states its two *purchases*
49
+ * ({@link HostClosingPort#classify} and {@link HostClosingPort#verify}) and never
50
+ * the transport behind them: a caller holding the service would have to
51
+ * re-implement the purchase, the memo, the latency split and the billing, and the
52
+ * one-charge rule is only stateable where the charge is built. It stays here.
53
+ *
54
+ * ## The skip that does not return
55
+ *
56
+ * Every skip in the other three modules ends the decision. `evidence-truncated`
57
+ * does not: the evidence was assembled with some of it dropped, the amount is
58
+ * reported, and the judgment proceeds on what survived. This module therefore
59
+ * distinguishes a *note* (`#note`, which records) from a *refusal* (`#refuse`,
60
+ * which records and returns). Collapsing the two would either stop the closing
61
+ * check whenever evidence is large, or lose the fact that it was truncated.
62
+ *
63
+ * ## A verdict that could not decide is not a contradiction
64
+ *
65
+ * `escalate` means the backend could not answer — an unavailable service degrades
66
+ * exactly this way. Steering a turn on an undecided verdict would turn a backend
67
+ * failure into a model-visible objection, so only `contradicted` results steer;
68
+ * `escalate` gets its own reason (`closing-undecided`) precisely so a run can tell
69
+ * "the evidence was fine" from "nobody looked".
70
+ *
71
+ * @module core/orchestrate-closing
72
+ */
73
+ import { type EvidenceEntry } from './evidence.js';
74
+ import type { HostBillingPort, HostDecisionPort, JudgmentCost, JudgmentPosition } from './orchestrate-host.js';
75
+ /** The capability every decision in this module belongs to. */
76
+ export declare const CLOSING_CAPABILITY: "closing";
77
+ /** The audit action an objection is recorded under. */
78
+ export declare const CLOSING_ACTION: "steer-closing";
79
+ /**
80
+ * The two latches this decision keeps, both keyed by turn rather than by identity.
81
+ *
82
+ * The other capabilities latch by *signature* — one repeated call is one episode.
83
+ * A closing check has no such identity: the episode is the turn itself, so the
84
+ * key is `closing:turn:<n>` and it is the host's storage that has to keep it.
85
+ */
86
+ export declare const CLOSING_LATCH: {
87
+ /** The turn was already objected to (or observed) — never twice per turn. */
88
+ readonly applied: (turn: number) => string;
89
+ /** The memo namespace of the verification request, so a replay is free. */
90
+ readonly verdictKey: (agent: string, turn: number) => string;
91
+ };
92
+ /** One planned objection, as the host records it. */
93
+ export interface ClosingPlanRecord {
94
+ readonly capability: typeof CLOSING_CAPABILITY;
95
+ readonly action: typeof CLOSING_ACTION;
96
+ readonly reason: string;
97
+ feedback: string;
98
+ readonly detail: Record<string, unknown>;
99
+ }
100
+ /**
101
+ * The judgment one closing check rode on.
102
+ *
103
+ * Both requests are folded into one charge on purpose: the turn budget bought one
104
+ * slot, and a reader of the account must not see two slots spent for one decision.
105
+ * `localLatencyMs` is the wait the two requests cost in this process; the two
106
+ * remote times are summed because the model was asked two questions.
107
+ */
108
+ export interface ClosingJudgment extends JudgmentCost {
109
+ }
110
+ /** What one closing check turned out to be. */
111
+ export type ClosingAction = 'objected' | 'pass-through';
112
+ /** What one orchestrated closing check produced. */
113
+ export interface ClosingOutcome {
114
+ /** What the capability was in force: a decision is only made when this is not `off`. */
115
+ readonly action: ClosingAction;
116
+ /** The reason the check did nothing, when it did nothing. */
117
+ readonly skip?: string;
118
+ /** Every skip reason this one check reported, in order (normally 0 or 1). */
119
+ readonly skips: readonly string[];
120
+ /** The objection, once the decision is to make one. */
121
+ readonly plan?: ClosingPlanRecord;
122
+ /** Whether the objection was really steered (active mode only). */
123
+ readonly applied: boolean;
124
+ /** The message to hand the model, when the host steers in active mode. */
125
+ readonly message?: string;
126
+ }
127
+ /** What the classification half answered. */
128
+ export interface ClaimClassificationLike {
129
+ readonly results: readonly {
130
+ readonly statement: string;
131
+ readonly isClaim: boolean;
132
+ readonly confidence: number;
133
+ }[];
134
+ readonly latencyMs: number;
135
+ }
136
+ /** What the verification half answered. */
137
+ export interface ClosingVerdictLike {
138
+ readonly passed: boolean;
139
+ readonly results: readonly {
140
+ readonly statement: string;
141
+ readonly outcome: string;
142
+ readonly confidence: number;
143
+ }[];
144
+ readonly latencyMs: number;
145
+ }
146
+ /** What the objection is built from, for the host's wording. */
147
+ export interface ClosingFeedbackFacts {
148
+ /** The contradicted statements, already clipped for quoting. */
149
+ readonly contradicted: readonly string[];
150
+ /** The turn that is closing. */
151
+ readonly turn: number;
152
+ }
153
+ /** Everything the shared layer cannot know by itself. */
154
+ export interface HostClosingPort extends HostDecisionPort, HostBillingPort<ClosingJudgment, ClosingPlanRecord> {
155
+ /** The effective mode of the `closing` capability. */
156
+ mode(): 'off' | 'observe' | 'active';
157
+ /**
158
+ * The turn's own words, as the stream carried them.
159
+ *
160
+ * The host accumulates them (`agent/assistant-stream` in DSH); the shared layer
161
+ * only asks for the string. An empty string means the turn said nothing, which
162
+ * is one of the four deterministic reasons nothing is bought.
163
+ */
164
+ claims(): string;
165
+ /**
166
+ * Whether at least one retained evidence entry looks like a failure.
167
+ *
168
+ * A host computes this from its own reading of its results; the shared layer
169
+ * needs only the boolean, because *which* result failed is what the judgment
170
+ * reads, not what the trigger reads.
171
+ */
172
+ evidenceSuspect(): boolean;
173
+ /** The evidence entries retained for this turn. */
174
+ evidence(): readonly EvidenceEntry[];
175
+ /** The evidence-assembly budget in force. */
176
+ evidenceBudget(): number;
177
+ /** Whether the caller's signal is already aborted (a cancelling turn). */
178
+ aborted(): boolean;
179
+ /** Whether this turn was already objected to (or observed) — the per-turn latch. */
180
+ alreadyObjected(): boolean;
181
+ /** Latch this turn as objected to. */
182
+ latchObjected(): void;
183
+ /** The identity the verification memo is namespaced by. */
184
+ agentId(): string;
185
+ /** The classification half of the one judgment. */
186
+ classify(request: {
187
+ readonly statements: readonly string[];
188
+ readonly context: string;
189
+ }): Promise<ClaimClassificationLike>;
190
+ /** The verification half of the same judgment. */
191
+ verify(claims: readonly {
192
+ readonly statement: string;
193
+ }[], evidence: string, options: {
194
+ readonly latchCacheKey: string;
195
+ }): Promise<ClosingVerdictLike>;
196
+ /** The confidence floor a classified sentence must clear to be a claim. */
197
+ claimMinConfidence(): number;
198
+ /** Word the objection the model reads. */
199
+ describe(facts: ClosingFeedbackFacts): string;
200
+ /** Hand the objection to the model. Only called in active mode. */
201
+ steer(message: string): void;
202
+ /** Record the evidence counters, which are engine-level rather than per-agent. */
203
+ noteEvidence(stats: {
204
+ readonly retainedChars: number;
205
+ readonly truncatedChars: number;
206
+ }): void;
207
+ }
208
+ /**
209
+ * Decide whether the turn that is closing contradicts its own evidence, and tell
210
+ * the host what to do about it.
211
+ *
212
+ * The position is an *input of this decision*, not a port accessor and not a
213
+ * counter. The turn here is the boundary being closed, which can be a turn no
214
+ * step has recorded yet — a turn that said something and admitted no step — so it
215
+ * cannot be read off the running counters. `step` is the step the engine last
216
+ * recorded, which is the same number the audit detail has always quoted.
217
+ *
218
+ * @param invocation - where in the run this check is being made.
219
+ * @param port - everything the shared layer cannot know by itself.
220
+ * @returns what the check decided, and the message to steer when it applied.
221
+ */
222
+ export declare function orchestrateClosing(invocation: {
223
+ readonly position: JudgmentPosition;
224
+ }, port: HostClosingPort): Promise<ClosingOutcome>;
225
+ /**
226
+ * The objection's wording, in the default form.
227
+ *
228
+ * Exported because a host that shows the text to the same audience may keep it
229
+ * verbatim; a host that words it differently supplies its own through the port.
230
+ * The statement clipping is the shared part: a contradicted claim is quoted at
231
+ * 160 characters with its whitespace collapsed, so a multi-line claim can never
232
+ * make the objection unbounded.
233
+ * @param facts - what the objection is built from.
234
+ * @param limit - the total character budget.
235
+ * @returns the text handed to the model.
236
+ */
237
+ export declare function describeClosing(facts: ClosingFeedbackFacts, limit: number): string;