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 (121) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +103 -23
  3. package/USER_GUIDE.md +121 -43
  4. package/dist/adapters/agy.js +1 -1
  5. package/dist/adapters/agy.js.map +1 -1
  6. package/dist/adapters/codex.d.ts +133 -4
  7. package/dist/adapters/codex.js +325 -2
  8. package/dist/adapters/codex.js.map +1 -1
  9. package/dist/backend/defaults.d.ts +31 -0
  10. package/dist/backend/defaults.js +32 -0
  11. package/dist/backend/defaults.js.map +1 -0
  12. package/dist/backend/jev.js +6 -5
  13. package/dist/backend/jev.js.map +1 -1
  14. package/dist/backend/mock.d.ts +12 -1
  15. package/dist/backend/mock.js +34 -0
  16. package/dist/backend/mock.js.map +1 -1
  17. package/dist/backend/simple-jev.js +5 -4
  18. package/dist/backend/simple-jev.js.map +1 -1
  19. package/dist/backend/types.d.ts +34 -0
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/cli/index.js +5 -3
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/core/closing.d.ts +90 -0
  24. package/dist/core/closing.js +111 -0
  25. package/dist/core/closing.js.map +1 -0
  26. package/dist/core/evidence.d.ts +119 -0
  27. package/dist/core/evidence.js +209 -0
  28. package/dist/core/evidence.js.map +1 -0
  29. package/dist/core/judge.d.ts +221 -0
  30. package/dist/core/judge.js +251 -0
  31. package/dist/core/judge.js.map +1 -0
  32. package/dist/core/orchestrate-closing.d.ts +237 -0
  33. package/dist/core/orchestrate-closing.js +250 -0
  34. package/dist/core/orchestrate-closing.js.map +1 -0
  35. package/dist/core/orchestrate-correction.d.ts +209 -0
  36. package/dist/core/orchestrate-correction.js +141 -0
  37. package/dist/core/orchestrate-correction.js.map +1 -0
  38. package/dist/core/orchestrate-host.d.ts +225 -0
  39. package/dist/core/orchestrate-host.js +80 -0
  40. package/dist/core/orchestrate-host.js.map +1 -0
  41. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  42. package/dist/core/orchestrate-stagnation.js +270 -0
  43. package/dist/core/orchestrate-stagnation.js.map +1 -0
  44. package/dist/core/orchestrate.d.ts +357 -0
  45. package/dist/core/orchestrate.js +418 -0
  46. package/dist/core/orchestrate.js.map +1 -0
  47. package/dist/core/policy.d.ts +122 -0
  48. package/dist/core/policy.js +102 -0
  49. package/dist/core/policy.js.map +1 -0
  50. package/dist/core/prune-plan.d.ts +141 -0
  51. package/dist/core/prune-plan.js +390 -0
  52. package/dist/core/prune-plan.js.map +1 -0
  53. package/dist/core/score.d.ts +2 -2
  54. package/dist/core/score.js.map +1 -1
  55. package/dist/core/text.d.ts +36 -0
  56. package/dist/core/text.js +66 -0
  57. package/dist/core/text.js.map +1 -0
  58. package/dist/hook/cli.d.ts +9 -0
  59. package/dist/hook/cli.js +52 -0
  60. package/dist/hook/cli.js.map +1 -0
  61. package/dist/hook/contract.d.ts +125 -0
  62. package/dist/hook/contract.js +159 -0
  63. package/dist/hook/contract.js.map +1 -0
  64. package/dist/hook/decision.d.ts +97 -0
  65. package/dist/hook/decision.js +955 -0
  66. package/dist/hook/decision.js.map +1 -0
  67. package/dist/hook/memory-store.d.ts +81 -0
  68. package/dist/hook/memory-store.js +157 -0
  69. package/dist/hook/memory-store.js.map +1 -0
  70. package/dist/hook/payload.d.ts +55 -0
  71. package/dist/hook/payload.js +129 -0
  72. package/dist/hook/payload.js.map +1 -0
  73. package/dist/hook/run.d.ts +48 -0
  74. package/dist/hook/run.js +218 -0
  75. package/dist/hook/run.js.map +1 -0
  76. package/dist/hook/store-port.d.ts +72 -0
  77. package/dist/hook/store-port.js +2 -0
  78. package/dist/hook/store-port.js.map +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +1 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/ports/audit.d.ts +18 -0
  83. package/dist/ports/audit.js +11 -0
  84. package/dist/ports/audit.js.map +1 -0
  85. package/dist/ports/clock.d.ts +14 -0
  86. package/dist/ports/clock.js +11 -0
  87. package/dist/ports/clock.js.map +1 -0
  88. package/dist/ports/decision.d.ts +75 -0
  89. package/dist/ports/decision.js +2 -0
  90. package/dist/ports/decision.js.map +1 -0
  91. package/dist/ports/index.d.ts +14 -0
  92. package/dist/ports/index.js +2 -0
  93. package/dist/ports/index.js.map +1 -0
  94. package/dist/ports/log.d.ts +22 -0
  95. package/dist/ports/log.js +12 -0
  96. package/dist/ports/log.js.map +1 -0
  97. package/dist/ports/state.d.ts +46 -0
  98. package/dist/ports/state.js +13 -0
  99. package/dist/ports/state.js.map +1 -0
  100. package/dist/state/clock.d.ts +40 -0
  101. package/dist/state/clock.js +43 -0
  102. package/dist/state/clock.js.map +1 -0
  103. package/dist/state/file-store.d.ts +340 -0
  104. package/dist/state/file-store.js +849 -0
  105. package/dist/state/file-store.js.map +1 -0
  106. package/dist/state/paths.d.ts +41 -0
  107. package/dist/state/paths.js +73 -0
  108. package/dist/state/paths.js.map +1 -0
  109. package/docs/USER_GUIDE.en.md +79 -36
  110. package/docs/claude-code.md +281 -0
  111. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  112. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  113. package/docs/dsh-plugin.md +54 -54
  114. package/docs/release-checklist-v0.1.0.md +32 -21
  115. package/docs/release-handbook-porting-notes.md +11 -11
  116. package/docs/release-handbook.md +55 -30
  117. package/docs/release-notes-v0.1.0.md +27 -14
  118. package/docs/release-notes-v0.3.0.md +152 -0
  119. package/docs/research/claude-code-harness.md +607 -0
  120. package/docs/research/pi-harness.md +621 -0
  121. package/package.json +16 -7
@@ -0,0 +1,90 @@
1
+ /** Completion claim candidates submitted to one closing judgment. */
2
+ export declare const MAX_CLAIMS = 3;
3
+ /** Minimum sentence length worth classifying as a claim candidate. */
4
+ export declare const MIN_CLAIM_CHARS = 8;
5
+ /** One classified candidate. */
6
+ export interface ClaimClassificationLike {
7
+ readonly statement: string;
8
+ readonly isClaim: boolean;
9
+ readonly confidence: number;
10
+ }
11
+ /** The classification half of a closing judgment's answer. */
12
+ export interface ClaimClassificationResponseLike {
13
+ readonly results: readonly ClaimClassificationLike[];
14
+ readonly latencyMs: number;
15
+ }
16
+ /** One verification result. */
17
+ export interface ClosingResultLike {
18
+ readonly statement: string;
19
+ readonly outcome: string;
20
+ readonly confidence: number;
21
+ }
22
+ /** The verification half of a closing judgment's answer. */
23
+ export interface ClosingVerdictLike {
24
+ readonly passed: boolean;
25
+ readonly results: readonly ClosingResultLike[];
26
+ }
27
+ /**
28
+ * The *candidate* sentences of one turn's assistant text.
29
+ *
30
+ * Deterministic and semantic-free on purpose: splitting, de-duplication, the
31
+ * length floor, and the last-{@link MAX_CLAIMS} bound are all the local work
32
+ * this module may do. Whether a candidate really claims completion is the
33
+ * backend's answer — an English word list would miss a Chinese "全部通过" and
34
+ * read `not complete` as the opposite, so there is none here.
35
+ *
36
+ * @param text - the turn's assistant text.
37
+ * @returns bounded, deduplicated candidates in their original order.
38
+ */
39
+ export declare function claimCandidates(text: string): string[];
40
+ /**
41
+ * The classified statements that really claim completion, above the confidence
42
+ * floor.
43
+ * @param classification - the backend's answer.
44
+ * @param minConfidence - the resolved claim floor.
45
+ * @returns one assertion per accepted claim.
46
+ */
47
+ export declare function claimsOf(classification: ClaimClassificationResponseLike, minConfidence: number): Array<{
48
+ statement: string;
49
+ }>;
50
+ /**
51
+ * The contradicted statements, clipped for the corrective message.
52
+ * @param verdict - the verification answer.
53
+ * @returns the statements whose evidence contradicts them.
54
+ */
55
+ export declare function contradictedOf(verdict: ClosingVerdictLike): string[];
56
+ /**
57
+ * How many verification results could not decide.
58
+ * @param verdict - the verification answer.
59
+ * @returns the `escalate` count.
60
+ */
61
+ export declare function undecidedOf(verdict: ClosingVerdictLike): number;
62
+ /**
63
+ * The skip reason of a closing judgment that does not object.
64
+ *
65
+ * `escalate` is not a contradiction: it means the gate could not decide — an
66
+ * unavailable backend degrades exactly this way — and steering a turn on an
67
+ * undecided verdict would turn a backend failure into a model-visible objection.
68
+ *
69
+ * @param verdict - the verification answer.
70
+ * @param contradicted - the statements that really contradict.
71
+ * @returns the machine reason to record, or `undefined` when the turn is steered.
72
+ */
73
+ export declare function closingSkipReason(verdict: ClosingVerdictLike, contradicted: readonly string[]): string | undefined;
74
+ /**
75
+ * Tokens the classification request reasoned about.
76
+ * @param statements - submitted candidates.
77
+ * @returns the estimated token count.
78
+ */
79
+ export declare function classificationTokens(statements: readonly string[]): number;
80
+ /**
81
+ * Tokens the verification request reasoned about: the classification batch plus
82
+ * the evidence the gate read.
83
+ * @param classificationTokensSpent - tokens of the classification request.
84
+ * @param claims - accepted claims submitted to verification.
85
+ * @param evidence - the assembled evidence text.
86
+ * @returns the estimated token count.
87
+ */
88
+ export declare function verificationTokens(classificationTokensSpent: number, claims: readonly {
89
+ statement: string;
90
+ }[], evidence: string): number;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Closing-check candidate selection and the closing decision.
3
+ *
4
+ * Two deterministic jobs live here: split a turn's own words into *candidate*
5
+ * completion claims (splitting, de-duplication, the length floor, the trailing
6
+ * cap), and decide what a classification/verification answer means. Whether a
7
+ * sentence really claims completion is a semantic question and is answered by
8
+ * the backend; this module never guesses with a word list.
9
+ *
10
+ * @module core/closing
11
+ */
12
+ import { clip, estimateTokens } from './text.js';
13
+ /** Completion claim candidates submitted to one closing judgment. */
14
+ export const MAX_CLAIMS = 3;
15
+ /** Minimum sentence length worth classifying as a claim candidate. */
16
+ export const MIN_CLAIM_CHARS = 8;
17
+ /**
18
+ * The *candidate* sentences of one turn's assistant text.
19
+ *
20
+ * Deterministic and semantic-free on purpose: splitting, de-duplication, the
21
+ * length floor, and the last-{@link MAX_CLAIMS} bound are all the local work
22
+ * this module may do. Whether a candidate really claims completion is the
23
+ * backend's answer — an English word list would miss a Chinese "全部通过" and
24
+ * read `not complete` as the opposite, so there is none here.
25
+ *
26
+ * @param text - the turn's assistant text.
27
+ * @returns bounded, deduplicated candidates in their original order.
28
+ */
29
+ export function claimCandidates(text) {
30
+ const candidates = [];
31
+ const seen = new Set();
32
+ for (const raw of text.split(/(?<=[.!?。!?\n])/)) {
33
+ const sentence = raw.replace(/\s+/g, ' ').trim();
34
+ if (sentence.length < MIN_CLAIM_CHARS)
35
+ continue;
36
+ const statement = clip(sentence, 200);
37
+ if (seen.has(statement))
38
+ continue;
39
+ seen.add(statement);
40
+ candidates.push(statement);
41
+ }
42
+ return candidates.length > MAX_CLAIMS ? candidates.slice(candidates.length - MAX_CLAIMS) : candidates;
43
+ }
44
+ /**
45
+ * The classified statements that really claim completion, above the confidence
46
+ * floor.
47
+ * @param classification - the backend's answer.
48
+ * @param minConfidence - the resolved claim floor.
49
+ * @returns one assertion per accepted claim.
50
+ */
51
+ export function claimsOf(classification, minConfidence) {
52
+ return classification.results
53
+ .filter((item) => item.isClaim && item.confidence >= minConfidence)
54
+ .map((item) => ({ statement: item.statement }));
55
+ }
56
+ /**
57
+ * The contradicted statements, clipped for the corrective message.
58
+ * @param verdict - the verification answer.
59
+ * @returns the statements whose evidence contradicts them.
60
+ */
61
+ export function contradictedOf(verdict) {
62
+ return verdict.results
63
+ .filter((item) => item.outcome === 'contradicted')
64
+ .map((item) => clip(item.statement, 160));
65
+ }
66
+ /**
67
+ * How many verification results could not decide.
68
+ * @param verdict - the verification answer.
69
+ * @returns the `escalate` count.
70
+ */
71
+ export function undecidedOf(verdict) {
72
+ return verdict.results.filter((item) => item.outcome === 'escalate').length;
73
+ }
74
+ /**
75
+ * The skip reason of a closing judgment that does not object.
76
+ *
77
+ * `escalate` is not a contradiction: it means the gate could not decide — an
78
+ * unavailable backend degrades exactly this way — and steering a turn on an
79
+ * undecided verdict would turn a backend failure into a model-visible objection.
80
+ *
81
+ * @param verdict - the verification answer.
82
+ * @param contradicted - the statements that really contradict.
83
+ * @returns the machine reason to record, or `undefined` when the turn is steered.
84
+ */
85
+ export function closingSkipReason(verdict, contradicted) {
86
+ if (contradicted.length > 0)
87
+ return undefined;
88
+ const undecided = undecidedOf(verdict);
89
+ return undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed';
90
+ }
91
+ /**
92
+ * Tokens the classification request reasoned about.
93
+ * @param statements - submitted candidates.
94
+ * @returns the estimated token count.
95
+ */
96
+ export function classificationTokens(statements) {
97
+ return statements.reduce((sum, statement) => sum + estimateTokens(statement), 0);
98
+ }
99
+ /**
100
+ * Tokens the verification request reasoned about: the classification batch plus
101
+ * the evidence the gate read.
102
+ * @param classificationTokensSpent - tokens of the classification request.
103
+ * @param claims - accepted claims submitted to verification.
104
+ * @param evidence - the assembled evidence text.
105
+ * @returns the estimated token count.
106
+ */
107
+ export function verificationTokens(classificationTokensSpent, claims, evidence) {
108
+ return (classificationTokensSpent
109
+ + claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(evidence)));
110
+ }
111
+ //# sourceMappingURL=closing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"closing.js","sourceRoot":"","sources":["../../src/core/closing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjD,qEAAqE;AACrE,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,CAAC;AAC5B,sEAAsE;AACtE,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,CAAC;AA4BjC;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,MAAM,UAAU,GAAa,EAAE,CAAC;IAChC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,EAAE,CAAC;QAChD,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;QACjD,IAAI,QAAQ,CAA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C;AAC9E,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAA2B,EAAE,YAA+B;IAC5F,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9C,MAAM,SAAS,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,OAAO,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC,qBAAqB,CAAC;AACtH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAA6B;IAChE,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;AACnF,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAChC,yBAAiC,EACjC,MAAwC,EACxC,QAAgB;IAEhB,OAAO,CACL,yBAAyB;UACvB,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC,CAC/F,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Closing-check candidate selection and the closing decision.\n *\n * Two deterministic jobs live here: split a turn's own words into *candidate*\n * completion claims (splitting, de-duplication, the length floor, the trailing\n * cap), and decide what a classification/verification answer means. Whether a\n * sentence really claims completion is a semantic question and is answered by\n * the backend; this module never guesses with a word list.\n *\n * @module core/closing\n */\nimport { clip, estimateTokens } from './text.js';\n\n/** Completion claim candidates submitted to one closing judgment. */\nexport const MAX_CLAIMS = 3;\n/** Minimum sentence length worth classifying as a claim candidate. */\nexport const MIN_CLAIM_CHARS = 8;\n\n/** One classified candidate. */\nexport interface ClaimClassificationLike {\n readonly statement: string;\n readonly isClaim: boolean;\n readonly confidence: number;\n}\n\n/** The classification half of a closing judgment's answer. */\nexport interface ClaimClassificationResponseLike {\n readonly results: readonly ClaimClassificationLike[];\n readonly latencyMs: number;\n}\n\n/** One verification result. */\nexport interface ClosingResultLike {\n readonly statement: string;\n readonly outcome: string;\n readonly confidence: number;\n}\n\n/** The verification half of a closing judgment's answer. */\nexport interface ClosingVerdictLike {\n readonly passed: boolean;\n readonly results: readonly ClosingResultLike[];\n}\n\n/**\n * The *candidate* sentences of one turn's assistant text.\n *\n * Deterministic and semantic-free on purpose: splitting, de-duplication, the\n * length floor, and the last-{@link MAX_CLAIMS} bound are all the local work\n * this module may do. Whether a candidate really claims completion is the\n * backend's answer — an English word list would miss a Chinese \"全部通过\" and\n * read `not complete` as the opposite, so there is none here.\n *\n * @param text - the turn's assistant text.\n * @returns bounded, deduplicated candidates in their original order.\n */\nexport function claimCandidates(text: string): string[] {\n const candidates: string[] = [];\n const seen = new Set<string>();\n for (const raw of text.split(/(?<=[.!?。!?\\n])/)) {\n const sentence = raw.replace(/\\s+/g, ' ').trim();\n if (sentence.length < MIN_CLAIM_CHARS) continue;\n const statement = clip(sentence, 200);\n if (seen.has(statement)) continue;\n seen.add(statement);\n candidates.push(statement);\n }\n return candidates.length > MAX_CLAIMS ? candidates.slice(candidates.length - MAX_CLAIMS) : candidates;\n}\n\n/**\n * The classified statements that really claim completion, above the confidence\n * floor.\n * @param classification - the backend's answer.\n * @param minConfidence - the resolved claim floor.\n * @returns one assertion per accepted claim.\n */\nexport function claimsOf(\n classification: ClaimClassificationResponseLike,\n minConfidence: number\n): Array<{ statement: string }> {\n return classification.results\n .filter((item) => item.isClaim && item.confidence >= minConfidence)\n .map((item) => ({ statement: item.statement }));\n}\n\n/**\n * The contradicted statements, clipped for the corrective message.\n * @param verdict - the verification answer.\n * @returns the statements whose evidence contradicts them.\n */\nexport function contradictedOf(verdict: ClosingVerdictLike): string[] {\n return verdict.results\n .filter((item) => item.outcome === 'contradicted')\n .map((item) => clip(item.statement, 160));\n}\n\n/**\n * How many verification results could not decide.\n * @param verdict - the verification answer.\n * @returns the `escalate` count.\n */\nexport function undecidedOf(verdict: ClosingVerdictLike): number {\n return verdict.results.filter((item) => item.outcome === 'escalate').length;\n}\n\n/**\n * The skip reason of a closing judgment that does not object.\n *\n * `escalate` is not a contradiction: it means the gate could not decide — an\n * unavailable backend degrades exactly this way — and steering a turn on an\n * undecided verdict would turn a backend failure into a model-visible objection.\n *\n * @param verdict - the verification answer.\n * @param contradicted - the statements that really contradict.\n * @returns the machine reason to record, or `undefined` when the turn is steered.\n */\nexport function closingSkipReason(verdict: ClosingVerdictLike, contradicted: readonly string[]): string | undefined {\n if (contradicted.length > 0) return undefined;\n const undecided = undecidedOf(verdict);\n return undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed';\n}\n\n/**\n * Tokens the classification request reasoned about.\n * @param statements - submitted candidates.\n * @returns the estimated token count.\n */\nexport function classificationTokens(statements: readonly string[]): number {\n return statements.reduce((sum, statement) => sum + estimateTokens(statement), 0);\n}\n\n/**\n * Tokens the verification request reasoned about: the classification batch plus\n * the evidence the gate read.\n * @param classificationTokensSpent - tokens of the classification request.\n * @param claims - accepted claims submitted to verification.\n * @param evidence - the assembled evidence text.\n * @returns the estimated token count.\n */\nexport function verificationTokens(\n classificationTokensSpent: number,\n claims: readonly { statement: string }[],\n evidence: string\n): number {\n return (\n classificationTokensSpent\n + claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(evidence))\n );\n}\n"]}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Evidence candidates and their budget.
3
+ *
4
+ * The closing judgment reads a bounded, prioritised digest of what the turn's
5
+ * tool results said. This module builds those candidates from a *structural*
6
+ * result value — an error flag, a canonical value, a message — and truncates
7
+ * them by priority. It imports no tool-execution or message type from a host.
8
+ *
9
+ * @module core/evidence
10
+ */
11
+ import type { TextBlockLike } from './text.js';
12
+ /** When one evidence line was retained, for truncation priority. */
13
+ export type EvidencePriority = 'diagnostic' | 'tail' | 'other';
14
+ /** One candidate the closing judgment may read. */
15
+ export interface EvidenceEntry {
16
+ /** Tool that produced the result. */
17
+ tool: string;
18
+ /** Bounded line or summary. */
19
+ text: string;
20
+ /** Truncation priority (lower is safer). */
21
+ priority: EvidencePriority;
22
+ /** Whether the result behind this entry is a failure suspicion. */
23
+ suspect: boolean;
24
+ }
25
+ /** The structural result facts this module reads: no host type required. */
26
+ export interface ToolResultLike {
27
+ readonly isError?: boolean;
28
+ readonly value?: unknown;
29
+ readonly content?: readonly TextBlockLike[];
30
+ readonly error?: {
31
+ readonly message?: string;
32
+ };
33
+ }
34
+ /** Characters of one evidence line. */
35
+ export declare const EVIDENCE_CHARS = 400;
36
+ /** Characters of one result's tail summary. */
37
+ export declare const EVIDENCE_TAIL_CHARS = 240;
38
+ /** Characters of the "other" (non-diagnostic, non-tail) fallback per result. */
39
+ export declare const EVIDENCE_OTHER_CHARS = 120;
40
+ /**
41
+ * Matches the failure markers that make a result a *candidate* for the closing
42
+ * evidence. A hit is a safety floor: the line is kept whatever the budget says.
43
+ * A miss is never a "failure-free" conclusion — the tail summary goes to System
44
+ * One, which decides what the result means.
45
+ */
46
+ export declare const FAILURE_MARKER: RegExp;
47
+ /**
48
+ * The exit status one tool result carries in its own canonical value.
49
+ *
50
+ * A shell result is *reported*, not errored: a command that exits 1 returns a
51
+ * successful result whose `value.exitCode` is the whole truth. The distinction
52
+ * matters twice over — a correction that never fires because the failure looked
53
+ * like a success, and a closing check that reads a green claim over a red build
54
+ * — so the status is taken from the tool's own structured field whenever the
55
+ * payload exposes one.
56
+ *
57
+ * @param value - the result's canonical value, when it has one.
58
+ * @returns the exit status, or `undefined` when the value is not a shell result.
59
+ */
60
+ export declare function structuredExitStatus(value: unknown): {
61
+ exitCode: number;
62
+ signal?: string;
63
+ } | undefined;
64
+ /**
65
+ * Whether the text ends in the host's own exit marker for a failed command.
66
+ *
67
+ * The marker is the last line of the model-facing content, so anchoring it to the
68
+ * end of the text keeps an *ordinary* result that merely mentions "exit code 1"
69
+ * in its body from being misread as a failure. This is the fallback for a result
70
+ * that carries no structured value — a virtual tool, a replay from an older
71
+ * record — not a replacement for {@link structuredExitStatus}.
72
+ * @param text - the model-facing text.
73
+ * @returns whether the last marker line reports a non-zero exit or a signal.
74
+ */
75
+ export declare function exitMarkerFailure(text: string): boolean;
76
+ /**
77
+ * Whether one result is a failure the interventions may act on.
78
+ *
79
+ * Three sources, in order of authority: the host's own `isError` flag, the exit
80
+ * status inside the tool's structured value, and the exit marker the host appends
81
+ * to the text. A text heuristic over words like "failed" is deliberately absent:
82
+ * a test log that prints the word is not a failing command.
83
+ *
84
+ * @param result - the execution-local result.
85
+ * @param text - the effective model-facing text of that result.
86
+ * @returns whether the result proves a failure.
87
+ */
88
+ export declare function failureOf(result: Readonly<ToolResultLike> | undefined, text: string): boolean;
89
+ /**
90
+ * Turn one observed result into closing-evidence candidates.
91
+ *
92
+ * The regex is a prefilter and a floor, never a conclusion: matching lines are
93
+ * kept whatever else happens, and a non-matching result still contributes its
94
+ * tail summary (with the structured facts) to System One. A result is a failure
95
+ * *suspicion* when a structured fact, a marker line, or a broader cue says so;
96
+ * what the result really means is decided by the closing judgment.
97
+ *
98
+ * @param tool - tool name that produced the result.
99
+ * @param result - the execution-local result.
100
+ * @param text - the effective model-facing text.
101
+ * @returns bounded candidates, diagnostics first.
102
+ */
103
+ export declare function evidenceOf(tool: string, result: Readonly<ToolResultLike> | undefined, text: string): EvidenceEntry[];
104
+ /**
105
+ * Assemble the turn's evidence candidates into one budgeted string.
106
+ *
107
+ * Priority order is diagnostic → tail → other. A diagnostic line is the safety
108
+ * floor and is never dropped; everything else competes for the budget and the
109
+ * dropped characters are reported so the truncation is auditable.
110
+ *
111
+ * @param entries - candidates, oldest first.
112
+ * @param budget - character budget of the assembled text.
113
+ * @returns assembled text plus the kept/dropped character counts.
114
+ */
115
+ export declare function assembleEvidence(entries: readonly EvidenceEntry[], budget: number): {
116
+ text: string;
117
+ retainedChars: number;
118
+ truncatedChars: number;
119
+ };
@@ -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/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,GAAG,KAAiD,CAAC;IACpE,IAAI,OAAO,SAAS,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC;QAAE,OAAO,SAAS,CAAC;IACrG,MAAM,MAAM,GAA0C,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,EAAE,CAAC;IACvF,IAAI,OAAO,SAAS,CAAC,MAAM,KAAK,QAAQ;QAAE,MAAM,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC;IAC3E,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,MAAM,KAAK,GAAG,qCAAqC,CAAC,I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AAM,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"]}