@aiwg/cli 2026.10.12 → 2026.10.15

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 (104) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +44 -1
  4. package/dist/src/artifacts/corpus-tools/cli.js +32 -0
  5. package/dist/src/artifacts/corpus-tools/discovery-log.js +1 -1
  6. package/dist/src/artifacts/corpus-tools/expand-cli.js +89 -0
  7. package/dist/src/artifacts/corpus-tools/expand-queue.js +38 -0
  8. package/dist/src/artifacts/corpus-tools/expand-state.js +40 -0
  9. package/dist/src/artifacts/corpus-tools/expand.js +125 -0
  10. package/dist/src/artifacts/corpus-tools/resolve-cli.js +91 -0
  11. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  12. package/dist/src/artifacts/corpus-tools/resolve.js +105 -0
  13. package/dist/src/cli/handlers/doctor-args.js +40 -0
  14. package/dist/src/cli/handlers/doctor-help.js +4 -2
  15. package/dist/src/cli/handlers/use-bundle-counts.js +32 -6
  16. package/dist/src/cli/handlers/use-skill-assets.js +207 -0
  17. package/dist/src/cli/handlers/use.js +30 -193
  18. package/dist/src/cli/handlers/utilities.js +5 -31
  19. package/dist/src/config/authorization-cli.js +11 -3
  20. package/dist/src/config/worker-context.js +33 -4
  21. package/dist/src/decision/context-pruning-common.js +41 -0
  22. package/dist/src/decision/context-pruning-evaluation.js +366 -0
  23. package/dist/src/decision/context-pruning-pilot.js +431 -0
  24. package/dist/src/decision/context-pruning-types.js +19 -0
  25. package/dist/src/decision/context-pruning.js +5 -847
  26. package/dist/src/decision/ensemble/contract.js +4 -24
  27. package/dist/src/decision/heldout/collector.js +1 -1
  28. package/dist/src/decision/qualification/release.js +5 -62
  29. package/dist/src/extensions/manifest.js +8 -1
  30. package/dist/src/extensions/project-local-doctor.js +78 -2
  31. package/dist/src/extensions/validation.js +10 -11
  32. package/dist/src/features/catalog.js +1 -1
  33. package/dist/src/gates/evaluate.js +5 -15
  34. package/dist/src/gates/heldout.js +42 -0
  35. package/dist/src/gates/index.js +2 -1
  36. package/dist/src/gates/upstream-ceiling.js +111 -0
  37. package/dist/src/models/provider-models.js +5 -8
  38. package/dist/src/models/worker-installation-store.mjs +228 -0
  39. package/dist/src/models/worker-installation.mjs +7 -162
  40. package/dist/src/models/wrapper-definitions.js +14 -0
  41. package/dist/src/models/wrapper-deployment.js +48 -25
  42. package/dist/src/models/wrapper-enforcement.js +72 -0
  43. package/dist/src/policy/hitl-check.js +80 -0
  44. package/dist/src/providers/provider-definitions.js +10 -10
  45. package/dist/src/research/clients/arxiv.js +10 -4
  46. package/dist/src/research/clients/base.js +5 -4
  47. package/dist/src/research/clients/crossref.js +9 -1
  48. package/dist/src/research/clients/semantic-scholar.js +73 -44
  49. package/dist/src/research/identity.js +85 -0
  50. package/dist/src/research/index.js +1 -0
  51. package/dist/src/research/reference-match.js +89 -0
  52. package/dist/src/rules/activation.d.mts +2 -0
  53. package/dist/src/rules/activation.mjs +23 -0
  54. package/dist/src/rules/core-startup.d.mts +2 -0
  55. package/dist/src/rules/core-startup.mjs +31 -0
  56. package/dist/src/skills/adapters/local.js +32 -9
  57. package/dist/src/skills/agent-skills.js +2 -0
  58. package/dist/src/skills/cli-display.js +33 -0
  59. package/dist/src/skills/cli.js +2 -26
  60. package/dist/src/skills/collision-discovery.js +84 -0
  61. package/dist/src/skills/deployer.js +20 -75
  62. package/dist/src/skills/deployment-ownership.js +74 -0
  63. package/dist/src/skills/doctor.js +2 -2
  64. package/dist/src/skills/importer.js +4 -26
  65. package/dist/src/skills/registry.js +22 -7
  66. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  67. package/dist/src/smiths/context-pipeline/aiwg-md.js +3 -0
  68. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  69. package/dist/src/smiths/context-pipeline/generator.js +40 -104
  70. package/dist/src/smiths/context-pipeline/managed-hook.js +10 -0
  71. package/dist/src/smiths/context-pipeline/parallelism-section.js +7 -3
  72. package/package.json +6 -2
  73. package/tools/agents/deploy-agents.mjs +2 -123
  74. package/tools/agents/providers/antigravity.mjs +4 -6
  75. package/tools/agents/providers/base.mjs +3 -3
  76. package/tools/agents/providers/claude.mjs +3 -5
  77. package/tools/agents/providers/codex.mjs +3 -5
  78. package/tools/agents/providers/context-write.mjs +12 -0
  79. package/tools/agents/providers/copilot.mjs +3 -5
  80. package/tools/agents/providers/cursor.mjs +3 -5
  81. package/tools/agents/providers/factory.mjs +3 -5
  82. package/tools/agents/providers/grok-build.mjs +17 -12
  83. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  84. package/tools/agents/providers/hermes-startup.mjs +209 -0
  85. package/tools/agents/providers/hermes.mjs +9 -359
  86. package/tools/agents/providers/model-wrapper.mjs +90 -0
  87. package/tools/agents/providers/muse.mjs +3 -3
  88. package/tools/agents/providers/omp.mjs +3 -1
  89. package/tools/agents/providers/openclaw.mjs +3 -5
  90. package/tools/agents/providers/opencode.mjs +3 -5
  91. package/tools/agents/providers/pi.mjs +1 -1
  92. package/tools/agents/providers/provider-paths-staging.mjs +9 -0
  93. package/tools/agents/providers/rule-delivery.mjs +26 -228
  94. package/tools/agents/providers/rule-presentation.mjs +13 -4
  95. package/tools/agents/providers/rule-projection.mjs +119 -0
  96. package/tools/agents/providers/rule-startup.mjs +70 -0
  97. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  98. package/tools/agents/providers/warp.mjs +5 -7
  99. package/tools/agents/providers/windsurf.mjs +14 -62
  100. package/tools/plugin/package-plugins.mjs +2 -2
  101. package/tools/plugin/plugin-links.mjs +3 -0
  102. package/tools/skills/codex-skill-transform.mjs +232 -0
  103. package/tools/skills/deploy-skills-codex.mjs +8 -249
  104. package/tools/warp/warp-content.mjs +548 -0
@@ -1,848 +1,6 @@
1
- import { ceilingDecision } from '../gates/lattice.js';
2
- import { ContextBudgetManager } from '../metrics/context-budget.js';
3
- import { sha256 } from './compile-cache/identity.js';
4
- import { admitEntry } from './entry.js';
5
- import { PairedDifferenceError, pairedBinaryDifferenceInterval, pairedMeanDifferenceBootstrap, pairedNonInferiority, } from './qualification/quality.js';
6
- export const CONTEXT_PRUNING_PROTECTED_POLICY_VERSION = 'decision-context-protected/v1';
7
- export const CONTEXT_PRUNING_CANDIDATE_SCHEMA = 'decision-context-candidate/v1';
8
- export const CONTEXT_PRUNING_RECEIPT_SCHEMA = 'decision-context-pruning-receipt/v1';
9
- export const CONTEXT_PRUNING_PREREGISTRATION_SCHEMA = 'decision-context-pruning-preregistration/v1';
10
- export const CONTEXT_PRUNING_EVALUATION_REPORT_SCHEMA = 'decision-context-pruning-evaluation-report/v1';
11
- /**
12
- * Clock-skew allowance for `holdoutAccessedAt` attestations: the recorder that stamps holdout access and the
13
- * evaluator that builds the report may disagree by up to five minutes. An attestation later than the
14
- * evaluation clock plus this allowance is a future attestation and is rejected.
15
- */
16
- export const CONTEXT_PRUNING_HOLDOUT_CLOCK_SKEW_MS = 5 * 60 * 1_000;
17
- export const CONTEXT_PRUNING_QUALITY_METRICS = [
18
- 'downstream-task-success',
19
- 'requirement-coverage',
20
- 'factual-coverage',
21
- 'citation-accuracy',
22
- 'human-preference',
23
- ];
24
- export class ContextPruningError extends Error {
25
- reason;
26
- constructor(message, reason) {
27
- super(message);
28
- this.reason = reason;
29
- this.name = 'ContextPruningError';
30
- }
31
- }
32
- const SHA = /^sha256:[0-9a-f]{64}$/;
33
- const SOURCE_TO_REASON = {
34
- system: 'system-rule',
35
- developer: 'developer-rule',
36
- project: 'project-rule',
37
- 'security-policy': 'security-policy',
38
- user: 'current-user-requirement',
39
- approval: 'action-approval',
40
- blocker: 'unresolved-blocker',
41
- provenance: 'provenance-required',
42
- citation: 'citation-required',
43
- artifact: 'artifact-pin',
44
- 'test-evidence': 'test-gate-evidence',
45
- 'open-decision': 'open-decision-evidence',
46
- };
47
- const VALID_SOURCE_KINDS = new Set([
48
- 'system', 'developer', 'project', 'security-policy', 'user', 'approval', 'blocker',
49
- 'provenance', 'citation', 'artifact', 'test-evidence', 'open-decision', 'retrieved',
50
- 'memory', 'tool-output', 'ordinary',
51
- ]);
52
- const VALID_PROTECTED_REASONS = new Set([
53
- 'system-rule', 'developer-rule', 'project-rule', 'security-policy', 'current-user-requirement',
54
- 'explicit-mention', 'unresolved-blocker', 'action-approval', 'artifact-pin', 'version-pin',
55
- 'digest-pin', 'provenance-required', 'citation-required', 'test-gate-evidence',
56
- 'open-decision-evidence', 'protected-dependency', 'external-evaluation-denied', 'local-only',
57
- 'restricted-data', 'legal-policy',
58
- ]);
59
- export function contextPruningDigest(value) {
60
- return sha256(value);
61
- }
62
- /** Order-independent digest of the frozen evaluation pairs: sorted (pairId, slice) tuples. */
63
- export function contextPruningPairSetDigest(pairs) {
64
- const tuples = pairs.map(pair => [pair.pairId, pair.slice])
65
- .sort(([a, sa], [b, sb]) => a < b ? -1 : a > b ? 1 : sa < sb ? -1 : sa > sb ? 1 : 0);
66
- return contextPruningDigest({ schemaVersion: 'decision-context-pruning-pair-set/v1', pairs: tuples });
67
- }
68
- /** Identity of one pilot run over an ordered candidate set, optionally tied to an evaluation pair. */
69
- export function contextPruningRunId(pairId, candidates) {
70
- return contextPruningDigest({
71
- schemaVersion: 'decision-context-pruning-run-id/v1',
72
- pairId,
73
- candidates: candidates.map(candidate => contextPruningDigest(candidate)),
74
- });
75
- }
76
- /** Order-independent digest of a receipt set, for anchoring the evaluated receipts separately from the report. */
77
- export function contextPruningReceiptSetDigest(receipts) {
78
- return contextPruningDigest({
79
- schemaVersion: 'decision-context-pruning-receipt-set/v1',
80
- receipts: receipts.map(receipt => receipt.receiptDigest).sort(),
81
- });
82
- }
83
- export function classifyContextPruningCandidate(candidate) {
84
- validateContextPruningCandidate(candidate);
85
- const reasons = new Set();
86
- const mapped = SOURCE_TO_REASON[candidate.source.kind];
87
- if (mapped)
88
- reasons.add(mapped);
89
- for (const hint of candidate.protectedHints)
90
- reasons.add(hint);
91
- if (candidate.dataPolicy.externalEvaluation === 'denied')
92
- reasons.add('external-evaluation-denied');
93
- if (candidate.dataPolicy.localOnly)
94
- reasons.add('local-only');
95
- if (candidate.dataPolicy.legalAction === 'requires-review')
96
- reasons.add('legal-policy');
97
- if (candidate.sensitivity === 'restricted')
98
- reasons.add('restricted-data');
99
- const sorted = [...reasons].sort();
100
- const policy = {
101
- version: CONTEXT_PRUNING_PROTECTED_POLICY_VERSION,
102
- sourceRules: SOURCE_TO_REASON,
103
- dataPolicy: ['externalEvaluation', 'localOnly', 'legalAction'],
104
- sensitivity: ['restricted'],
105
- protectedHints: [...VALID_PROTECTED_REASONS].sort(),
106
- };
107
- return {
108
- schemaVersion: CONTEXT_PRUNING_PROTECTED_POLICY_VERSION,
109
- itemId: candidate.itemId,
110
- protected: sorted.length > 0,
111
- reasons: sorted,
112
- policyDigest: contextPruningDigest(policy),
113
- };
114
- }
115
- export function classifyContextPruningCandidates(candidates) {
116
- const byId = uniqueCandidates(candidates);
117
- const classifications = new Map();
118
- for (const candidate of candidates)
119
- classifications.set(candidate.itemId, classifyContextPruningCandidate(candidate));
120
- const protectedQueue = candidates.filter(candidate => classifications.get(candidate.itemId).protected)
121
- .map(candidate => candidate.itemId);
122
- for (let index = 0; index < protectedQueue.length; index++) {
123
- const item = byId.get(protectedQueue[index]);
124
- for (const dependencyId of item.dependencies) {
125
- const dependency = byId.get(dependencyId);
126
- if (!dependency)
127
- throw new ContextPruningError(`unknown context dependency '${dependencyId}'`, 'semantic');
128
- const current = classifications.get(dependencyId);
129
- if (current.reasons.includes('protected-dependency'))
130
- continue;
131
- classifications.set(dependencyId, {
132
- ...current,
133
- protected: true,
134
- reasons: [...new Set([...current.reasons, 'protected-dependency'])].sort(),
135
- });
136
- protectedQueue.push(dependencyId);
137
- }
138
- }
139
- return classifications;
140
- }
141
- export function planContextPruningEvaluations(candidates, questions) {
142
- return planContextPruningEvaluationRun(candidates, questions).jobs;
143
- }
144
- export function planContextPruningEvaluationRun(candidates, questions) {
145
- const byId = uniqueCandidates(candidates);
146
- const classifications = classifyContextPruningCandidates(candidates);
147
- const exclusions = [...classifications.values()]
148
- .filter(classification => classification.protected)
149
- .map(classification => ({ itemId: classification.itemId, reasons: [...classification.reasons].sort() }));
150
- const excluded = new Set(exclusions.map(item => item.itemId));
151
- const groups = new Map();
152
- for (const question of questions) {
153
- if (!question.id || !question.itemId || !question.subject || !['relevance', 'disposition', 'omission-risk'].includes(question.kind)) {
154
- throw new ContextPruningError('invalid context pruning question', 'schema');
155
- }
156
- const candidate = byId.get(question.itemId);
157
- if (!candidate)
158
- throw new ContextPruningError(`unknown context item '${question.itemId}'`, 'semantic');
159
- if (excluded.has(candidate.itemId))
160
- continue;
161
- const subject = pruningSubject(candidate);
162
- if (question.subject !== subject)
163
- throw new ContextPruningError('question subject must be the context item subject', 'semantic');
164
- const key = `${question.itemId}\0${question.batchKey ?? 'default'}`;
165
- const group = groups.get(key) ?? [];
166
- group.push(question);
167
- groups.set(key, group);
168
- }
169
- const jobs = [...groups.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, group]) => {
170
- const candidate = byId.get(group[0].itemId);
171
- const subject = pruningSubject(candidate);
172
- if (group.some(question => question.itemId !== candidate.itemId || question.subject !== subject)) {
173
- throw new ContextPruningError('unrelated context chunks cannot share a native batch', 'semantic');
174
- }
175
- return {
176
- subject,
177
- itemId: candidate.itemId,
178
- state: { candidateDigest: contextPruningDigest(candidate), itemId: candidate.itemId, locator: candidate.locator },
179
- questions: [...group].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
180
- contextQuestion: {
181
- id: `context-pruning:${candidate.itemId}:${group[0].batchKey ?? 'default'}`,
182
- subject,
183
- compatibilityKey: `context-pruning:${candidate.itemId}:${group[0].batchKey ?? 'default'}`,
184
- entry: { candidateDigest: contextPruningDigest(candidate), questions: group.map(question => question.kind).sort() },
185
- },
186
- };
187
- });
188
- return { jobs, exclusions };
189
- }
190
- export function applyContextPruningPilot(input) {
191
- validatePolicy(input.policy);
192
- if (input.pairId !== undefined && (typeof input.pairId !== 'string' || !input.pairId)) {
193
- throw new ContextPruningError('pairId must be a non-empty string', 'invalid-input');
194
- }
195
- const pairId = input.pairId ?? null;
196
- const now = input.now ?? (() => new Date().toISOString());
197
- const baseline = input.candidates.map(candidate => candidate.itemId);
198
- const evidence = new Map((input.evidence ?? []).map(item => [item.itemId, item]));
199
- const disabledReason = input.monitoringRegression ? 'drift-or-monitoring-regression'
200
- : input.policy.mode === 'disabled' ? 'configured-disabled' : null;
201
- const mode = disabledReason ? 'deterministic-fallback' : input.policy.mode;
202
- const classifications = classifyContextPruningCandidates(input.candidates);
203
- const runId = contextPruningRunId(pairId, input.candidates);
204
- const deterministicBaseline = input.budget === undefined ? null
205
- : computeContextBudgetManagerBaseline(input.candidates, input.budget);
206
- const deterministicDrops = new Set(deterministicBaseline?.droppedItemIds ?? []);
207
- const receipts = input.candidates.map(candidate => {
208
- validateContextPruningCandidate(candidate);
209
- const classification = classifications.get(candidate.itemId);
210
- const itemEvidence = evidence.get(candidate.itemId);
211
- const fallbackAction = deterministicDrops.has(candidate.itemId) ? 'drop' : 'keep';
212
- const decision = decideContextAction(candidate, classification, input.policy, itemEvidence, disabledReason, fallbackAction);
213
- return buildContextPruningReceipt(candidate, classification, decision, now(), runId, pairId);
214
- });
215
- return {
216
- schemaVersion: 'decision-context-pruning-run/v1',
217
- runId,
218
- pairId,
219
- mode,
220
- baselineItemIds: baseline,
221
- // A distinct array: callers that mutate one list cannot silently alter the other.
222
- downstreamItemIds: [...baseline],
223
- receipts,
224
- disabledReason,
225
- deterministicBaseline,
226
- };
227
- }
228
- /**
229
- * Validates a receipt's shape and self-digest. When the run's candidate envelopes are supplied, it also
230
- * re-derives the run identity and the protected-item classification and refuses any mismatch, so a
231
- * relabelled receipt with a recomputed digest, or a receipt from another run, is rejected.
232
- */
233
- export function validateContextPruningReceipt(receipt, candidates) {
234
- requirePlain(receipt, 'receipt');
235
- if (receipt.schemaVersion !== CONTEXT_PRUNING_RECEIPT_SCHEMA || !receipt.itemId || !receipt.locator
236
- || typeof receipt.runId !== 'string' || !SHA.test(receipt.runId)
237
- || !(receipt.pairId === null || (typeof receipt.pairId === 'string' && receipt.pairId))
238
- || !SHA.test(receipt.originalDigest) || !Number.isSafeInteger(receipt.originalTokenEstimate) || receipt.originalTokenEstimate < 0
239
- || !['keep', 'drop', 'truncate', 'summarize'].includes(receipt.proposedAction)
240
- || !['keep', 'drop', 'truncate', 'summarize'].includes(receipt.appliedAction)
241
- || !(receipt.decisionReceiptDigest === null || SHA.test(receipt.decisionReceiptDigest))
242
- || !receipt.reversibleReference || receipt.reversibleReference.originalDigest !== receipt.originalDigest
243
- || !receipt.reversibleReference.locator || !receipt.reversibleReference.restorationPath
244
- || !SHA.test(receipt.receiptDigest)) {
245
- throw new ContextPruningError('invalid pruning receipt', 'schema');
246
- }
247
- if ((receipt.proposedAction === 'truncate' || receipt.proposedAction === 'summarize')
248
- && receipt.reason === 'accepted-evidence' && receipt.reversibleReference.transformation === null) {
249
- throw new ContextPruningError('transformed receipts require a reversible artifact reference', 'semantic');
250
- }
251
- if (receipt.reversibleReference.transformation !== null
252
- && receipt.reversibleReference.transformation.sourceDigest !== receipt.originalDigest) {
253
- throw new ContextPruningError('transformation source digest must match the original context item', 'semantic');
254
- }
255
- const { receiptDigest, ...payload } = receipt;
256
- if (receiptDigest !== contextPruningDigest(payload))
257
- throw new ContextPruningError('pruning receipt digest mismatch', 'semantic');
258
- if (candidates !== undefined) {
259
- const candidate = candidates.find(item => item.itemId === receipt.itemId);
260
- if (!candidate || receipt.runId !== contextPruningRunId(receipt.pairId, candidates)
261
- || receipt.originalDigest !== candidate.contentDigest || receipt.locator !== candidate.locator
262
- || receipt.originalTokenEstimate !== candidate.tokenEstimate) {
263
- throw new ContextPruningError('pruning receipt is not bound to the evaluated run', 'semantic');
264
- }
265
- const derived = classifyContextPruningCandidates(candidates).get(candidate.itemId);
266
- if (contextPruningDigest(derived) !== contextPruningDigest(receipt.classification)) {
267
- throw new ContextPruningError('pruning receipt classification does not match the candidate envelope', 'semantic');
268
- }
269
- // A protected item is never proposed for, or subjected to, a destructive action by this pilot.
270
- if (derived.protected && (receipt.proposedAction !== 'keep' || receipt.appliedAction !== 'keep')) {
271
- throw new ContextPruningError('pruning receipt classification does not match its protected action', 'semantic');
272
- }
273
- }
274
- return receipt;
275
- }
276
- export function createContextPruningPreregistration(input) {
277
- const payload = { schemaVersion: CONTEXT_PRUNING_PREREGISTRATION_SCHEMA, ...input };
278
- return validateContextPruningPreregistration({ ...payload, digest: contextPruningDigest(payload) });
279
- }
280
- export function validateContextPruningPreregistration(value) {
281
- requirePlain(value, 'preregistration');
282
- const t = value.thresholds;
283
- const ci = t?.confidenceInterval;
284
- const metrics = Array.isArray(t?.qualityMetrics) ? t.qualityMetrics : [];
285
- const slices = Array.isArray(t?.slices) ? t.slices : [];
286
- const bootstrapTail = ci && Number.isSafeInteger(ci.bootstrapResamples) && Number.isSafeInteger(ci.levelBps)
287
- ? Math.floor(ci.bootstrapResamples * (10_000 - ci.levelBps) / 20_000) : 0;
288
- if (value.schemaVersion !== CONTEXT_PRUNING_PREREGISTRATION_SCHEMA || !value.id
289
- || !Number.isFinite(Date.parse(value.registeredAt))
290
- || typeof value.pairSetDigest !== 'string' || !SHA.test(value.pairSetDigest)
291
- || !t || t.protectedRetentionBps !== 10_000 || !ci
292
- // pairedBinaryDifferenceInterval accepts only levels strictly between 5000 and 9999.
293
- || !Number.isSafeInteger(ci.levelBps) || ci.levelBps <= 5_000 || ci.levelBps >= 9_999
294
- || !['newcombe-10', 'tango'].includes(ci.binaryMethod) || ci.boundedMethod !== 'percentile-bootstrap'
295
- || !Number.isSafeInteger(ci.bootstrapSeed) || ci.bootstrapSeed < 0 || ci.bootstrapSeed > 0xffff_ffff
296
- || !Number.isSafeInteger(ci.bootstrapResamples) || ci.bootstrapResamples > 1_000_000 || bootstrapTail < 5
297
- || metrics.length !== CONTEXT_PRUNING_QUALITY_METRICS.length
298
- || new Set(metrics.map(item => item?.metric)).size !== metrics.length
299
- || metrics.some(item => !CONTEXT_PRUNING_QUALITY_METRICS.includes(item?.metric) || !['binary', 'bounded'].includes(item.scale))
300
- || slices.length === 0 || new Set(slices).size !== slices.length
301
- || slices.some(slice => typeof slice !== 'string' || !slice.trim())
302
- || !Number.isSafeInteger(t.minimumOverallN) || t.minimumOverallN < 2
303
- || !Number.isSafeInteger(t.minimumSliceN) || t.minimumSliceN < 1
304
- || !Number.isSafeInteger(t.minimumZeroVarianceN) || t.minimumZeroVarianceN < 2
305
- || !Number.isSafeInteger(t.minimumProtectedN) || t.minimumProtectedN < 2
306
- || (t.powerRule !== null && (typeof t.powerRule !== 'string' || !t.powerRule.trim()))
307
- || !Number.isSafeInteger(t.qualityNonInferiorityMarginBps) || t.qualityNonInferiorityMarginBps > 0
308
- || t.qualityNonInferiorityMarginBps < -10_000
309
- || !Number.isSafeInteger(t.positiveTotalTokenTarget) || t.positiveTotalTokenTarget <= 0
310
- || !Number.isFinite(t.positiveTotalCostTargetUsd) || t.positiveTotalCostTargetUsd <= 0) {
311
- throw new ContextPruningError('invalid context pruning preregistration', 'schema');
312
- }
313
- const { digest, ...payload } = value;
314
- if (digest !== contextPruningDigest(payload))
315
- throw new ContextPruningError('preregistration digest mismatch', 'semantic');
316
- return value;
317
- }
318
- /**
319
- * Builds the paired evaluation report. `trustedPreregistrationDigest` must come from a separately anchored
320
- * record made before holdout access (as evaluatePreregisteredBinaryBenchmark requires): a caller-created
321
- * preregistration cannot attest itself. A report without a recorded holdout access time cannot PROMOTE.
322
- * A holdout access attested later than the evaluation clock plus CONTEXT_PRUNING_HOLDOUT_CLOCK_SKEW_MS
323
- * is rejected as a future attestation.
324
- */
325
- export function buildContextPruningEvaluationReport(input) {
326
- const preregistration = validateContextPruningPreregistration(input.preregistration);
327
- if (typeof input.trustedPreregistrationDigest !== 'string' || !SHA.test(input.trustedPreregistrationDigest)
328
- || preregistration.digest !== input.trustedPreregistrationDigest) {
329
- throw new ContextPruningError('preregistration is not anchored to the trusted digest', 'semantic');
330
- }
331
- const holdoutAccessedAt = input.holdoutAccessedAt;
332
- const holdoutAtMs = holdoutAccessedAt === null ? NaN : Date.parse(holdoutAccessedAt);
333
- if (holdoutAccessedAt !== null && (typeof holdoutAccessedAt !== 'string' || !Number.isFinite(holdoutAtMs)
334
- || holdoutAtMs <= Date.parse(preregistration.registeredAt))) {
335
- throw new ContextPruningError('holdout access must be recorded after preregistration', 'semantic');
336
- }
337
- if (Number.isFinite(holdoutAtMs)) {
338
- const evaluationNowMs = (input.evaluationNow ?? Date.now)();
339
- // Fail closed: an unknown evaluation time cannot vouch for the attestation.
340
- if (!Number.isFinite(evaluationNowMs) || holdoutAtMs - evaluationNowMs > CONTEXT_PRUNING_HOLDOUT_CLOCK_SKEW_MS) {
341
- throw new ContextPruningError('future holdout access attestation is rejected', 'semantic');
342
- }
343
- }
344
- validateIntegrity(input.integrity);
345
- const thresholds = preregistration.thresholds;
346
- validateMetrics(input.metrics, preregistration);
347
- const metrics = input.metrics;
348
- if (contextPruningPairSetDigest(metrics.pairs) !== preregistration.pairSetDigest) {
349
- throw new ContextPruningError('evaluated pair set does not match the preregistered pair set', 'semantic');
350
- }
351
- const findings = new Set();
352
- const missing = new Set(input.missingInputs ?? []);
353
- if (holdoutAccessedAt === null)
354
- findings.add('holdout-access-unrecorded');
355
- const sliceSupport = Object.fromEntries(thresholds.slices.map(slice => [slice, 0]));
356
- for (const pair of metrics.pairs)
357
- sliceSupport[pair.slice] += 1;
358
- if (metrics.pairs.length < thresholds.minimumOverallN)
359
- findings.add('insufficient-overall-sample');
360
- for (const slice of thresholds.slices) {
361
- if (sliceSupport[slice] < thresholds.minimumSliceN)
362
- findings.add(`insufficient-slice:${slice}`);
363
- }
364
- const protectedRetention = deriveProtectedRetention(input.pruningRuns, metrics.pairs, input.trustedReceiptSetDigest);
365
- if (protectedRetention.bps === null)
366
- findings.add('insufficient-protected-receipts');
367
- else if (protectedRetention.bps !== metrics.protectedRetentionBps) {
368
- throw new ContextPruningError('protected retention does not reconcile with the pruning receipts', 'semantic');
369
- }
370
- if (metrics.protectedRetentionBps < 10_000 || (protectedRetention.bps !== null && protectedRetention.bps < 10_000)) {
371
- findings.add('protected-retention-breach');
372
- }
373
- // A full retention rate on too few protected items is not evidence: the count comes from validated receipts.
374
- if (protectedRetention.protectedItems < thresholds.minimumProtectedN)
375
- findings.add('insufficient-protected-sample');
376
- const quality = thresholds.qualityMetrics.map(({ metric, scale }) => evaluateQualityMetric(metric, scale, metrics.quality.find(item => item.metric === metric), metrics.pairs, preregistration));
377
- for (const result of quality) {
378
- for (const slice of thresholds.slices) {
379
- if (result.sliceSupport[slice] < thresholds.minimumSliceN)
380
- findings.add(`insufficient-quality-slice:${result.metric}:${slice}`);
381
- }
382
- if (result.missingPairs > 0)
383
- findings.add(`quality-outcomes-incomplete:${result.metric}`);
384
- if (result.decision === 'not-non-inferior') {
385
- findings.add('quality-non-inferiority-failed');
386
- findings.add(`quality-non-inferiority-failed:${result.metric}`);
387
- if (result.harm) {
388
- findings.add('quality-harm');
389
- findings.add(`quality-harm:${result.metric}`);
390
- }
391
- else {
392
- findings.add(`quality-non-inferiority-inconclusive:${result.metric}`);
393
- }
394
- }
395
- else if (result.decision === 'insufficient' && result.n === 0) {
396
- findings.add(`quality-metric-missing:${result.metric}`);
397
- }
398
- else if (result.decision === 'insufficient' && result.n < thresholds.minimumOverallN) {
399
- findings.add(`insufficient-quality-sample:${result.metric}`);
400
- }
401
- else if (result.decision === 'insufficient' && result.missingPairs === 0 && result.scale === 'bounded'
402
- && result.interval !== null && result.interval.lowerBps === result.interval.upperBps
403
- && result.n < thresholds.minimumZeroVarianceN) {
404
- // A conclusive-sized read withheld for lack of variability evidence: a zero-width bounded
405
- // interval below the preregistered zero-variance support.
406
- findings.add(`insufficient-quality-support:${result.metric}`);
407
- }
408
- else if (result.decision === 'insufficient') {
409
- // Interval construction failed, the verdict was unreadable, or a passing
410
- // verdict was withheld for omitted pairs: adequate n is not evidence.
411
- findings.add(`insufficient-quality-evidence:${result.metric}`);
412
- }
413
- }
414
- const providerSavings = providerUsageSavings(metrics.providerUsage);
415
- const estimatorSavings = { totalTokens: totalSavings(metrics.estimatorUsage, 'total') };
416
- if (providerSavings.totalTokens < 0 || providerSavings.uncachedTokens < 0
417
- || (providerSavings.costUsd !== null && providerSavings.costUsd < 0)) {
418
- findings.add('negative-net-economics');
419
- }
420
- if (providerSavings.totalTokens < thresholds.positiveTotalTokenTarget
421
- || providerSavings.uncachedTokens < thresholds.positiveTotalTokenTarget)
422
- findings.add('provider-token-target-not-met');
423
- if (estimatorSavings.totalTokens < thresholds.positiveTotalTokenTarget)
424
- findings.add('estimator-token-target-not-met');
425
- if (providerSavings.costUsd === null)
426
- findings.add('provider-cost-unknown');
427
- else if (providerSavings.costUsd < thresholds.positiveTotalCostTargetUsd)
428
- findings.add('provider-cost-target-not-met');
429
- if (input.integrity.integrity_state !== 'verified')
430
- findings.add('integrity-not-verified');
431
- const upstreamDecision = input.integrity.release_gate.decision;
432
- if (upstreamDecision === 'ROLLBACK')
433
- findings.add('upstream-rollback');
434
- if (upstreamDecision === 'HOLD')
435
- findings.add('upstream-hold');
436
- for (const name of missing)
437
- findings.add(`missing-input:${name}`);
438
- // Automatic rollback triggers from the D26 rollout plan: protected miss, demonstrated quality harm, negative
439
- // economics. An inconclusive non-inferiority result (no evidence of harm) holds instead.
440
- const rollback = findings.has('protected-retention-breach')
441
- || findings.has('quality-harm') || findings.has('negative-net-economics');
442
- const decision = ceilingDecision(upstreamDecision, rollback ? 'ROLLBACK' : findings.size > 0 ? 'HOLD' : 'PROMOTE');
443
- const advisory = [...findings].some(item => item.startsWith('insufficient-') || item.startsWith('quality-metric-missing:')
444
- || item.startsWith('missing-input:') || item.startsWith('quality-outcomes-incomplete:')
445
- || item.startsWith('quality-non-inferiority-inconclusive:')
446
- || item === 'holdout-access-unrecorded' || item === 'provider-cost-unknown')
447
- ? 'INSUFFICIENT EVIDENCE' : null;
448
- const payload = {
449
- schemaVersion: CONTEXT_PRUNING_EVALUATION_REPORT_SCHEMA,
450
- preregistration,
451
- holdoutAccessedAt,
452
- integrity: input.integrity,
453
- metrics,
454
- derived: { sampleN: metrics.pairs.length, sliceSupport, quality, providerSavings, estimatorSavings, protectedRetention },
455
- missingInputs: [...missing].sort(),
456
- findings: [...findings].sort(),
457
- upstreamDecision,
458
- decision,
459
- advisory,
460
- };
461
- return { ...payload, digest: contextPruningDigest(payload) };
462
- }
463
- function evaluateQualityMetric(metric, scale, outcomes, recordedPairs, preregistration) {
464
- const { confidenceInterval: ci, minimumOverallN, minimumZeroVarianceN, qualityNonInferiorityMarginBps, slices } = preregistration.thresholds;
465
- const pairs = outcomes?.pairs ?? [];
466
- const sliceOf = new Map(recordedPairs.map(pair => [pair.pairId, pair.slice]));
467
- const sliceSupport = Object.fromEntries(slices.map(slice => [slice, 0]));
468
- for (const pair of pairs)
469
- sliceSupport[sliceOf.get(pair.pairId)] += 1;
470
- // validateMetrics guarantees outcome pair IDs are a unique subset of the recorded pairs.
471
- const missingPairs = recordedPairs.length - pairs.length;
472
- const result = (interval, decision) => ({
473
- metric, scale, n: pairs.length, missingPairs,
474
- harm: decision === 'not-non-inferior' && interval !== null
475
- && (interval.upperBps < 0 || interval.estimateBps < qualityNonInferiorityMarginBps),
476
- sliceSupport, interval, decision,
477
- });
478
- if (pairs.length < minimumOverallN)
479
- return result(null, 'insufficient');
480
- let interval;
481
- try {
482
- if (scale === 'binary') {
483
- const counts = { both: 0, candidateOnly: 0, baselineOnly: 0, neither: 0 };
484
- for (const pair of pairs) {
485
- if (pair.candidate === 1 && pair.baseline === 1)
486
- counts.both++;
487
- else if (pair.candidate === 1)
488
- counts.candidateOnly++;
489
- else if (pair.baseline === 1)
490
- counts.baselineOnly++;
491
- else
492
- counts.neither++;
493
- }
494
- interval = pairedBinaryDifferenceInterval({ counts, levelBps: ci.levelBps, method: ci.binaryMethod });
495
- }
496
- else {
497
- interval = pairedMeanDifferenceBootstrap({
498
- differences: pairs.map(pair => pair.candidate - pair.baseline), levelBps: ci.levelBps,
499
- seed: ci.bootstrapSeed, resamples: ci.bootstrapResamples, bounds: [-1, 1],
500
- });
501
- }
502
- }
503
- catch (error) {
504
- if (error instanceof PairedDifferenceError)
505
- return result(null, 'insufficient');
506
- throw error;
507
- }
508
- const verdict = pairedNonInferiority({ interval, marginBps: qualityNonInferiorityMarginBps });
509
- // A regression visible in the reported outcomes still fails; omitted pairs can only withhold a pass.
510
- if (verdict.decision === 'non-inferior' && missingPairs > 0)
511
- return result(interval, 'insufficient');
512
- // A zero-width bounded interval carries no variability evidence: identical pairs at a small n are
513
- // inconclusive, so a would-be pass needs the preregistered zero-variance support first. Only passes
514
- // are withheld here; demonstrated harm still rolls back through the verdict below.
515
- if (verdict.decision === 'non-inferior' && scale === 'bounded'
516
- && interval.lowerBps === interval.upperBps && pairs.length < minimumZeroVarianceN) {
517
- return result(interval, 'insufficient');
518
- }
519
- return result(interval, verdict.decision);
520
- }
521
- function deriveProtectedRetention(runs, pairs, trustedReceiptSetDigest) {
522
- const pairIds = new Set(pairs.map(pair => pair.pairId));
523
- if (!Array.isArray(runs) || runs.length !== pairIds.size || new Set(runs.map(run => run?.pairId)).size !== runs.length
524
- || runs.some(run => !run || !pairIds.has(run.pairId) || !Array.isArray(run.candidates) || !Array.isArray(run.receipts))) {
525
- throw new ContextPruningError('pruning runs must cover every evaluated pair exactly once', 'invalid-input');
526
- }
527
- const allReceipts = runs.flatMap(run => run.receipts);
528
- if (typeof trustedReceiptSetDigest !== 'string' || !SHA.test(trustedReceiptSetDigest)
529
- || contextPruningReceiptSetDigest(allReceipts) !== trustedReceiptSetDigest) {
530
- throw new ContextPruningError('evaluated receipt set does not match the trusted receipt-set digest', 'semantic');
531
- }
532
- let protectedItems = 0;
533
- let retained = 0;
534
- for (const run of runs) {
535
- uniqueCandidates(run.candidates);
536
- const itemIds = run.receipts.map((receipt) => receipt?.itemId);
537
- if (new Set(itemIds).size !== itemIds.length || itemIds.length !== run.candidates.length) {
538
- throw new ContextPruningError('pruning receipts are not bound to the evaluated run candidates', 'semantic');
539
- }
540
- for (const receipt of run.receipts) {
541
- if (receipt?.pairId !== run.pairId)
542
- throw new ContextPruningError('pruning receipt is not bound to the evaluated run', 'semantic');
543
- validateContextPruningReceipt(receipt, run.candidates);
544
- if (!receipt.classification.protected)
545
- continue;
546
- protectedItems++;
547
- if (receipt.proposedAction === 'keep' && receipt.appliedAction === 'keep')
548
- retained++;
549
- }
550
- }
551
- return { protectedItems, retained, bps: protectedItems === 0 ? null : Math.floor(retained * 10_000 / protectedItems) };
552
- }
553
- function pruningSubject(candidate) {
554
- return `context-item:${candidate.itemId}`;
555
- }
556
- function decideContextAction(candidate, classification, policy, evidence, disabledReason, fallbackAction) {
557
- if (classification.protected)
558
- return { proposedAction: 'keep', appliedAction: 'keep',
559
- mode: disabledReason ? 'deterministic-fallback' : policy.mode,
560
- reason: 'protected-item', decisionReceiptDigest: null, transformation: null };
561
- const fallback = (reason) => deterministicFallback(fallbackAction, reason);
562
- if (disabledReason)
563
- return fallback(disabledReason === 'configured-disabled' ? 'disabled' : 'drift-or-monitoring-regression');
564
- if (policy.mode === 'disabled')
565
- return fallback('disabled');
566
- if (!evidence || evidence.itemId !== candidate.itemId || evidence.subject !== pruningSubject(candidate))
567
- return fallback('invalid-evidence');
568
- if (evidence.status === 'cancelled')
569
- return fallback('cancelled');
570
- if (evidence.status === 'incomplete')
571
- return fallback('incomplete-state');
572
- if (evidence.status === 'uncalibrated')
573
- return fallback('uncalibrated');
574
- if (evidence.status === 'drifted')
575
- return fallback('drift-or-monitoring-regression');
576
- if (evidence.status === 'failed')
577
- return fallback('evaluation-failed');
578
- if (policy.modelIdentityDigest === null || policy.calibrationDigest === null
579
- || evidence.modelIdentityDigest === undefined || evidence.calibrationDigest === undefined
580
- || evidence.modelIdentityDigest !== policy.modelIdentityDigest || evidence.calibrationDigest !== policy.calibrationDigest) {
581
- return fallback('drift-or-monitoring-regression');
582
- }
583
- const confidenceBps = evidence.confidenceBps;
584
- const marginBps = evidence.marginBps;
585
- if (evidence.status !== 'success' || evidence.disagreement || evidence.proposedAction === undefined
586
- || typeof confidenceBps !== 'number' || typeof marginBps !== 'number'
587
- || !Number.isSafeInteger(confidenceBps) || !Number.isSafeInteger(marginBps)
588
- || confidenceBps < policy.minimumConfidenceBps || marginBps < policy.minimumMarginBps
589
- || evidence.calibrated !== true || !evidence.decisionReceiptDigest || !SHA.test(evidence.decisionReceiptDigest)) {
590
- return fallback(evidence.status === 'uncertain' ? 'uncertain-evidence' : 'invalid-evidence');
591
- }
592
- const proposed = evidence.proposedAction;
593
- if (!policy.allowedDestructiveActions.includes(proposed) && proposed !== 'keep')
594
- return fallback('policy-denied-action');
595
- if ((proposed === 'truncate' || proposed === 'summarize') && !validTransformation(evidence.transformation, proposed, candidate.contentDigest)) {
596
- return fallback('unsupported-transformation');
597
- }
598
- return {
599
- proposedAction: proposed,
600
- appliedAction: 'keep',
601
- mode: policy.mode,
602
- reason: policy.mode === 'shadow' && proposed !== 'keep' ? 'shadow-only' : 'accepted-evidence',
603
- decisionReceiptDigest: evidence.decisionReceiptDigest,
604
- transformation: evidence.transformation ?? null,
605
- };
606
- }
607
- function deterministicFallback(action, reason) {
608
- return {
609
- proposedAction: action,
610
- appliedAction: 'keep',
611
- mode: 'deterministic-fallback',
612
- reason: reason === 'disabled' ? 'disabled'
613
- : ['invalid-evidence', 'uncertain-evidence', 'uncalibrated', 'incomplete-state', 'cancelled', 'evaluation-failed',
614
- 'drift-or-monitoring-regression', 'unsupported-transformation', 'policy-denied-action'].includes(reason)
615
- ? reason : 'prior-deterministic-fallback',
616
- decisionReceiptDigest: null,
617
- transformation: null,
618
- };
619
- }
620
- function buildContextPruningReceipt(candidate, classification, decision, createdAt, runId, pairId) {
621
- const transformation = decision.transformation ?? null;
622
- const payload = {
623
- schemaVersion: CONTEXT_PRUNING_RECEIPT_SCHEMA,
624
- runId,
625
- pairId,
626
- itemId: candidate.itemId,
627
- locator: candidate.locator,
628
- originalDigest: candidate.contentDigest,
629
- originalTokenEstimate: candidate.tokenEstimate,
630
- classification,
631
- proposedAction: decision.proposedAction,
632
- appliedAction: decision.appliedAction,
633
- mode: decision.mode,
634
- reason: decision.reason,
635
- decisionReceiptDigest: decision.decisionReceiptDigest,
636
- reversibleReference: {
637
- locator: candidate.locator,
638
- originalDigest: candidate.contentDigest,
639
- restorationPath: candidate.locator,
640
- transformation,
641
- },
642
- createdAt,
643
- };
644
- return validateContextPruningReceipt({ ...payload, receiptDigest: contextPruningDigest(payload) });
645
- }
646
- function validTransformation(value, action, sourceDigest) {
647
- return Boolean(value && value.action === action && value.qualityCheck === 'passed'
648
- && value.sourceDigest === sourceDigest && value.locator && SHA.test(value.digest));
649
- }
650
- export function computeContextBudgetManagerBaseline(candidates, config) {
651
- const manager = new ContextBudgetManager(process.cwd(), config);
652
- for (const candidate of candidates) {
653
- validateContextPruningCandidate(candidate);
654
- // ContextBudgetManager sizes item text itself; sizing the digest string would understate real content.
655
- if (candidate.content === undefined) {
656
- throw new ContextPruningError(`ContextBudgetManager baseline requires host-owned content for '${candidate.itemId}'`, 'invalid-input');
657
- }
658
- // The envelope priority is passed as ContextBudgetManager similarity; the manager derives its own priority.
659
- manager.addItem(candidate.itemId, candidate.content, sourceTypeForBudget(candidate), candidate.priority);
660
- }
661
- const result = manager.degrade();
662
- // ContextBudgetManager spares only source type 'system'; protected (and dependency-protected) items are
663
- // retained here so the drop list can be applied as the fallback without removing protected context.
664
- const classifications = classifyContextPruningCandidates(candidates);
665
- const isProtected = (id) => classifications.get(id).protected;
666
- const byId = new Map([...result.kept, ...result.dropped].map(item => [item.id, item]));
667
- const droppedIds = new Set(result.dropped.filter(item => !isProtected(item.id)).map(item => item.id));
668
- // Re-adding protected items can exceed the manager's target, so continue its own rule (ascending priority,
669
- // never system items) over the remaining unprotected items until the target is met or none remain.
670
- const target = Math.floor(manager.contextBudget * manager.getConfig().warningThreshold);
671
- let current = candidates.reduce((sum, candidate) => sum + (droppedIds.has(candidate.itemId) ? 0 : byId.get(candidate.itemId).tokens), 0);
672
- const remaining = candidates.map(candidate => byId.get(candidate.itemId))
673
- .filter(item => !droppedIds.has(item.id) && !isProtected(item.id) && item.source.type !== 'system')
674
- .sort((a, b) => a.priority - b.priority);
675
- for (const item of remaining) {
676
- if (current <= target)
677
- break;
678
- droppedIds.add(item.id);
679
- current -= item.tokens;
680
- }
681
- const kept = candidates.map(candidate => byId.get(candidate.itemId)).filter(item => !droppedIds.has(item.id));
682
- const dropped = candidates.map(candidate => byId.get(candidate.itemId)).filter(item => droppedIds.has(item.id));
683
- return {
684
- source: 'ContextBudgetManager',
685
- usage: {
686
- inputTokens: kept.reduce((sum, item) => sum + item.tokens, 0),
687
- cachedInputTokens: null,
688
- outputTokens: 0,
689
- costUsd: null,
690
- },
691
- keptItemIds: kept.map(item => item.id).sort(),
692
- droppedItemIds: dropped.map(item => item.id).sort(),
693
- protectedRetainedItemIds: result.dropped.filter(item => isProtected(item.id)).map(item => item.id).sort(),
694
- tokensFreed: dropped.reduce((sum, item) => sum + item.tokens, 0),
695
- withinBudget: current <= target,
696
- };
697
- }
698
- function validateContextPruningCandidate(candidate) {
699
- requirePlain(candidate, 'candidate');
700
- if (candidate.schemaVersion !== CONTEXT_PRUNING_CANDIDATE_SCHEMA || !candidate.itemId || !candidate.locator
701
- || !SHA.test(candidate.contentDigest) || !candidate.source || !VALID_SOURCE_KINDS.has(candidate.source.kind) || !candidate.source.addedAt
702
- || !Number.isFinite(Date.parse(candidate.source.addedAt))
703
- || (candidate.content !== undefined && contextPruningDigest(candidate.content) !== candidate.contentDigest)
704
- || !Number.isSafeInteger(candidate.tokenEstimate) || candidate.tokenEstimate < 0
705
- || !Number.isFinite(candidate.priority) || candidate.priority < 0 || candidate.priority > 1
706
- || !['verified', 'untrusted'].includes(candidate.trust)
707
- || !['public', 'internal', 'confidential', 'restricted'].includes(candidate.sensitivity)
708
- || !Array.isArray(candidate.dependencies) || new Set(candidate.dependencies).size !== candidate.dependencies.length
709
- || candidate.dependencies.some(value => typeof value !== 'string' || !value)
710
- || !Array.isArray(candidate.protectedHints) || new Set(candidate.protectedHints).size !== candidate.protectedHints.length
711
- || candidate.protectedHints.some(reason => !VALID_PROTECTED_REASONS.has(reason))
712
- || !candidate.taskSubject || !candidate.dataPolicy
713
- || !['allowed', 'denied'].includes(candidate.dataPolicy.externalEvaluation)
714
- || typeof candidate.dataPolicy.localOnly !== 'boolean'
715
- || !['none', 'requires-review'].includes(candidate.dataPolicy.legalAction)) {
716
- throw new ContextPruningError('invalid context candidate', 'schema');
717
- }
718
- try {
719
- admitEntry(candidate);
720
- }
721
- catch {
722
- throw new ContextPruningError('context candidate failed admission', 'schema');
723
- }
724
- }
725
- function validatePolicy(policy) {
726
- if (!['disabled', 'shadow', 'advisory'].includes(policy.mode)
727
- || !Number.isSafeInteger(policy.minimumConfidenceBps) || policy.minimumConfidenceBps < 0 || policy.minimumConfidenceBps > 10_000
728
- || !Number.isSafeInteger(policy.minimumMarginBps) || policy.minimumMarginBps < 0 || policy.minimumMarginBps > 10_000
729
- || !Array.isArray(policy.allowedDestructiveActions)
730
- || policy.allowedDestructiveActions.some(action => !['keep', 'drop', 'truncate', 'summarize'].includes(action))
731
- || (policy.calibrationDigest !== null && !SHA.test(policy.calibrationDigest))
732
- || (policy.modelIdentityDigest !== null && !SHA.test(policy.modelIdentityDigest))) {
733
- throw new ContextPruningError('invalid context pruning policy', 'schema');
734
- }
735
- }
736
- function validateIntegrity(integrity) {
737
- if (!integrity || typeof integrity !== 'object' || !integrity.release_gate
738
- || !['PROMOTE', 'HOLD', 'ROLLBACK'].includes(integrity.release_gate.decision)
739
- || typeof integrity.integrity_state !== 'string') {
740
- throw new ContextPruningError('invalid eval-integrity metadata', 'schema');
741
- }
742
- }
743
- const isCount = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
744
- function validateMetrics(metrics, preregistration) {
745
- requirePlain(metrics, 'metrics');
746
- const slices = new Set(preregistration.thresholds.slices);
747
- const pairs = Array.isArray(metrics.pairs) ? metrics.pairs : null;
748
- const pairIds = new Set(pairs?.map(pair => pair?.pairId));
749
- if (!pairs || pairIds.size !== pairs.length
750
- || pairs.some(pair => !pair || typeof pair.pairId !== 'string' || !pair.pairId || !slices.has(pair.slice))) {
751
- throw new ContextPruningError('pair records must have unique IDs and preregistered slices', 'schema');
752
- }
753
- const scales = new Map(preregistration.thresholds.qualityMetrics.map(item => [item.metric, item.scale]));
754
- const quality = Array.isArray(metrics.quality) ? metrics.quality : null;
755
- if (!quality || new Set(quality.map(item => item?.metric)).size !== quality.length
756
- || quality.some(item => !item || !scales.has(item.metric) || !Array.isArray(item.pairs))) {
757
- throw new ContextPruningError('quality outcomes must name each preregistered metric at most once', 'schema');
758
- }
759
- for (const item of quality) {
760
- const scale = scales.get(item.metric);
761
- const seen = new Set();
762
- for (const pair of item.pairs) {
763
- const inRange = (value) => typeof value === 'number' && Number.isFinite(value)
764
- && (scale === 'binary' ? value === 0 || value === 1 : value >= 0 && value <= 1);
765
- if (!pair || !pairIds.has(pair.pairId) || seen.has(pair.pairId) || !inRange(pair.baseline) || !inRange(pair.candidate)) {
766
- throw new ContextPruningError(`quality outcome for '${item.metric}' is out of range or not reconciled with the pair records`, 'schema');
767
- }
768
- seen.add(pair.pairId);
769
- }
770
- }
771
- if (!isCount(metrics.protectedRetentionBps) || metrics.protectedRetentionBps > 10_000
772
- || metrics.sharedStateAccounting !== 'not-applicable'
773
- || !usageAccounting(metrics.providerUsage, 'provider') || !usageAccounting(metrics.estimatorUsage, 'estimator')
774
- || !isCount(metrics.totalCalls) || !metrics.latencyMs
775
- || [metrics.latencyMs.p50, metrics.latencyMs.p95, metrics.latencyMs.p99]
776
- .some(value => value !== null && (!Number.isFinite(value) || value < 0))) {
777
- throw new ContextPruningError('invalid context pruning metrics', 'schema');
778
- }
779
- const cache = metrics.promptCache;
780
- for (const arm of ['baseline', 'prunedDownstream']) {
781
- const reported = cache?.[arm];
782
- const usage = metrics.providerUsage[arm];
783
- // Cache credit is never a caller assertion: it must match provider-reported usage for the same arm.
784
- if (!reported || !isCount(reported.hits) || !isCount(reported.misses) || !isCount(reported.cachedInputTokens)
785
- || reported.cachedInputTokens !== usage.cachedInputTokens
786
- || (reported.cachedInputTokens > 0 && reported.hits === 0)) {
787
- throw new ContextPruningError(`prompt-cache usage for '${arm}' does not reconcile with provider usage`, 'semantic');
788
- }
789
- }
790
- }
791
- const USAGE_ARMS = ['baseline', 'prunedDownstream', 'decisionCalls', 'fallbackCalls', 'transformationCalls'];
792
- function usage(value, source) {
793
- return Boolean(value) && isCount(value.inputTokens) && isCount(value.outputTokens)
794
- && (source === 'provider'
795
- ? isCount(value.cachedInputTokens) && value.cachedInputTokens <= value.inputTokens
796
- : value.cachedInputTokens === null)
797
- && (value.costUsd === null || (Number.isFinite(value.costUsd) && value.costUsd >= 0));
798
- }
799
- function usageAccounting(value, source) {
800
- return Boolean(value) && typeof value === 'object'
801
- && Object.keys(value).sort().join() === [...USAGE_ARMS].sort().join()
802
- && USAGE_ARMS.every(arm => usage(value[arm], source));
803
- }
804
- /** Baseline arm minus every pruned-arm call (downstream, decision, fallback, transformation). */
805
- function totalSavings(value, basis) {
806
- const tokens = (item) => item.inputTokens + item.outputTokens
807
- - (basis === 'uncached' ? item.cachedInputTokens ?? 0 : 0);
808
- return tokens(value.baseline) - USAGE_ARMS.filter(arm => arm !== 'baseline').reduce((sum, arm) => sum + tokens(value[arm]), 0);
809
- }
810
- function providerUsageSavings(value) {
811
- const costs = USAGE_ARMS.map(arm => value[arm].costUsd);
812
- return {
813
- totalTokens: totalSavings(value, 'total'),
814
- uncachedTokens: totalSavings(value, 'uncached'),
815
- costUsd: costs.some(cost => cost === null) ? null
816
- : value.baseline.costUsd - USAGE_ARMS.filter(arm => arm !== 'baseline').reduce((sum, arm) => sum + value[arm].costUsd, 0),
817
- cachedInputTokensDelta: value.prunedDownstream.cachedInputTokens - value.baseline.cachedInputTokens,
818
- };
819
- }
820
- function sourceTypeForBudget(candidate) {
821
- if (candidate.source.kind === 'system' || candidate.source.kind === 'developer' || candidate.source.kind === 'project')
822
- return 'system';
823
- if (candidate.source.kind === 'user')
824
- return 'user';
825
- if (candidate.protectedHints.includes('explicit-mention'))
826
- return 'at-mention';
827
- return 'auto';
828
- }
829
- function uniqueCandidates(candidates) {
830
- const byId = new Map(candidates.map(candidate => [candidate.itemId, candidate]));
831
- if (byId.size !== candidates.length)
832
- throw new ContextPruningError('candidate item IDs must be unique', 'semantic');
833
- for (const candidate of candidates)
834
- validateContextPruningCandidate(candidate);
835
- for (const candidate of candidates) {
836
- for (const dependencyId of candidate.dependencies) {
837
- if (!byId.has(dependencyId))
838
- throw new ContextPruningError(`unknown context dependency '${dependencyId}'`, 'semantic');
839
- }
840
- }
841
- return byId;
842
- }
843
- function requirePlain(value, label) {
844
- if (!value || typeof value !== 'object' || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
845
- throw new ContextPruningError(`${label} must be a plain object`, 'schema');
846
- }
847
- }
1
+ // Public context pruning API; implementation is split by contract, pilot and evaluation ownership.
2
+ export * from './context-pruning-types.js';
3
+ export { ContextPruningError, contextPruningDigest, contextPruningPairSetDigest, contextPruningRunId, contextPruningReceiptSetDigest, } from './context-pruning-common.js';
4
+ export { classifyContextPruningCandidate, classifyContextPruningCandidates, planContextPruningEvaluations, planContextPruningEvaluationRun, applyContextPruningPilot, validateContextPruningReceipt, computeContextBudgetManagerBaseline, } from './context-pruning-pilot.js';
5
+ export { createContextPruningPreregistration, validateContextPruningPreregistration, buildContextPruningEvaluationReport, } from './context-pruning-evaluation.js';
848
6
  //# sourceMappingURL=context-pruning.js.map