@pi-unipi/background-tasks 2.6.3 → 2.9.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 (58) hide show
  1. package/package.json +6 -5
  2. package/src/__tests__/anthropic-attribution.test.ts +0 -195
  3. package/src/__tests__/config.test.ts +0 -137
  4. package/src/__tests__/core.test.ts +0 -493
  5. package/src/__tests__/delegate-artifacts.test.ts +0 -528
  6. package/src/__tests__/delegate-budget.test.ts +0 -456
  7. package/src/__tests__/delegate-launch.test.ts +0 -676
  8. package/src/__tests__/delegate-result-package.test.ts +0 -350
  9. package/src/__tests__/delegate-seed.test.ts +0 -392
  10. package/src/__tests__/durable-fs.test.ts +0 -559
  11. package/src/__tests__/extension-api.test.ts +0 -579
  12. package/src/__tests__/fusion-artifacts.test.ts +0 -1039
  13. package/src/__tests__/fusion-budget.test.ts +0 -1356
  14. package/src/__tests__/fusion-claude-cache.test.ts +0 -320
  15. package/src/__tests__/fusion-config.test.ts +0 -335
  16. package/src/__tests__/fusion-context-prompts.test.ts +0 -670
  17. package/src/__tests__/fusion-evaluation.test.ts +0 -315
  18. package/src/__tests__/fusion-extraction-equivalence.test.ts +0 -58
  19. package/src/__tests__/fusion-golden-bytes.test.ts +0 -35
  20. package/src/__tests__/fusion-high-cardinality.test.ts +0 -192
  21. package/src/__tests__/fusion-model-selector.test.ts +0 -205
  22. package/src/__tests__/fusion-orchestrator.test.ts +0 -1194
  23. package/src/__tests__/fusion-rpc.test.ts +0 -369
  24. package/src/__tests__/fusion-sdk.test.ts +0 -1226
  25. package/src/__tests__/fusion-v5-core.test.ts +0 -219
  26. package/src/__tests__/fusion-validate-orchestrator.test.ts +0 -240
  27. package/src/__tests__/fusion-web-fetch.test.ts +0 -485
  28. package/src/__tests__/fusion-workflows.test.ts +0 -59
  29. package/src/__tests__/helpers/delegate-deterministic-seed.ts +0 -109
  30. package/src/__tests__/helpers/delegate-seed-subprocess.ts +0 -10
  31. package/src/__tests__/helpers/fusion-canonical-subprocess.ts +0 -21
  32. package/src/__tests__/helpers/fusion-canonical.ts +0 -140
  33. package/src/__tests__/helpers/fusion-fake-pi.ts +0 -279
  34. package/src/__tests__/helpers/fusion-golden-corpus.ts +0 -500
  35. package/src/__tests__/helpers/fusion-high-cardinality.ts +0 -140
  36. package/src/__tests__/helpers/normalize.ts +0 -22
  37. package/src/__tests__/helpers/pi-hook-contract-evidence.json +0 -18
  38. package/src/__tests__/pi-launch.test.ts +0 -202
  39. package/src/__tests__/registry.test.ts +0 -1580
  40. package/src/__tests__/scripted-provider/delegate-ambient-provider.test.ts +0 -130
  41. package/src/__tests__/scripted-provider/delegate-child-guard.test.ts +0 -631
  42. package/src/__tests__/scripted-provider/delegate-guard-provider.ts +0 -403
  43. package/src/__tests__/scripted-provider/follow-up.test.ts +0 -448
  44. package/src/__tests__/scripted-provider/fusion-output-recovery.test.ts +0 -132
  45. package/src/__tests__/scripted-provider/fusion-reason.test.ts +0 -310
  46. package/src/__tests__/scripted-provider/fusion-runtime-guard.test.ts +0 -163
  47. package/src/__tests__/scripted-provider/hook-contract-provider.ts +0 -179
  48. package/src/__tests__/scripted-provider/hook-probe-a.ts +0 -3
  49. package/src/__tests__/scripted-provider/hook-probe-b.ts +0 -3
  50. package/src/__tests__/scripted-provider/hook-probe-extension.ts +0 -126
  51. package/src/__tests__/scripted-provider/output-recovery-provider.ts +0 -153
  52. package/src/__tests__/scripted-provider/pi-hook-contract-evidence.json +0 -18
  53. package/src/__tests__/scripted-provider/pi-hook-contract.test.ts +0 -477
  54. package/src/__tests__/scripted-provider/runtime-guard-probe.ts +0 -28
  55. package/src/__tests__/scripted-provider/runtime-guard-provider.ts +0 -49
  56. package/src/__tests__/scripted-provider/scripted-provider-extension.ts +0 -408
  57. package/src/__tests__/task-manager.test.ts +0 -479
  58. package/src/__tests__/windows-taskkill.test.ts +0 -161
@@ -1,315 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import {
4
- assertMergerFindingCoverage,
5
- boundedEvaluationErrors,
6
- parseFusionEvaluation,
7
- parseFusionValidationCandidateReport,
8
- recoverFencedFusionValidationCandidateReport,
9
- renderValidatedFusionValidationReport,
10
- validateFusionEvaluation,
11
- validateFusionFindingAccounting,
12
- } from '../fusion/evaluation.js';
13
- import {
14
- FUSION_EVALUATION_SCHEMA_VERSION,
15
- FUSION_VALIDATE_CANDIDATE_SCHEMA_VERSION,
16
- FusionError,
17
- type FusionValidationFindingAccounting,
18
- } from '../fusion/types.js';
19
-
20
- function validEvaluation(): Record<string, unknown> {
21
- return {
22
- schema_version: FUSION_EVALUATION_SCHEMA_VERSION,
23
- candidate_assessments: [
24
- {
25
- candidate_id: 'A',
26
- summary: 'solid',
27
- strengths: ['clear'],
28
- limitations: ['brief'],
29
- useful_contributions: ['structure'],
30
- risks: ['misses edge case'],
31
- },
32
- {
33
- candidate_id: 'B',
34
- summary: 'detailed',
35
- strengths: ['coverage'],
36
- limitations: ['wordy'],
37
- useful_contributions: ['tests'],
38
- risks: ['overstates'],
39
- },
40
- {
41
- candidate_id: 'C',
42
- summary: 'balanced',
43
- strengths: ['tradeoffs'],
44
- limitations: ['few examples'],
45
- useful_contributions: ['risk list'],
46
- risks: ['needs cleanup'],
47
- },
48
- ],
49
- agreements: ['all address the request'],
50
- conflicts: [
51
- {
52
- topic: 'scope',
53
- positions: [
54
- { candidate_id: 'A', position: 'small' },
55
- { candidate_id: 'B', position: 'broad' },
56
- ],
57
- resolution: 'use the smallest complete scope',
58
- },
59
- ],
60
- synthesis_plan: {
61
- must_include: [{ candidate_id: 'C', contribution: 'risk list' }],
62
- must_resolve: ['scope'],
63
- must_avoid: ['unsupported claims'],
64
- },
65
- };
66
- }
67
-
68
- function singletonAccounting(): FusionValidationFindingAccounting {
69
- return {
70
- findings: [
71
- {
72
- id: 'A-F001',
73
- candidate_id: 'A',
74
- severity: 'high',
75
- location: 'src/fusion.ts:12',
76
- evidence: 'read line 12',
77
- impact: 'breaks workflow',
78
- summary: 'workflow bug',
79
- },
80
- ],
81
- decisions: [
82
- {
83
- source_id: 'A-F001',
84
- disposition: 'include',
85
- rationale: 'candidate A: A-F001 is supported by evidence',
86
- group_id: 'G001',
87
- },
88
- ],
89
- groups: [
90
- {
91
- group_id: 'G001',
92
- source_ids: ['A-F001'],
93
- severity: 'high',
94
- location: 'src/fusion.ts:12',
95
- evidence: 'read line 12',
96
- impact: 'breaks workflow',
97
- summary: 'workflow bug',
98
- rationale: 'the evidence supports inclusion',
99
- },
100
- ],
101
- };
102
- }
103
-
104
- void describe('fusion evaluation schema', () => {
105
- void it('accepts a closed valid evaluation object', () => {
106
- const parsed = parseFusionEvaluation(JSON.stringify(validEvaluation()));
107
- assert.equal(parsed.schema_version, FUSION_EVALUATION_SCHEMA_VERSION);
108
- assert.deepEqual(
109
- parsed.candidate_assessments.map((entry) => entry.candidate_id),
110
- ['A', 'B', 'C'],
111
- );
112
- });
113
-
114
- void it('rejects wrappers and invalid JSON without substring extraction', () => {
115
- assert.throws(() => parseFusionEvaluation('```json\n{}\n```'), /JSON only/);
116
- assert.throws(
117
- () => parseFusionEvaluation(`${JSON.stringify(validEvaluation())}\nprose`),
118
- /JSON only/,
119
- );
120
- });
121
-
122
- void it('rejects unknown fields, duplicate IDs, and blank strings', () => {
123
- const withExtra = validEvaluation();
124
- withExtra['winner'] = 'A';
125
- const extra = validateFusionEvaluation(withExtra);
126
- assert.equal(extra.ok, false);
127
- if (!extra.ok) assert.match(extra.errors.join('\n'), /unknown key winner/);
128
-
129
- const duplicate = validEvaluation();
130
- const assessments = duplicate['candidate_assessments'];
131
- assert.ok(Array.isArray(assessments));
132
- const first = assessments[0];
133
- assert.ok(typeof first === 'object' && first !== null && !Array.isArray(first));
134
- Reflect.set(first, 'candidate_id', 'B');
135
- const duplicateResult = validateFusionEvaluation(duplicate);
136
- assert.equal(duplicateResult.ok, false);
137
- if (!duplicateResult.ok) assert.match(duplicateResult.errors.join('\n'), /unique/);
138
-
139
- const blank = validEvaluation();
140
- blank['agreements'] = [' '];
141
- const blankResult = validateFusionEvaluation(blank);
142
- assert.equal(blankResult.ok, false);
143
- if (!blankResult.ok) assert.match(blankResult.errors.join('\n'), /non-blank/);
144
- });
145
-
146
- void it('requires conflict positions from distinct candidates without duplicate IDs', () => {
147
- const invalid = validEvaluation();
148
- invalid['conflicts'] = [
149
- {
150
- topic: 'scope',
151
- positions: [
152
- { candidate_id: 'A', position: 'small' },
153
- { candidate_id: 'A', position: 'also small' },
154
- ],
155
- resolution: 'compare real disagreement',
156
- },
157
- ];
158
- const result = validateFusionEvaluation(invalid);
159
- assert.equal(result.ok, false);
160
- if (!result.ok) assert.match(result.errors.join('\n'), /two distinct|unique/);
161
-
162
- const duplicateWithTwoIds = validEvaluation();
163
- duplicateWithTwoIds['conflicts'] = [
164
- {
165
- topic: 'scope',
166
- positions: [
167
- { candidate_id: 'A', position: 'small' },
168
- { candidate_id: 'A', position: 'duplicate small' },
169
- { candidate_id: 'B', position: 'broad' },
170
- ],
171
- resolution: 'compare real disagreement',
172
- },
173
- ];
174
- const duplicateResult = validateFusionEvaluation(duplicateWithTwoIds);
175
- assert.equal(duplicateResult.ok, false);
176
- if (!duplicateResult.ok) assert.match(duplicateResult.errors.join('\n'), /unique/);
177
- });
178
-
179
- void it('keeps validation parsing strict while narrowly recovering one audited JSON fence', () => {
180
- const report = JSON.stringify({
181
- schema_version: FUSION_VALIDATE_CANDIDATE_SCHEMA_VERSION,
182
- findings: [],
183
- verified: ['read src/file.ts'],
184
- limitations: [],
185
- });
186
- assert.throws(
187
- () => parseFusionValidationCandidateReport(`\`\`\`json\n${report}\n\`\`\``, 'A'),
188
- /structured JSON only/,
189
- );
190
- const recovered = recoverFencedFusionValidationCandidateReport(
191
- `Validation complete.\n\n\`\`\`json\n${report}\n\`\`\``,
192
- 'A',
193
- );
194
- assert.ok(recovered);
195
- assert.equal(recovered.normalization, 'prose_then_markdown_json_fence');
196
- assert.equal(recovered.response, report);
197
- assert.deepEqual(recovered.report.verified, ['read src/file.ts']);
198
- assert.equal(
199
- recoverFencedFusionValidationCandidateReport(
200
- `\`\`\`json\n${report}\n\`\`\`\ntrailing prose`,
201
- 'A',
202
- ),
203
- undefined,
204
- );
205
- });
206
-
207
- void it('validates validation finding singleton, duplicate, and exclusion contracts', () => {
208
- const singleton = singletonAccounting();
209
- assert.deepEqual(validateFusionFindingAccounting(singleton), []);
210
- const rendered = renderValidatedFusionValidationReport(singleton);
211
- assert.match(rendered, /# Validation report/);
212
- assert.match(rendered, /workflow bug/);
213
- assert.doesNotMatch(rendered, /A-F001|candidate A/i, 'rendered rationale must not expose source ids or candidate labels');
214
-
215
- const duplicateDecision: FusionValidationFindingAccounting = {
216
- ...singleton,
217
- decisions: [singleton.decisions[0]!, { ...singleton.decisions[0]!, rationale: 'duplicate' }],
218
- };
219
- assert.match(validateFusionFindingAccounting(duplicateDecision).join('\n'), /accounted more than once/);
220
-
221
- const includeWithoutGroup: FusionValidationFindingAccounting = {
222
- ...singleton,
223
- decisions: [{ source_id: 'A-F001', disposition: 'include', rationale: 'supported' }],
224
- };
225
- assert.match(validateFusionFindingAccounting(includeWithoutGroup).join('\n'), /group_id required/);
226
-
227
- const excludedWithGroup: FusionValidationFindingAccounting = {
228
- ...singleton,
229
- decisions: [
230
- { source_id: 'A-F001', disposition: 'exclude', rationale: 'duplicate of stronger finding', group_id: 'G001' },
231
- ],
232
- };
233
- assert.match(validateFusionFindingAccounting(excludedWithGroup).join('\n'), /group_id must be omitted/);
234
-
235
- const excluded: FusionValidationFindingAccounting = {
236
- ...singleton,
237
- decisions: [{ source_id: 'A-F001', disposition: 'exclude', rationale: 'candidate A: not supported' }],
238
- groups: [],
239
- };
240
- assert.deepEqual(validateFusionFindingAccounting(excluded), []);
241
- const excludedReport = renderValidatedFusionValidationReport(excluded);
242
- assert.match(excludedReport, /No included findings/);
243
- assert.match(excludedReport, /Excluded source findings/);
244
- assert.doesNotMatch(excludedReport, /candidate A|A-F001/i);
245
- });
246
-
247
- void it('merges distinct duplicate source findings into one resolved group', () => {
248
- const singleton = singletonAccounting();
249
- const duplicate: FusionValidationFindingAccounting = {
250
- findings: [
251
- ...singleton.findings,
252
- {
253
- ...singleton.findings[0]!,
254
- id: 'B-F001',
255
- candidate_id: 'B',
256
- severity: 'minor',
257
- evidence: 'independent read of line 12',
258
- },
259
- ],
260
- decisions: [
261
- { source_id: 'A-F001', disposition: 'include', rationale: 'supported', group_id: 'G001' },
262
- { source_id: 'B-F001', disposition: 'include', rationale: 'same defect', group_id: 'G001' },
263
- ],
264
- groups: [
265
- {
266
- ...singleton.groups[0]!,
267
- source_ids: ['A-F001', 'B-F001'],
268
- severity: 'high',
269
- evidence: 'both reviewers independently read line 12',
270
- rationale: 'same location and failure mechanism; high severity has stronger support',
271
- },
272
- ],
273
- };
274
- assert.deepEqual(validateFusionFindingAccounting(duplicate), []);
275
- const rendered = renderValidatedFusionValidationReport(duplicate);
276
- assert.equal((rendered.match(/### high: workflow bug/gu) ?? []).length, 1);
277
- assert.doesNotMatch(rendered, /### minor:/u);
278
- });
279
-
280
- void it('rejects validation merger dropped and invented group IDs', () => {
281
- const singleton = singletonAccounting();
282
- assert.doesNotThrow(() => assertMergerFindingCoverage(singleton, ['G001']));
283
- assert.throws(
284
- () => assertMergerFindingCoverage(singleton, []),
285
- /merger dropped included group G001/,
286
- );
287
- assert.throws(
288
- () => assertMergerFindingCoverage(singleton, ['G001', 'G999']),
289
- /invented or revived group G999/,
290
- );
291
- });
292
-
293
- void it('bounds validation errors for repair prompts and user-facing failures', () => {
294
- const errors = Array.from(
295
- { length: 200 },
296
- (_, index) => `error-${String(index)}-${'x'.repeat(800)}`,
297
- );
298
- const bounded = boundedEvaluationErrors(errors);
299
- assert.ok(bounded.length < errors.length);
300
- assert.ok(bounded.join('').length < 4300);
301
- assert.match(bounded.at(-1) ?? '', /omitted/);
302
- });
303
-
304
- void it('throws a typed error for invalid parsed content', () => {
305
- assert.throws(
306
- () =>
307
- parseFusionEvaluation(JSON.stringify({ schema_version: FUSION_EVALUATION_SCHEMA_VERSION })),
308
- (error: unknown) => {
309
- assert.ok(error instanceof FusionError);
310
- assert.equal(error.code, 'evaluation_invalid');
311
- return true;
312
- },
313
- );
314
- });
315
- });
@@ -1,58 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { buildFusionCleanTaskCanonicalInput } from '../fusion/clean-context.js';
4
- import { buildFusionCanonicalInput } from '../fusion/context.js';
5
- import { canonicalJson } from '../attested-pi-run.js';
6
- import { sessionWith, userMessage } from './helpers/fusion-canonical.js';
7
-
8
- void describe('fusion v5 context boundaries', () => {
9
- void it('keeps reason as the only workflow that projects parent conversation', () => {
10
- const sessionManager = sessionWith([userMessage('visible parent text')]);
11
- const built = buildFusionCanonicalInput({ cwd: '/repo', sessionManager, getSystemPrompt: () => 'parent system' }, { source: 'tool', request: 'reason about this', toolName: 'fusion_reason' });
12
- assert.equal(built.input.workflow, 'reason');
13
- assert.equal(built.input.context?.kind, 'session_projection');
14
- assert.match(built.serialized, /visible parent text/);
15
- assert.match(built.serialized, /parent system/);
16
- });
17
-
18
- void it('clean canonical input is byte-identical across unrelated parent sessions with same request and cwd', () => {
19
- const parentSentinel = 'PARENT-SESSION-SENTINEL-never-forward';
20
- const unrelatedLeft = sessionWith([userMessage(`left ${parentSentinel}`)]);
21
- const unrelatedRight = sessionWith([userMessage(`right ${parentSentinel}`)]);
22
- assert.notDeepEqual(unrelatedLeft.getEntries(), unrelatedRight.getEntries());
23
-
24
- const requests = {
25
- investigate: canonicalJson({ objective: 'inspect', background: [], deliverable: 'answer', scope: [], constraints: [] }),
26
- research: canonicalJson({ objective: 'research', background: [], deliverable: 'answer', scope: [], constraints: [], sources: [{ url: 'https://example.com/a', purpose: 'unit' }] }),
27
- validate: canonicalJson({ objective: 'validate', background: [], changeSummary: 'changed', scope: ['src'], acceptanceCriteria: ['works'], verification: { status: 'not_run', evidence: [], reason: 'unit' }, knownLimitations: [], exclusions: [] }),
28
- } as const;
29
-
30
- for (const [workflow, request] of Object.entries(requests) as Array<[keyof typeof requests, string]>) {
31
- const declaredSources = workflow === 'research'
32
- ? [{ url: 'https://example.com/a', purpose: 'unit' }]
33
- : [];
34
- const left = buildFusionCleanTaskCanonicalInput({ cwd: '/repo', source: 'tool', workflow, request, declaredSources });
35
- const right = buildFusionCleanTaskCanonicalInput({ cwd: '/repo', source: 'tool', workflow, request, declaredSources });
36
- assert.equal(left.serialized, right.serialized, workflow);
37
- assert.equal(left.input.context.kind, 'clean_task');
38
- assert.equal('system_prompt' in left.input, false);
39
- assert.equal('conversation_projection' in left.input, false);
40
- assert.equal('ledger' in left, false);
41
- assert.doesNotMatch(left.serialized, new RegExp(parentSentinel));
42
- }
43
- });
44
-
45
- void it('refuses old parent-session projection fallback before touching throwing clean accessors', () => {
46
- const throwingParent = {
47
- get cwd(): never { throw new Error('clean workflow touched parent cwd'); },
48
- get sessionManager(): never { throw new Error('clean workflow touched parent session'); },
49
- getSystemPrompt(): never { throw new Error('clean workflow touched parent system prompt'); },
50
- };
51
- for (const workflow of ['investigate', 'research', 'validate'] as const) {
52
- assert.throws(
53
- () => buildFusionCanonicalInput(throwingParent as never, { source: 'tool', request: 'clean', workflow }),
54
- /parent session projection is available only to the reason workflow/,
55
- );
56
- }
57
- });
58
- });
@@ -1,35 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { readFile } from 'node:fs/promises';
4
- import { createHash } from 'node:crypto';
5
- import { buildFusionCleanTaskCanonicalInput } from '../fusion/clean-context.js';
6
- import { canonicalJson } from '../attested-pi-run.js';
7
-
8
- async function fixture(path: string | URL): Promise<unknown> {
9
- return JSON.parse(await readFile(path, 'utf8')) as unknown;
10
- }
11
-
12
- void describe('fusion historical and v5 canonical fixtures', () => {
13
- void it('keeps historical v4 golden fixtures explicitly historical', async () => {
14
- const brainstorm = await fixture(new URL('../fixtures/fusion-golden-bytes.json', import.meta.url));
15
- const validate = await fixture(new URL('../fixtures/fusion-validate-golden-bytes.json', import.meta.url));
16
- assert.equal(typeof brainstorm, 'object');
17
- assert.equal(typeof validate, 'object');
18
- const bytes = await readFile(new URL('../fixtures/fusion-golden-bytes.json', import.meta.url));
19
- assert.equal(createHash('sha256').update(bytes).digest('hex').length, 64);
20
- });
21
-
22
- void it('pins a reviewed v5 clean canonical input shape without parent context', () => {
23
- const built = buildFusionCleanTaskCanonicalInput({
24
- cwd: '/repo',
25
- source: 'tool',
26
- workflow: 'investigate',
27
- request: canonicalJson({ objective: 'o', background: [], deliverable: 'd', scope: [], constraints: [] }),
28
- });
29
- assert.equal(built.input.schema_version, 'pi-background-tasks.fusion-input.v5');
30
- assert.equal(built.input.context.kind, 'clean_task');
31
- assert.equal('system_prompt' in built.input, false);
32
- assert.equal('conversation_projection' in built.input, false);
33
- assert.equal(built.serialized, canonicalJson(built.input));
34
- });
35
- });
@@ -1,192 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { canonicalJson } from '../attested-pi-run.js';
4
- import { FusionBudget } from '../fusion/budget.js';
5
- import {
6
- FUSION_COMMAND_CONTEXT_POLICY_ID,
7
- type ResolvedFusionModel,
8
- type ResolvedFusionModels,
9
- } from '../fusion/types.js';
10
- import {
11
- buildFrom,
12
- omissionEntries,
13
- projectedText,
14
- type ExpandedFusionOmissionEntry,
15
- } from './helpers/fusion-canonical.js';
16
- import { buildHighCardinalitySession } from './helpers/fusion-high-cardinality.js';
17
-
18
- /**
19
- * Regression coverage for the production incident in which omission receipts
20
- * grew to 43% of a 290 KB projected prompt (340 runs over 1,465 omitted
21
- * events). Existing fixtures used a few very large tool results and therefore
22
- * could not reproduce it: the cost came from receipt cardinality, not payload
23
- * size.
24
- */
25
- function resolved(qualifiedId: string, contextWindow: number): ResolvedFusionModel {
26
- const slash = qualifiedId.indexOf('/');
27
- return {
28
- selection: '$current',
29
- source: 'current',
30
- provider: qualifiedId.slice(0, slash),
31
- model: qualifiedId.slice(slash + 1),
32
- qualifiedId,
33
- thinkingLevel: 'high',
34
- contextWindow,
35
- maxOutputTokens: 32_768,
36
- };
37
- }
38
-
39
- function codexModels(): ResolvedFusionModels {
40
- return {
41
- candidates: [
42
- resolved('openai-codex/gpt-5.6-sol', 272_000),
43
- resolved('openai-codex/gpt-5.6-terra', 272_000),
44
- resolved('openai-codex/gpt-5.5', 272_000),
45
- ],
46
- evaluator: resolved('openai-codex/gpt-5.6-sol', 272_000),
47
- merger: resolved('openai-codex/gpt-5.6-sol', 272_000),
48
- };
49
- }
50
-
51
- void describe('fusion high-cardinality tool activity', () => {
52
- void it('keeps receipt metadata small when omitted events are numerous and short', () => {
53
- const session = buildHighCardinalitySession();
54
- const built = buildFrom(session.messages, { source: 'tool', request: 'summarize' });
55
- const projection = built.input.conversation_projection;
56
- const receipts = omissionEntries(built.input);
57
-
58
- // One receipt per retained-text separated run, and every event ledgered.
59
- assert.equal(receipts.length, session.expectedRuns);
60
- assert.equal(built.ledger.entries.length, session.expectedLedgerEvents);
61
- assert.equal(projection.accounting.omitted_run_count, session.expectedRuns);
62
- assert.equal(projection.accounting.omitted_event_count, session.expectedLedgerEvents);
63
-
64
- // Per-receipt cost is the quantity that regressed: the incident averaged
65
- // 356 bytes per receipt because each carried a run hash, ledger indices,
66
- // and a per-kind byte map. Pin the compact cost directly, since the ratio
67
- // to total payload depends on how much visible text a fixture happens to
68
- // contain and is therefore not a stable signal.
69
- const receiptBytes = projection.accounting.omission_receipt_utf8_bytes;
70
- const perReceipt = receiptBytes / receipts.length;
71
- assert.ok(
72
- perReceipt < 140,
73
- `each receipt must stay compact, saw ${perReceipt.toFixed(1)} bytes`,
74
- );
75
-
76
- // Receipt metadata must never exceed the conversational text it annotates.
77
- const visibleBytes =
78
- projection.accounting.included_user_text_bytes +
79
- projection.accounting.included_assistant_text_bytes;
80
- assert.ok(
81
- receiptBytes < visibleBytes,
82
- `receipts (${String(receiptBytes)} B) must not outweigh visible text (${String(visibleBytes)} B)`,
83
- );
84
- });
85
-
86
- void it('emits only the compact model-facing receipt tuple', () => {
87
- const session = buildHighCardinalitySession({ runs: 8 });
88
- const built = buildFrom(session.messages, { source: 'tool', request: 'r' });
89
- const compactReceipts = built.input.conversation_projection.entries.filter(
90
- (entry) => entry[0] === 'o',
91
- );
92
- assert.equal(compactReceipts.length, session.expectedRuns);
93
- for (const receipt of compactReceipts) {
94
- assert.equal(receipt.length, 4);
95
- assert.equal(receipt[0], 'o');
96
- const span = receipt[1];
97
- assert.equal(span.length, 2);
98
- assert.ok(span[0] <= span[1]);
99
- assert.ok(Number.isSafeInteger(receipt[2]) && receipt[2] >= 0);
100
- const counts = receipt[3];
101
- assert.equal(counts.length, 3);
102
- for (const value of counts) {
103
- assert.ok(Number.isSafeInteger(value) && value >= 0, 'tuple counts must be non-negative');
104
- }
105
- }
106
- for (const receipt of omissionEntries(built.input)) {
107
- assert.deepEqual(Object.keys(receipt).sort(), ['at', 'bytes', 'counts', 'kind']);
108
- }
109
- // Retired coordinates and hashes must not reappear in the prompt bytes.
110
- for (const banned of [
111
- 'ledger_run_sha256',
112
- 'ledger_index_first',
113
- 'ledger_index_last',
114
- 'source_ordinal_first',
115
- 'payload_bytes',
116
- ]) {
117
- assert.doesNotMatch(built.serialized, new RegExp(banned), banned);
118
- }
119
- });
120
-
121
- void it('reconciles every receipt against the ledger it summarizes', () => {
122
- const session = buildHighCardinalitySession({ runs: 12 });
123
- const built = buildFrom(session.messages, { source: 'tool', request: 'r' });
124
- const map = built.ledger.projection_map;
125
-
126
- // Every ledger row is represented exactly once.
127
- const covered = new Set<number>();
128
- for (const entry of map) {
129
- for (let i = entry.ledger_index_first; i <= entry.ledger_index_last; i++) {
130
- assert.equal(covered.has(i), false, `ledger row ${String(i)} mapped twice`);
131
- covered.add(i);
132
- }
133
- }
134
- assert.equal(covered.size, built.ledger.entries.length);
135
-
136
- // Receipt byte totals recompute exactly from the mapped ledger rows.
137
- const receipts = omissionEntries(built.input);
138
- const receiptMaps = map.filter((entry) => entry.entry_kind === 'omitted_activity');
139
- assert.equal(receiptMaps.length, receipts.length);
140
- for (const [index, entry] of receiptMaps.entries()) {
141
- const rows = built.ledger.entries.slice(
142
- entry.ledger_index_first,
143
- entry.ledger_index_last + 1,
144
- );
145
- const expected = rows
146
- .filter((row) => row.kind !== 'tool_result_image')
147
- .reduce((total, row) => total + row.payload_bytes, 0);
148
- const receipt = receipts[index];
149
- assert.ok(receipt);
150
- assert.equal(receipt.bytes, expected, `receipt ${String(index)} byte total mismatch`);
151
- }
152
- });
153
-
154
- void it('preserves all conversational text and forwards no tool payload', () => {
155
- const session = buildHighCardinalitySession({ runs: 20 });
156
- const built = buildFrom(session.messages, { source: 'tool', request: 'r' });
157
- const text = projectedText(built.input);
158
- for (let run = 0; run < 20; run++) {
159
- assert.match(text, new RegExp(`USER-TURN-${String(run)} `));
160
- assert.match(text, new RegExp(`ASSISTANT-TURN-${String(run)} `));
161
- }
162
- // Payload and thinking sentinels never reach the prompt.
163
- assert.doesNotMatch(built.serialized, /g{50}/);
164
- assert.doesNotMatch(built.serialized, /z{50}/);
165
- assert.doesNotMatch(built.serialized, /k{50}/);
166
- });
167
-
168
- void it('keeps input-only workflow preflight inside a real route budget', () => {
169
- const session = buildHighCardinalitySession();
170
- const built = buildFrom(session.messages, { source: 'tool', request: 'summarize' });
171
- const budget = new FusionBudget(codexModels(), FUSION_COMMAND_CONTEXT_POLICY_ID);
172
- const plan = budget.plan(built.input);
173
- assert.equal(plan.blockers.length, 0);
174
- for (const stage of plan.stages) {
175
- assert.ok(
176
- stage.input_only_input_tokens_upper_bound <= stage.allowed_input_tokens,
177
- `${stage.budget_stage} input must fit the limiting route, saw ${String(stage.input_only_input_tokens_upper_bound)} of ${String(stage.allowed_input_tokens)}`,
178
- );
179
- }
180
- assert.equal(plan.warnings.some((entry) => entry.warning_kind === 'worst_case_reservation'), true);
181
- });
182
-
183
- void it('produces byte-identical output for repeated construction', () => {
184
- const session = buildHighCardinalitySession({ runs: 30 });
185
- const first = buildFrom(session.messages, { source: 'tool', request: 'same' });
186
- const second = buildFrom(session.messages, { source: 'tool', request: 'same' });
187
- assert.equal(first.serialized, second.serialized);
188
- assert.equal(canonicalJson(first.ledger), canonicalJson(second.ledger));
189
- const receipts: readonly ExpandedFusionOmissionEntry[] = omissionEntries(first.input);
190
- assert.equal(receipts.length, session.expectedRuns);
191
- });
192
- });