dsh-harness-reflex 0.1.0 → 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 (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
@@ -0,0 +1,209 @@
1
+ import { clip } from './text.js';
2
+ /** Characters of one evidence line. */
3
+ export const EVIDENCE_CHARS = 400;
4
+ /** Characters of one result's tail summary. */
5
+ export const EVIDENCE_TAIL_CHARS = 240;
6
+ /** Characters of the "other" (non-diagnostic, non-tail) fallback per result. */
7
+ export const EVIDENCE_OTHER_CHARS = 120;
8
+ /**
9
+ * Matches the failure markers that make a result a *candidate* for the closing
10
+ * evidence. A hit is a safety floor: the line is kept whatever the budget says.
11
+ * A miss is never a "failure-free" conclusion — the tail summary goes to System
12
+ * One, which decides what the result means.
13
+ */
14
+ export const FAILURE_MARKER = /(\berror\b|\berrors\b|\bfailed\b|\bfailure\b|\bfailures\b|\bfail\b|exit code [1-9]|\bnot ok\b|\bFAIL\b|\bexception\b|\btraceback\b)/i;
15
+ /**
16
+ * Prefilter for a failure *suspicion* — the deterministic trigger that makes a
17
+ * closing judgment worth buying. It is broader than {@link FAILURE_MARKER}
18
+ * because `{ok:false}`, a timeout, and a Chinese error must reach System One
19
+ * too; none of these decides anything by itself.
20
+ */
21
+ const FAILURE_CUE = new RegExp(`${FAILURE_MARKER.source}|\\bok\\b\\s*[:=]\\s*false|"ok"\\s*:\\s*false|\\btimed?\\s*out\\b|\\btimeout\\b|`
22
+ + '失败|错误|异常|超时|无法|未通过|仍有失败|还有失败|报错', 'i');
23
+ /**
24
+ * The exit status one tool result carries in its own canonical value.
25
+ *
26
+ * A shell result is *reported*, not errored: a command that exits 1 returns a
27
+ * successful result whose `value.exitCode` is the whole truth. The distinction
28
+ * matters twice over — a correction that never fires because the failure looked
29
+ * like a success, and a closing check that reads a green claim over a red build
30
+ * — so the status is taken from the tool's own structured field whenever the
31
+ * payload exposes one.
32
+ *
33
+ * @param value - the result's canonical value, when it has one.
34
+ * @returns the exit status, or `undefined` when the value is not a shell result.
35
+ */
36
+ export function structuredExitStatus(value) {
37
+ if (typeof value !== 'object' || value === null)
38
+ return undefined;
39
+ const candidate = value;
40
+ if (typeof candidate.exitCode !== 'number' || !Number.isFinite(candidate.exitCode))
41
+ return undefined;
42
+ const status = { exitCode: candidate.exitCode };
43
+ if (typeof candidate.signal === 'string')
44
+ status.signal = candidate.signal;
45
+ return status;
46
+ }
47
+ /**
48
+ * Whether the text ends in the host's own exit marker for a failed command.
49
+ *
50
+ * The marker is the last line of the model-facing content, so anchoring it to the
51
+ * end of the text keeps an *ordinary* result that merely mentions "exit code 1"
52
+ * in its body from being misread as a failure. This is the fallback for a result
53
+ * that carries no structured value — a virtual tool, a replay from an older
54
+ * record — not a replacement for {@link structuredExitStatus}.
55
+ * @param text - the model-facing text.
56
+ * @returns whether the last marker line reports a non-zero exit or a signal.
57
+ */
58
+ export function exitMarkerFailure(text) {
59
+ const match = /(?:^|\n)\[exit code: ([0-9]+)\]\s*$/.exec(text);
60
+ if (match)
61
+ return Number(match[1]) !== 0;
62
+ return /(?:^|\n)\[killed by signal: [^\]\n]+\]\s*$/.test(text);
63
+ }
64
+ /**
65
+ * Whether one result is a failure the interventions may act on.
66
+ *
67
+ * Three sources, in order of authority: the host's own `isError` flag, the exit
68
+ * status inside the tool's structured value, and the exit marker the host appends
69
+ * to the text. A text heuristic over words like "failed" is deliberately absent:
70
+ * a test log that prints the word is not a failing command.
71
+ *
72
+ * @param result - the execution-local result.
73
+ * @param text - the effective model-facing text of that result.
74
+ * @returns whether the result proves a failure.
75
+ */
76
+ export function failureOf(result, text) {
77
+ if (!result)
78
+ return false;
79
+ if (result.isError === true)
80
+ return true;
81
+ const status = structuredExitStatus(result.value);
82
+ if (status)
83
+ return status.exitCode !== 0 || status.signal !== undefined;
84
+ return exitMarkerFailure(text);
85
+ }
86
+ /** The primitive structured facts one result exposes, for the tail summary. */
87
+ function structuredFacts(result) {
88
+ const facts = {};
89
+ if (!result)
90
+ return facts;
91
+ if (result.isError !== undefined)
92
+ facts.isError = result.isError === true;
93
+ const status = structuredExitStatus(result.value);
94
+ if (status) {
95
+ facts.exitCode = status.exitCode;
96
+ if (status.signal !== undefined)
97
+ facts.signal = status.signal;
98
+ }
99
+ let value = result.value;
100
+ if (typeof value === 'string' && /^\s*[{[]/.test(value)) {
101
+ try {
102
+ value = JSON.parse(value);
103
+ }
104
+ catch {
105
+ value = undefined;
106
+ }
107
+ }
108
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
109
+ const record = value;
110
+ for (const key of ['ok', 'status', 'timedOut', 'timeout', 'isError', 'exitCode', 'signal']) {
111
+ const field = record[key];
112
+ if (typeof field === 'string' || typeof field === 'number' || typeof field === 'boolean')
113
+ facts[key] = field;
114
+ }
115
+ }
116
+ return facts;
117
+ }
118
+ /** Whether structured facts alone prove (or at least suspect) a failure. */
119
+ function factsSuspectFailure(facts) {
120
+ if (facts.isError === true)
121
+ return true;
122
+ if (typeof facts.exitCode === 'number' && facts.exitCode !== 0)
123
+ return true;
124
+ if (typeof facts.signal === 'string' && facts.signal.length > 0)
125
+ return true;
126
+ if (facts.ok === false || facts.timedOut === true || facts.timeout === true)
127
+ return true;
128
+ if (typeof facts.status === 'string' && /fail|error|timeout|timed_?out/i.test(facts.status))
129
+ return true;
130
+ return false;
131
+ }
132
+ /**
133
+ * Turn one observed result into closing-evidence candidates.
134
+ *
135
+ * The regex is a prefilter and a floor, never a conclusion: matching lines are
136
+ * kept whatever else happens, and a non-matching result still contributes its
137
+ * tail summary (with the structured facts) to System One. A result is a failure
138
+ * *suspicion* when a structured fact, a marker line, or a broader cue says so;
139
+ * what the result really means is decided by the closing judgment.
140
+ *
141
+ * @param tool - tool name that produced the result.
142
+ * @param result - the execution-local result.
143
+ * @param text - the effective model-facing text.
144
+ * @returns bounded candidates, diagnostics first.
145
+ */
146
+ export function evidenceOf(tool, result, text) {
147
+ const entries = [];
148
+ const lines = text.split(/\r?\n/);
149
+ const diagnostics = lines.filter((line) => FAILURE_MARKER.test(line));
150
+ for (const line of diagnostics) {
151
+ const clipped = clip(line.trim(), EVIDENCE_CHARS);
152
+ if (clipped.length > 0)
153
+ entries.push({ tool, text: clipped, priority: 'diagnostic', suspect: true });
154
+ }
155
+ const facts = structuredFacts(result);
156
+ const factText = Object.keys(facts).length > 0 ? `{${JSON.stringify(facts)}} ` : '';
157
+ const collapsed = text.replace(/\s+/g, ' ').trim();
158
+ const tail = clip(`${factText}${collapsed}`, EVIDENCE_TAIL_CHARS);
159
+ if (tail.length > 0) {
160
+ entries.push({
161
+ tool,
162
+ text: `${tool} tail: ${tail}`,
163
+ priority: 'tail',
164
+ suspect: failureOf(result, text)
165
+ || diagnostics.length > 0
166
+ || factsSuspectFailure(facts)
167
+ || FAILURE_CUE.test(text)
168
+ });
169
+ }
170
+ if (diagnostics.length === 0) {
171
+ const head = clip(collapsed, EVIDENCE_OTHER_CHARS);
172
+ if (head.length > 0) {
173
+ entries.push({ tool, text: `${tool}: ${head}`, priority: 'other', suspect: FAILURE_CUE.test(text) });
174
+ }
175
+ }
176
+ return entries;
177
+ }
178
+ /**
179
+ * Assemble the turn's evidence candidates into one budgeted string.
180
+ *
181
+ * Priority order is diagnostic → tail → other. A diagnostic line is the safety
182
+ * floor and is never dropped; everything else competes for the budget and the
183
+ * dropped characters are reported so the truncation is auditable.
184
+ *
185
+ * @param entries - candidates, oldest first.
186
+ * @param budget - character budget of the assembled text.
187
+ * @returns assembled text plus the kept/dropped character counts.
188
+ */
189
+ export function assembleEvidence(entries, budget) {
190
+ const lines = [];
191
+ let retained = 0;
192
+ let truncated = 0;
193
+ for (const priority of ['diagnostic', 'tail', 'other']) {
194
+ for (const entry of entries) {
195
+ if (entry.priority !== priority)
196
+ continue;
197
+ const size = entry.text.length + (lines.length > 0 ? 1 : 0);
198
+ const fits = priority === 'diagnostic' || retained + size <= budget;
199
+ if (!fits) {
200
+ truncated += size;
201
+ continue;
202
+ }
203
+ lines.push(entry.text);
204
+ retained += size;
205
+ }
206
+ }
207
+ return { text: lines.join('\n'), retainedChars: retained, truncatedChars: truncated };
208
+ }
209
+ //# sourceMappingURL=evidence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evidence.js","sourceRoot":"","sources":["../../../../src/vendor/harness-reflex/core/evidence.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAyBjC,uCAAuC;AACvC,MAAM,CAAC,MAAM,cAAc,GAAG,GAAG,CAAC;AAClC,+CAA+C;AAC/C,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,gFAAgF;AAChF,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAExC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,sIAAsI,CAAC;AAErK;;;;;GAKG;AACH,MAAM,WAAW,GAAG,IAAI,MAAM,CAC5B,GAAG,cAAc,CAAC,MAAM,kFAAkF;MACtG,iCAAiC,EACrC,GAAG,CACJ,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAc;IACjD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAClE,MAAM,SAAS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AAC;AACjB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,gBAAgB,CAC9B,OAAiC,EACjC,MAAc;IAEd,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,KAAK,MAAM,QAAQ,IAAI,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAU,EAAE,CAAC;QAChE,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC5B,IAAI,KAAK,CAAC,QAAQ,KAAK,QAAQ;gBAAE,SAAS;YAC1C,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5D,MAAM,IAAI,GAAG,QAAQ,KAAK,YAAY,IAAI,QAAQ,GAAG,IAAI,IAAI,MAAM,CAAC;YACpE,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,SAAS,IAAI,IAAI,CAAC;gBAClB,SAAS;YACX,CAAC;YACD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YACvB,QAAQ,IAAI,IAAI,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,cAAc,EAAE,SAAS,EAAE,CAAC;AACxF,CAAC","sourcesContent":["/**\n * Evidence candidates and their budget.\n *\n * The closing judgment reads a bounded, prioritised digest of what the turn's\n * tool results said. This module builds those candidates from a *structural*\n * result value — an error flag, a canonical value, a message — and truncates\n * them by priority. It imports no tool-execution or message type from a host.\n *\n * @module core/evidence\n */\nimport type { TextBlockLike } from './text.js';\nimport { clip } from './text.js';\n\n/** When one evidence line was retained, for truncation priority. */\nexport type EvidencePriority = 'diagnostic' | 'tail' | 'other';\n\n/** One candidate the closing judgment may read. */\nexport interface EvidenceEntry {\n /** Tool that produced the result. */\n tool: string;\n /** Bounded line or summary. */\n text: string;\n /** Truncation priority (lower is safer). */\n priority: EvidencePriority;\n /** Whether the result behind this entry is a failure suspicion. */\n suspect: boolean;\n}\n\n/** The structural result facts this module reads: no host type required. */\nexport interface ToolResultLike {\n readonly isError?: boolean;\n readonly value?: unknown;\n readonly content?: readonly TextBlockLike[];\n readonly error?: { readonly message?: string };\n}\n\n/** Characters of one evidence line. */\nexport const EVIDENCE_CHARS = 400;\n/** Characters of one result's tail summary. */\nexport const EVIDENCE_TAIL_CHARS = 240;\n/** Characters of the \"other\" (non-diagnostic, non-tail) fallback per result. */\nexport const EVIDENCE_OTHER_CHARS = 120;\n\n/**\n * Matches the failure markers that make a result a *candidate* for the closing\n * evidence. A hit is a safety floor: the line is kept whatever the budget says.\n * A miss is never a \"failure-free\" conclusion — the tail summary goes to System\n * One, which decides what the result means.\n */\nexport const FAILURE_MARKER = /(\\berror\\b|\\berrors\\b|\\bfailed\\b|\\bfailure\\b|\\bfailures\\b|\\bfail\\b|exit code [1-9]|\\bnot ok\\b|\\bFAIL\\b|\\bexception\\b|\\btraceback\\b)/i;\n\n/**\n * Prefilter for a failure *suspicion* — the deterministic trigger that makes a\n * closing judgment worth buying. It is broader than {@link FAILURE_MARKER}\n * because `{ok:false}`, a timeout, and a Chinese error must reach System One\n * too; none of these decides anything by itself.\n */\nconst FAILURE_CUE = new RegExp(\n `${FAILURE_MARKER.source}|\\\\bok\\\\b\\\\s*[:=]\\\\s*false|\"ok\"\\\\s*:\\\\s*false|\\\\btimed?\\\\s*out\\\\b|\\\\btimeout\\\\b|`\n + '失败|错误|异常|超时|无法|未通过|仍有失败|还有失败|报错',\n 'i'\n);\n\n/**\n * The exit status one tool result carries in its own canonical value.\n *\n * A shell result is *reported*, not errored: a command that exits 1 returns a\n * successful result whose `value.exitCode` is the whole truth. The distinction\n * matters twice over — a correction that never fires because the failure looked\n * like a success, and a closing check that reads a green claim over a red build\n * — so the status is taken from the tool's own structured field whenever the\n * payload exposes one.\n *\n * @param value - the result's canonical value, when it has one.\n * @returns the exit status, or `undefined` when the value is not a shell result.\n */\nexport function structuredExitStatus(value: unknown): { exitCode: number; signal?: string } | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const candidate = value as { exitCode?: unknown; signal?: unknown };\n if (typeof candidate.exitCode !== 'number' || !Number.isFinite(candidate.exitCode)) return undefined;\n const status: { exitCode: number; signal?: string } = { exitCode: candidate.exitCode };\n if (typeof candidate.signal === 'string') status.signal = candidate.signal;\n return status;\n}\n\n/**\n * Whether the text ends in the host's own exit marker for a failed command.\n *\n * The marker is the last line of the model-facing content, so anchoring it to the\n * end of the text keeps an *ordinary* result that merely mentions \"exit code 1\"\n * in its body from being misread as a failure. This is the fallback for a result\n * that carries no structured value — a virtual tool, a replay from an older\n * record — not a replacement for {@link structuredExitStatus}.\n * @param text - the model-facing text.\n * @returns whether the last marker line reports a non-zero exit or a signal.\n */\nexport function exitMarkerFailure(text: string): boolean {\n const match = /(?:^|\\n)\\[exit code: ([0-9]+)\\]\\s*$/.exec(text);\n if (match) return Number(match[1]) !== 0;\n return /(?:^|\\n)\\[killed by signal: [^\\]\\n]+\\]\\s*$/.test(text);\n}\n\n/**\n * Whether one result is a failure the interventions may act on.\n *\n * Three sources, in order of authority: the host's own `isError` flag, the exit\n * status inside the tool's structured value, and the exit marker the host appends\n * to the text. A text heuristic over words like \"failed\" is deliberately absent:\n * a test log that prints the word is not a failing command.\n *\n * @param result - the execution-local result.\n * @param text - the effective model-facing text of that result.\n * @returns whether the result proves a failure.\n */\nexport function failureOf(result: Readonly<ToolResultLike> | undefined, text: string): boolean {\n if (!result) return false;\n if (result.isError === true) return true;\n const status = structuredExitStatus(result.value);\n if (status) return status.exitCode !== 0 || status.signal !== undefined;\n return exitMarkerFailure(text);\n}\n\n/** The primitive structured facts one result exposes, for the tail summary. */\nfunction structuredFacts(result: Readonly<ToolResultLike> | undefined): Record<string, string | number | boolean> {\n const facts: Record<string, string | number | boolean> = {};\n if (!result) return facts;\n if (result.isError !== undefined) facts.isError = result.isError === true;\n const status = structuredExitStatus(result.value);\n if (status) {\n facts.exitCode = status.exitCode;\n if (status.signal !== undefined) facts.signal = status.signal;\n }\n let value: unknown = result.value;\n if (typeof value === 'string' && /^\\s*[{[]/.test(value)) {\n try {\n value = JSON.parse(value);\n } catch {\n value = undefined;\n }\n }\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n const record = value as Record<string, unknown>;\n for (const key of ['ok', 'status', 'timedOut', 'timeout', 'isError', 'exitCode', 'signal']) {\n const field = record[key];\n if (typeof field === 'string' || typeof field === 'number' || typeof field === 'boolean') facts[key] = field;\n }\n }\n return facts;\n}\n\n/** Whether structured facts alone prove (or at least suspect) a failure. */\nfunction factsSuspectFailure(facts: Readonly<Record<string, string | number | boolean>>): boolean {\n if (facts.isError === true) return true;\n if (typeof facts.exitCode === 'number' && facts.exitCode !== 0) return true;\n if (typeof facts.signal === 'string' && facts.signal.length > 0) return true;\n if (facts.ok === false || facts.timedOut === true || facts.timeout === true) return true;\n if (typeof facts.status === 'string' && /fail|error|timeout|timed_?out/i.test(facts.status)) return true;\n return false;\n}\n\n/**\n * Turn one observed result into closing-evidence candidates.\n *\n * The regex is a prefilter and a floor, never a conclusion: matching lines are\n * kept whatever else happens, and a non-matching result still contributes its\n * tail summary (with the structured facts) to System One. A result is a failure\n * *suspicion* when a structured fact, a marker line, or a broader cue says so;\n * what the result really means is decided by the closing judgment.\n *\n * @param tool - tool name that produced the result.\n * @param result - the execution-local result.\n * @param text - the effective model-facing text.\n * @returns bounded candidates, diagnostics first.\n */\nexport function evidenceOf(\n tool: string,\n result: Readonly<ToolResultLike> | undefined,\n text: string\n): EvidenceEntry[] {\n const entries: EvidenceEntry[] = [];\n const lines = text.split(/\\r?\\n/);\n const diagnostics = lines.filter((line) => FAILURE_MARKER.test(line));\n for (const line of diagnostics) {\n const clipped = clip(line.trim(), EVIDENCE_CHARS);\n if (clipped.length > 0) entries.push({ tool, text: clipped, priority: 'diagnostic', suspect: true });\n }\n const facts = structuredFacts(result);\n const factText = Object.keys(facts).length > 0 ? `{${JSON.stringify(facts)}} ` : '';\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const tail = clip(`${factText}${collapsed}`, EVIDENCE_TAIL_CHARS);\n if (tail.length > 0) {\n entries.push({\n tool,\n text: `${tool} tail: ${tail}`,\n priority: 'tail',\n suspect:\n failureOf(result, text)\n || diagnostics.length > 0\n || factsSuspectFailure(facts)\n || FAILURE_CUE.test(text)\n });\n }\n if (diagnostics.length === 0) {\n const head = clip(collapsed, EVIDENCE_OTHER_CHARS);\n if (head.length > 0) {\n entries.push({ tool, text: `${tool}: ${head}`, priority: 'other', suspect: FAILURE_CUE.test(text) });\n }\n }\n return entries;\n}\n\n/**\n * Assemble the turn's evidence candidates into one budgeted string.\n *\n * Priority order is diagnostic → tail → other. A diagnostic line is the safety\n * floor and is never dropped; everything else competes for the budget and the\n * dropped characters are reported so the truncation is auditable.\n *\n * @param entries - candidates, oldest first.\n * @param budget - character budget of the assembled text.\n * @returns assembled text plus the kept/dropped character counts.\n */\nexport function assembleEvidence(\n entries: readonly EvidenceEntry[],\n budget: number\n): { text: string; retainedChars: number; truncatedChars: number } {\n const lines: string[] = [];\n let retained = 0;\n let truncated = 0;\n for (const priority of ['diagnostic', 'tail', 'other'] as const) {\n for (const entry of entries) {\n if (entry.priority !== priority) continue;\n const size = entry.text.length + (lines.length > 0 ? 1 : 0);\n const fits = priority === 'diagnostic' || retained + size <= budget;\n if (!fits) {\n truncated += size;\n continue;\n }\n lines.push(entry.text);\n retained += size;\n }\n }\n return { text: lines.join('\\n'), retainedChars: retained, truncatedChars: truncated };\n}\n"]}
@@ -0,0 +1,221 @@
1
+ /**
2
+ * The deterministic pre-trigger, the judgment call, and the cost accounting.
3
+ *
4
+ * The expensive path of every capability is one System 1 judgment. This module
5
+ * owns the cheap path that decides whether a judgment is worth buying, the
6
+ * once-per-turn call itself (memoized by the window it is about), and the
7
+ * bookkeeping that bills exactly one judgment per call. The transport arrives as
8
+ * one `buy(step)` callback and never as the service itself; the clock is a
9
+ * {@link ClockPort}; neither is imported from a host.
10
+ *
11
+ * @module core/judge
12
+ */
13
+ import type { StagnationCheckResponse } from '../backend/types.js';
14
+ import type { ClockPort } from '../ports/clock.js';
15
+ import type { StagnationBackendPort } from '../ports/decision.js';
16
+ import type { JudgmentState, JudgmentStep } from './orchestrate-host.js';
17
+ import type { PolicySnapshot } from './policy.js';
18
+ /** One step of one agent's detection window. */
19
+ export interface ObservedStep {
20
+ /** `tool:argumentsDigest` — the identity a repetition is measured on. */
21
+ signature: string;
22
+ tool: string;
23
+ input: string;
24
+ output: string;
25
+ error: string;
26
+ failed: boolean;
27
+ turn: number;
28
+ at: number;
29
+ /** Whether the step was a legitimate wait query rather than progress. */
30
+ wait?: boolean;
31
+ }
32
+ /** Why a deterministic pre-trigger wants a judgment. */
33
+ export interface StagnationSuspicion {
34
+ suspicious: boolean;
35
+ /** The pattern the trigger suspects, before System 1 confirms it. */
36
+ pattern?: 'repetition' | 'oscillation' | 'failing_retry';
37
+ /** Human-readable trigger facts, for the audit record. */
38
+ note: string;
39
+ /** How many steps the pattern was measured on. */
40
+ repeats: number;
41
+ }
42
+ /**
43
+ * Count the identical trailing repeats of one signature.
44
+ * @param steps - observed steps, oldest first.
45
+ * @param signature - the identity to count.
46
+ * @returns the length of the trailing run of that signature.
47
+ */
48
+ export declare function countTrailingRepeats(steps: readonly ObservedStep[], signature: string): number;
49
+ /**
50
+ * Count the trailing consecutive failures.
51
+ * @param steps - observed steps, oldest first.
52
+ * @returns the length of the trailing run of failing steps.
53
+ */
54
+ export declare function countTrailingFailures(steps: readonly ObservedStep[]): number;
55
+ /**
56
+ * Whether the window's tail alternates between exactly two call identities.
57
+ *
58
+ * `A B A B` is the cheapest loop to miss and among the most wasteful to run:
59
+ * neither call repeats consecutively, so a consecutive-repeat trigger never
60
+ * fires.
61
+ * @param steps - observed steps, oldest first.
62
+ * @param window - how many trailing steps to inspect.
63
+ * @returns whether the tail oscillates.
64
+ */
65
+ export declare function detectOscillation(steps: readonly ObservedStep[], window: number): boolean;
66
+ /**
67
+ * Decide, locally and deterministically, whether a judgment is worth spending.
68
+ *
69
+ * This is the cost gate of the whole surface: the expensive path is a System 1
70
+ * call, and it only opens when the *cheap* path already sees a pattern. A single
71
+ * distinctive call is never judged, however large its output.
72
+ *
73
+ * @param steps - observed steps, oldest first.
74
+ * @param options - thresholds, window, and the current call identity.
75
+ * @returns the suspicion, with `suspicious: false` when nothing justifies a call.
76
+ */
77
+ export declare function suspicionOf(steps: readonly ObservedStep[], options: {
78
+ repeatThreshold: number;
79
+ failureThreshold: number;
80
+ window: number;
81
+ signature: string;
82
+ }): StagnationSuspicion;
83
+ /** The verdict that stands in when no judgment could be spent. */
84
+ export declare const EMPTY_VERDICT: StagnationCheckResponse;
85
+ /** What one judgment cost, charged exactly once per judgment. */
86
+ export interface JudgmentCharge {
87
+ judgments: number;
88
+ memoHits: number;
89
+ localLatencyMs: number;
90
+ remoteLatencyMs: number;
91
+ judgeTokens: number;
92
+ }
93
+ /** One token and latency account of a mode or a capability. */
94
+ export interface InterventionCostBucket {
95
+ /** Decisions planned. */
96
+ plans: number;
97
+ /** Decisions whose plan was executed. */
98
+ applied: number;
99
+ /** System 1 judgments paid for. */
100
+ judgments: number;
101
+ /** Judgments served from the per-turn verdict memo instead of a new call. */
102
+ memoHits: number;
103
+ /** Milliseconds spent in local, deterministic work. */
104
+ localLatencyMs: number;
105
+ /** Milliseconds spent waiting for System 1. */
106
+ remoteLatencyMs: number;
107
+ /** Tokens the judgments reasoned about. */
108
+ judgeTokens: number;
109
+ /** Tokens of the payloads decisions were made about. */
110
+ originalTokens: number;
111
+ /** Tokens the candidates would carry. */
112
+ candidateTokens: number;
113
+ /** Tokens the candidates would have saved. */
114
+ potentialSavedTokens: number;
115
+ /** Tokens actually removed from the model-visible surface. */
116
+ actualSavedTokens: number;
117
+ /** Tokens actually added to the model-visible surface. */
118
+ injectedTokens: number;
119
+ }
120
+ /** A fresh, zeroed cost bucket. */
121
+ export declare function emptyBucket(): InterventionCostBucket;
122
+ /** One charge against a mode's and a capability's account. */
123
+ export interface CostCharge {
124
+ judgments?: number;
125
+ memoHits?: number;
126
+ localLatencyMs?: number;
127
+ remoteLatencyMs?: number;
128
+ judgeTokens?: number;
129
+ originalTokens?: number;
130
+ candidateTokens?: number;
131
+ potentialSavedTokens?: number;
132
+ actualSavedTokens?: number;
133
+ injectedTokens?: number;
134
+ }
135
+ /**
136
+ * Add one charge to one bucket.
137
+ *
138
+ * Every counter has exactly one writer, so a reader can add the parts up without
139
+ * meeting a number twice.
140
+ * @param bucket - the bucket to bill.
141
+ * @param plans - decisions planned by this charge.
142
+ * @param applied - decisions applied by this charge.
143
+ * @param charge - the token/latency/decision counts.
144
+ */
145
+ export declare function applyCharge(bucket: InterventionCostBucket, plans: number, applied: number, charge: CostCharge): void;
146
+ /** The state one judgment memo and the two budgets live in. */
147
+ export interface VerdictMemoState extends JudgmentState {
148
+ verdictTurn: number;
149
+ /** Identity of the window the cached verdict was about. */
150
+ verdictKey: string;
151
+ verdict?: StagnationCheckResponse;
152
+ }
153
+ /** The outcome of one judgment request. */
154
+ export interface JudgmentOutcome {
155
+ useful: boolean;
156
+ paid: boolean;
157
+ reused: boolean;
158
+ judgeTokens: number;
159
+ localLatencyMs: number;
160
+ remoteLatencyMs: number;
161
+ skip?: string;
162
+ response: StagnationCheckResponse;
163
+ }
164
+ /**
165
+ * The memo key of one judgment: the question plus the trailing window it is
166
+ * asked about.
167
+ * @param goal - the wait/context question, when one was asked.
168
+ * @param steps - the window.
169
+ * @param repeatThreshold - how many trailing signatures identify the window.
170
+ * @returns a stable key.
171
+ */
172
+ export declare function judgmentKey(goal: string | undefined, steps: readonly ObservedStep[], repeatThreshold: number): string;
173
+ /**
174
+ * Ask for one stagnation verdict, reusing this turn's answer when the window is
175
+ * the same one.
176
+ *
177
+ * The question is the trailing window plus the context it is asked in, so the
178
+ * answer is cached against both: the same episode is never judged twice, while
179
+ * a *different* episode or a different wait context in the same turn is a new
180
+ * question — and therefore subject to the turn's budget.
181
+ *
182
+ * The purchase is this function's, not the host's: `buy` is called only after
183
+ * the memo missed, after both budgets admitted the question, and after
184
+ * {@link spendJudgment} booked the slot. A host that was handed the transport
185
+ * instead would have to reproduce that order, and the one place a wrong answer is
186
+ * a model-visible regression is the place the type would stop helping.
187
+ *
188
+ * @param args - state, policy, the host's `buy`, clock, window, question, and
189
+ * abort signal.
190
+ * @returns the outcome, including why a judgment was refused.
191
+ */
192
+ export declare function runJudgment(args: {
193
+ state: VerdictMemoState;
194
+ policy: PolicySnapshot;
195
+ /** One purchase: ask the service about one step, and report what it cost. */
196
+ buy?: (step: JudgmentStep) => Promise<StagnationCheckResponse>;
197
+ /**
198
+ * The pre-g-046 channel: a service handed over whole, instead of a purchase.
199
+ *
200
+ * Kept **only** for the frozen parity snapshot
201
+ * (`packages/dsh-harness-reflex/src/baseline/interventions.ts`), which is the
202
+ * oracle of the refactor and may not be touched. Every live caller passes
203
+ * {@link buy}; the snapshot's `#judge` still passes its composition's service,
204
+ * and the parity run therefore keeps this channel exercised.
205
+ *
206
+ * @deprecated Pass `buy`. Nothing added from now on should use this.
207
+ */
208
+ backend?: StagnationBackendPort;
209
+ clock: ClockPort;
210
+ steps: readonly ObservedStep[];
211
+ goal?: string;
212
+ signal?: AbortSignal;
213
+ }): Promise<JudgmentOutcome>;
214
+ /**
215
+ * The charge of one judgment, so every judgment is billed exactly once.
216
+ * @param verdict - the outcome of the judgment call.
217
+ * @param started - clock reading at hook entry.
218
+ * @param finished - clock reading now.
219
+ * @returns the charge.
220
+ */
221
+ export declare function judgmentCharge(verdict: Pick<JudgmentOutcome, 'paid' | 'reused' | 'judgeTokens' | 'localLatencyMs' | 'remoteLatencyMs'>, started: number, finished: number): JudgmentCharge;