@aiwg/cli 2026.10.11 → 2026.10.14

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 (174) hide show
  1. package/agentic/code/providers/model-catalog.v1.json +62 -12
  2. package/agentic/code/providers/pi/aiwg-bridge.ts +44 -1
  3. package/dist/src/artifacts/binding-target-identity.js +51 -0
  4. package/dist/src/artifacts/checksum-manifest.js +12 -0
  5. package/dist/src/artifacts/index-builder.js +11 -13
  6. package/dist/src/artifacts/query-engine.js +5 -11
  7. package/dist/src/cli/handlers/doctor-help.js +32 -0
  8. package/dist/src/cli/handlers/gates.js +19 -18
  9. package/dist/src/cli/handlers/models-help.js +7 -1
  10. package/dist/src/cli/handlers/models.js +3 -3
  11. package/dist/src/cli/handlers/script-runner.js +8 -5
  12. package/dist/src/cli/handlers/sessions-intake.js +104 -0
  13. package/dist/src/cli/handlers/sessions-tail.js +172 -0
  14. package/dist/src/cli/handlers/sessions.js +90 -17
  15. package/dist/src/cli/handlers/skill-lint.js +10 -3
  16. package/dist/src/cli/handlers/steward-format.js +100 -0
  17. package/dist/src/cli/handlers/steward-models.js +167 -0
  18. package/dist/src/cli/handlers/steward.js +14 -248
  19. package/dist/src/cli/handlers/use-bundle-counts.js +87 -0
  20. package/dist/src/cli/handlers/use-skill-assets.js +207 -0
  21. package/dist/src/cli/handlers/use.js +35 -216
  22. package/dist/src/cli/handlers/utilities.js +1 -24
  23. package/dist/src/config/aiwg-config.js +7 -0
  24. package/dist/src/config/authorization-cli.js +97 -0
  25. package/dist/src/config/cli-help.js +1 -0
  26. package/dist/src/config/cli.js +10 -1
  27. package/dist/src/decision/context-pruning-common.js +41 -0
  28. package/dist/src/decision/context-pruning-evaluation.js +366 -0
  29. package/dist/src/decision/context-pruning-pilot.js +431 -0
  30. package/dist/src/decision/context-pruning-types.js +19 -0
  31. package/dist/src/decision/context-pruning.js +5 -846
  32. package/dist/src/decision/ensemble/contract.js +17 -26
  33. package/dist/src/decision/ensemble-study/artifacts.js +5 -0
  34. package/dist/src/decision/ensemble-study/score.js +4 -3
  35. package/dist/src/decision/feature-export.js +3 -9
  36. package/dist/src/decision/heldout/collector.js +2 -2
  37. package/dist/src/decision/issue-triage/runtime.js +3 -9
  38. package/dist/src/decision/qualification/gates.js +2 -1
  39. package/dist/src/decision/qualification/release.js +6 -64
  40. package/dist/src/decision/routing/report.js +2 -0
  41. package/dist/src/decision/sdlc-screening.js +3 -5
  42. package/dist/src/decision/sensitivity/comparative.js +5 -3
  43. package/dist/src/extensions/manifest.js +8 -1
  44. package/dist/src/extensions/project-local-doctor.js +78 -2
  45. package/dist/src/extensions/validation.js +10 -11
  46. package/dist/src/gates/driver.js +6 -77
  47. package/dist/src/gates/evaluate.js +6 -23
  48. package/dist/src/gates/floors.js +4 -4
  49. package/dist/src/gates/index.js +3 -3
  50. package/dist/src/gates/lattice.js +26 -0
  51. package/dist/src/gates/registry.js +2 -1
  52. package/dist/src/gates/report.js +19 -7
  53. package/dist/src/gates/upstream-ceiling.js +111 -0
  54. package/dist/src/issues/audit-cli.js +120 -0
  55. package/dist/src/issues/audit-contract.js +64 -0
  56. package/dist/src/issues/audit-local.js +82 -0
  57. package/dist/src/issues/audit.js +220 -0
  58. package/dist/src/lint/rule-activation.js +15 -1
  59. package/dist/src/mission-protocol/canonical-codecs.js +270 -0
  60. package/dist/src/mission-protocol/codecs.js +22 -550
  61. package/dist/src/mission-protocol/health-trace-codecs.js +281 -0
  62. package/dist/src/mission-protocol/health-trace-types.js +43 -0
  63. package/dist/src/mission-protocol/types.js +2 -42
  64. package/dist/src/mission-protocol/worker-contract-json.js +10 -0
  65. package/dist/src/mission-protocol/worker-review-gate.js +100 -0
  66. package/dist/src/mission-protocol/worker-review-types.js +2 -0
  67. package/dist/src/models/catalog-policy.js +280 -0
  68. package/dist/src/models/index.js +1 -1
  69. package/dist/src/models/model-catalog.v1.json +62 -12
  70. package/dist/src/models/policy-resources.js +28 -0
  71. package/dist/src/models/provider-models.js +5 -8
  72. package/dist/src/models/provider-policy.js +10 -546
  73. package/dist/src/models/resolver.js +26 -8
  74. package/dist/src/models/router.js +15 -2
  75. package/dist/src/models/tiers.js +13 -0
  76. package/dist/src/models/types.js +0 -6
  77. package/dist/src/models/worker-ceilings.js +59 -0
  78. package/dist/src/models/worker-invocation-policy.js +243 -0
  79. package/dist/src/models/worker-plan.js +16 -20
  80. package/dist/src/models/worker-review-lineage.js +55 -0
  81. package/dist/src/models/worker-selection-policy.js +1 -1
  82. package/dist/src/models/wrapper-definitions.js +14 -0
  83. package/dist/src/models/wrapper-deployment.js +48 -25
  84. package/dist/src/models/wrapper-enforcement.js +72 -0
  85. package/dist/src/models/wrapper-route.js +6 -3
  86. package/dist/src/policy/authorization.js +1 -0
  87. package/dist/src/policy/hitl-check.js +80 -0
  88. package/dist/src/policy/hitl-config.js +63 -0
  89. package/dist/src/policy/hitl-receipt.js +57 -0
  90. package/dist/src/policy/hitl-types.js +4 -0
  91. package/dist/src/policy/hitl-validation.js +39 -0
  92. package/dist/src/policy/hitl.js +117 -0
  93. package/dist/src/rules/activation.d.mts +3 -1
  94. package/dist/src/rules/activation.mjs +23 -2
  95. package/dist/src/rules/gate-coverage.js +51 -0
  96. package/dist/src/rules/gate-references.js +16 -0
  97. package/dist/src/rules/rule-frontmatter.schema.json +7 -1
  98. package/dist/src/serve/worker-command-request.js +21 -4
  99. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  100. package/dist/src/serve/worker-invocation.js +21 -10
  101. package/dist/src/sessions/adapters/deepseek-harness.js +1 -0
  102. package/dist/src/sessions/adapters/grok-build-native.js +269 -0
  103. package/dist/src/sessions/adapters/grok-build.js +57 -15
  104. package/dist/src/sessions/adapters/hermes-state-db.js +252 -0
  105. package/dist/src/sessions/adapters/hermes.js +42 -3
  106. package/dist/src/sessions/adapters/warp.js +1 -1
  107. package/dist/src/sessions/batch-import.js +10 -0
  108. package/dist/src/sessions/contracts.js +1 -1
  109. package/dist/src/sessions/discovery-capability.js +38 -0
  110. package/dist/src/sessions/importer.js +8 -251
  111. package/dist/src/sessions/index.js +4 -0
  112. package/dist/src/sessions/intake-dir.js +71 -0
  113. package/dist/src/sessions/normalization.js +251 -0
  114. package/dist/src/sessions/tail.js +91 -0
  115. package/dist/src/sessions/workspace-discovery.js +83 -7
  116. package/dist/src/skills/adapters/local.js +32 -9
  117. package/dist/src/skills/agent-skill-sidecar.js +28 -0
  118. package/dist/src/skills/agent-skills.js +6 -23
  119. package/dist/src/skills/claude-surface-projection.js +25 -0
  120. package/dist/src/skills/cli-display.js +33 -0
  121. package/dist/src/skills/cli.js +2 -26
  122. package/dist/src/skills/collision-discovery.js +84 -0
  123. package/dist/src/skills/deployer.js +26 -361
  124. package/dist/src/skills/deployment-ownership.js +74 -0
  125. package/dist/src/skills/deployment-policy.js +114 -0
  126. package/dist/src/skills/deployment-projection.js +152 -0
  127. package/dist/src/skills/deployment-types.js +20 -0
  128. package/dist/src/skills/doctor.js +2 -2
  129. package/dist/src/skills/exporter.js +8 -31
  130. package/dist/src/skills/importer.js +4 -26
  131. package/dist/src/skills/provider-extensions.js +41 -0
  132. package/dist/src/skills/registry.js +22 -7
  133. package/dist/src/skills/run.js +6 -0
  134. package/dist/src/skills/types.js +0 -8
  135. package/dist/src/skills/validator-resources.js +68 -0
  136. package/dist/src/skills/validator.js +6 -55
  137. package/dist/src/smiths/context-pipeline/parallelism-section.js +7 -3
  138. package/dist/src/storage/cli-migrate-options.js +125 -0
  139. package/dist/src/storage/cli-migrate.js +111 -0
  140. package/dist/src/storage/cli.js +4 -279
  141. package/dist/src/storage/migration-adapter.js +79 -0
  142. package/dist/src/storage/migration-copy.js +108 -0
  143. package/dist/src/storage/migration-protocol.js +14 -197
  144. package/dist/src/storage/migration-records.js +186 -0
  145. package/dist/src/storage/migration-types.js +12 -0
  146. package/dist/src/tracker/forge-http.js +2 -1
  147. package/dist/src/tracker/issue-pages.js +110 -0
  148. package/package.json +3 -1
  149. package/schemas/mission-v1.schema.json +335 -0
  150. package/schemas/models/model-catalog.v1.schema.json +19 -1
  151. package/schemas/models/model-config-compatibility.v1.schema.json +3 -2
  152. package/schemas/models/model-policy.v1.schema.json +1 -1
  153. package/tools/agents/providers/antigravity.mjs +3 -5
  154. package/tools/agents/providers/base.mjs +3 -3
  155. package/tools/agents/providers/claude.mjs +3 -5
  156. package/tools/agents/providers/codex.mjs +3 -5
  157. package/tools/agents/providers/copilot.mjs +3 -5
  158. package/tools/agents/providers/cursor.mjs +3 -5
  159. package/tools/agents/providers/factory.mjs +3 -5
  160. package/tools/agents/providers/grok-build.mjs +9 -7
  161. package/tools/agents/providers/model-wrapper.mjs +86 -0
  162. package/tools/agents/providers/omp.mjs +3 -1
  163. package/tools/agents/providers/openclaw.mjs +3 -5
  164. package/tools/agents/providers/opencode.mjs +3 -5
  165. package/tools/agents/providers/provider-paths-staging.mjs +44 -0
  166. package/tools/agents/providers/rule-binding-targets.mjs +146 -0
  167. package/tools/agents/providers/rule-delivery.mjs +9 -128
  168. package/tools/agents/providers/warp.mjs +3 -5
  169. package/tools/agents/providers/windsurf.mjs +3 -5
  170. package/tools/plugin/package-plugins.mjs +2 -2
  171. package/tools/skills/codex-skill-transform.mjs +232 -0
  172. package/tools/skills/deploy-skills-codex.mjs +8 -249
  173. package/tools/warp/warp-content.mjs +548 -0
  174. package/vscode-extension/schemas/aiwg.config.v1.json +177 -0
@@ -0,0 +1,431 @@
1
+ // Context pruning pilot classification, decisions, receipts and deterministic baseline.
2
+ import { ContextBudgetManager } from '../metrics/context-budget.js';
3
+ import { admitEntry } from './entry.js';
4
+ import { ContextPruningError, SHA, contextPruningDigest, contextPruningRunId, requirePlain } from './context-pruning-common.js';
5
+ import { CONTEXT_PRUNING_PROTECTED_POLICY_VERSION, CONTEXT_PRUNING_CANDIDATE_SCHEMA, CONTEXT_PRUNING_RECEIPT_SCHEMA } from './context-pruning-types.js';
6
+ const SOURCE_TO_REASON = {
7
+ system: 'system-rule',
8
+ developer: 'developer-rule',
9
+ project: 'project-rule',
10
+ 'security-policy': 'security-policy',
11
+ user: 'current-user-requirement',
12
+ approval: 'action-approval',
13
+ blocker: 'unresolved-blocker',
14
+ provenance: 'provenance-required',
15
+ citation: 'citation-required',
16
+ artifact: 'artifact-pin',
17
+ 'test-evidence': 'test-gate-evidence',
18
+ 'open-decision': 'open-decision-evidence',
19
+ };
20
+ const VALID_SOURCE_KINDS = new Set([
21
+ 'system', 'developer', 'project', 'security-policy', 'user', 'approval', 'blocker',
22
+ 'provenance', 'citation', 'artifact', 'test-evidence', 'open-decision', 'retrieved',
23
+ 'memory', 'tool-output', 'ordinary',
24
+ ]);
25
+ const VALID_PROTECTED_REASONS = new Set([
26
+ 'system-rule', 'developer-rule', 'project-rule', 'security-policy', 'current-user-requirement',
27
+ 'explicit-mention', 'unresolved-blocker', 'action-approval', 'artifact-pin', 'version-pin',
28
+ 'digest-pin', 'provenance-required', 'citation-required', 'test-gate-evidence',
29
+ 'open-decision-evidence', 'protected-dependency', 'external-evaluation-denied', 'local-only',
30
+ 'restricted-data', 'legal-policy',
31
+ ]);
32
+ export function classifyContextPruningCandidate(candidate) {
33
+ validateContextPruningCandidate(candidate);
34
+ const reasons = new Set();
35
+ const mapped = SOURCE_TO_REASON[candidate.source.kind];
36
+ if (mapped)
37
+ reasons.add(mapped);
38
+ for (const hint of candidate.protectedHints)
39
+ reasons.add(hint);
40
+ if (candidate.dataPolicy.externalEvaluation === 'denied')
41
+ reasons.add('external-evaluation-denied');
42
+ if (candidate.dataPolicy.localOnly)
43
+ reasons.add('local-only');
44
+ if (candidate.dataPolicy.legalAction === 'requires-review')
45
+ reasons.add('legal-policy');
46
+ if (candidate.sensitivity === 'restricted')
47
+ reasons.add('restricted-data');
48
+ const sorted = [...reasons].sort();
49
+ const policy = {
50
+ version: CONTEXT_PRUNING_PROTECTED_POLICY_VERSION,
51
+ sourceRules: SOURCE_TO_REASON,
52
+ dataPolicy: ['externalEvaluation', 'localOnly', 'legalAction'],
53
+ sensitivity: ['restricted'],
54
+ protectedHints: [...VALID_PROTECTED_REASONS].sort(),
55
+ };
56
+ return {
57
+ schemaVersion: CONTEXT_PRUNING_PROTECTED_POLICY_VERSION,
58
+ itemId: candidate.itemId,
59
+ protected: sorted.length > 0,
60
+ reasons: sorted,
61
+ policyDigest: contextPruningDigest(policy),
62
+ };
63
+ }
64
+ export function classifyContextPruningCandidates(candidates) {
65
+ const byId = uniqueCandidates(candidates);
66
+ const classifications = new Map();
67
+ for (const candidate of candidates)
68
+ classifications.set(candidate.itemId, classifyContextPruningCandidate(candidate));
69
+ const protectedQueue = candidates.filter(candidate => classifications.get(candidate.itemId).protected)
70
+ .map(candidate => candidate.itemId);
71
+ for (let index = 0; index < protectedQueue.length; index++) {
72
+ const item = byId.get(protectedQueue[index]);
73
+ for (const dependencyId of item.dependencies) {
74
+ const dependency = byId.get(dependencyId);
75
+ if (!dependency)
76
+ throw new ContextPruningError(`unknown context dependency '${dependencyId}'`, 'semantic');
77
+ const current = classifications.get(dependencyId);
78
+ if (current.reasons.includes('protected-dependency'))
79
+ continue;
80
+ classifications.set(dependencyId, {
81
+ ...current,
82
+ protected: true,
83
+ reasons: [...new Set([...current.reasons, 'protected-dependency'])].sort(),
84
+ });
85
+ protectedQueue.push(dependencyId);
86
+ }
87
+ }
88
+ return classifications;
89
+ }
90
+ export function planContextPruningEvaluations(candidates, questions) {
91
+ return planContextPruningEvaluationRun(candidates, questions).jobs;
92
+ }
93
+ export function planContextPruningEvaluationRun(candidates, questions) {
94
+ const byId = uniqueCandidates(candidates);
95
+ const classifications = classifyContextPruningCandidates(candidates);
96
+ const exclusions = [...classifications.values()]
97
+ .filter(classification => classification.protected)
98
+ .map(classification => ({ itemId: classification.itemId, reasons: [...classification.reasons].sort() }));
99
+ const excluded = new Set(exclusions.map(item => item.itemId));
100
+ const groups = new Map();
101
+ for (const question of questions) {
102
+ if (!question.id || !question.itemId || !question.subject || !['relevance', 'disposition', 'omission-risk'].includes(question.kind)) {
103
+ throw new ContextPruningError('invalid context pruning question', 'schema');
104
+ }
105
+ const candidate = byId.get(question.itemId);
106
+ if (!candidate)
107
+ throw new ContextPruningError(`unknown context item '${question.itemId}'`, 'semantic');
108
+ if (excluded.has(candidate.itemId))
109
+ continue;
110
+ const subject = pruningSubject(candidate);
111
+ if (question.subject !== subject)
112
+ throw new ContextPruningError('question subject must be the context item subject', 'semantic');
113
+ const key = `${question.itemId}\0${question.batchKey ?? 'default'}`;
114
+ const group = groups.get(key) ?? [];
115
+ group.push(question);
116
+ groups.set(key, group);
117
+ }
118
+ const jobs = [...groups.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, group]) => {
119
+ const candidate = byId.get(group[0].itemId);
120
+ const subject = pruningSubject(candidate);
121
+ if (group.some(question => question.itemId !== candidate.itemId || question.subject !== subject)) {
122
+ throw new ContextPruningError('unrelated context chunks cannot share a native batch', 'semantic');
123
+ }
124
+ return {
125
+ subject,
126
+ itemId: candidate.itemId,
127
+ state: { candidateDigest: contextPruningDigest(candidate), itemId: candidate.itemId, locator: candidate.locator },
128
+ questions: [...group].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
129
+ contextQuestion: {
130
+ id: `context-pruning:${candidate.itemId}:${group[0].batchKey ?? 'default'}`,
131
+ subject,
132
+ compatibilityKey: `context-pruning:${candidate.itemId}:${group[0].batchKey ?? 'default'}`,
133
+ entry: { candidateDigest: contextPruningDigest(candidate), questions: group.map(question => question.kind).sort() },
134
+ },
135
+ };
136
+ });
137
+ return { jobs, exclusions };
138
+ }
139
+ export function applyContextPruningPilot(input) {
140
+ validatePolicy(input.policy);
141
+ if (input.pairId !== undefined && (typeof input.pairId !== 'string' || !input.pairId)) {
142
+ throw new ContextPruningError('pairId must be a non-empty string', 'invalid-input');
143
+ }
144
+ const pairId = input.pairId ?? null;
145
+ const now = input.now ?? (() => new Date().toISOString());
146
+ const baseline = input.candidates.map(candidate => candidate.itemId);
147
+ const evidence = new Map((input.evidence ?? []).map(item => [item.itemId, item]));
148
+ const disabledReason = input.monitoringRegression ? 'drift-or-monitoring-regression'
149
+ : input.policy.mode === 'disabled' ? 'configured-disabled' : null;
150
+ const mode = disabledReason ? 'deterministic-fallback' : input.policy.mode;
151
+ const classifications = classifyContextPruningCandidates(input.candidates);
152
+ const runId = contextPruningRunId(pairId, input.candidates);
153
+ const deterministicBaseline = input.budget === undefined ? null
154
+ : computeContextBudgetManagerBaseline(input.candidates, input.budget);
155
+ const deterministicDrops = new Set(deterministicBaseline?.droppedItemIds ?? []);
156
+ const receipts = input.candidates.map(candidate => {
157
+ validateContextPruningCandidate(candidate);
158
+ const classification = classifications.get(candidate.itemId);
159
+ const itemEvidence = evidence.get(candidate.itemId);
160
+ const fallbackAction = deterministicDrops.has(candidate.itemId) ? 'drop' : 'keep';
161
+ const decision = decideContextAction(candidate, classification, input.policy, itemEvidence, disabledReason, fallbackAction);
162
+ return buildContextPruningReceipt(candidate, classification, decision, now(), runId, pairId);
163
+ });
164
+ return {
165
+ schemaVersion: 'decision-context-pruning-run/v1',
166
+ runId,
167
+ pairId,
168
+ mode,
169
+ baselineItemIds: baseline,
170
+ // A distinct array: callers that mutate one list cannot silently alter the other.
171
+ downstreamItemIds: [...baseline],
172
+ receipts,
173
+ disabledReason,
174
+ deterministicBaseline,
175
+ };
176
+ }
177
+ /**
178
+ * Validates a receipt's shape and self-digest. When the run's candidate envelopes are supplied, it also
179
+ * re-derives the run identity and the protected-item classification and refuses any mismatch, so a
180
+ * relabelled receipt with a recomputed digest, or a receipt from another run, is rejected.
181
+ */
182
+ export function validateContextPruningReceipt(receipt, candidates) {
183
+ requirePlain(receipt, 'receipt');
184
+ if (receipt.schemaVersion !== CONTEXT_PRUNING_RECEIPT_SCHEMA || !receipt.itemId || !receipt.locator
185
+ || typeof receipt.runId !== 'string' || !SHA.test(receipt.runId)
186
+ || !(receipt.pairId === null || (typeof receipt.pairId === 'string' && receipt.pairId))
187
+ || !SHA.test(receipt.originalDigest) || !Number.isSafeInteger(receipt.originalTokenEstimate) || receipt.originalTokenEstimate < 0
188
+ || !['keep', 'drop', 'truncate', 'summarize'].includes(receipt.proposedAction)
189
+ || !['keep', 'drop', 'truncate', 'summarize'].includes(receipt.appliedAction)
190
+ || !(receipt.decisionReceiptDigest === null || SHA.test(receipt.decisionReceiptDigest))
191
+ || !receipt.reversibleReference || receipt.reversibleReference.originalDigest !== receipt.originalDigest
192
+ || !receipt.reversibleReference.locator || !receipt.reversibleReference.restorationPath
193
+ || !SHA.test(receipt.receiptDigest)) {
194
+ throw new ContextPruningError('invalid pruning receipt', 'schema');
195
+ }
196
+ if ((receipt.proposedAction === 'truncate' || receipt.proposedAction === 'summarize')
197
+ && receipt.reason === 'accepted-evidence' && receipt.reversibleReference.transformation === null) {
198
+ throw new ContextPruningError('transformed receipts require a reversible artifact reference', 'semantic');
199
+ }
200
+ if (receipt.reversibleReference.transformation !== null
201
+ && receipt.reversibleReference.transformation.sourceDigest !== receipt.originalDigest) {
202
+ throw new ContextPruningError('transformation source digest must match the original context item', 'semantic');
203
+ }
204
+ const { receiptDigest, ...payload } = receipt;
205
+ if (receiptDigest !== contextPruningDigest(payload))
206
+ throw new ContextPruningError('pruning receipt digest mismatch', 'semantic');
207
+ if (candidates !== undefined) {
208
+ const candidate = candidates.find(item => item.itemId === receipt.itemId);
209
+ if (!candidate || receipt.runId !== contextPruningRunId(receipt.pairId, candidates)
210
+ || receipt.originalDigest !== candidate.contentDigest || receipt.locator !== candidate.locator
211
+ || receipt.originalTokenEstimate !== candidate.tokenEstimate) {
212
+ throw new ContextPruningError('pruning receipt is not bound to the evaluated run', 'semantic');
213
+ }
214
+ const derived = classifyContextPruningCandidates(candidates).get(candidate.itemId);
215
+ if (contextPruningDigest(derived) !== contextPruningDigest(receipt.classification)) {
216
+ throw new ContextPruningError('pruning receipt classification does not match the candidate envelope', 'semantic');
217
+ }
218
+ // A protected item is never proposed for, or subjected to, a destructive action by this pilot.
219
+ if (derived.protected && (receipt.proposedAction !== 'keep' || receipt.appliedAction !== 'keep')) {
220
+ throw new ContextPruningError('pruning receipt classification does not match its protected action', 'semantic');
221
+ }
222
+ }
223
+ return receipt;
224
+ }
225
+ function pruningSubject(candidate) {
226
+ return `context-item:${candidate.itemId}`;
227
+ }
228
+ function decideContextAction(candidate, classification, policy, evidence, disabledReason, fallbackAction) {
229
+ if (classification.protected)
230
+ return { proposedAction: 'keep', appliedAction: 'keep',
231
+ mode: disabledReason ? 'deterministic-fallback' : policy.mode,
232
+ reason: 'protected-item', decisionReceiptDigest: null, transformation: null };
233
+ const fallback = (reason) => deterministicFallback(fallbackAction, reason);
234
+ if (disabledReason)
235
+ return fallback(disabledReason === 'configured-disabled' ? 'disabled' : 'drift-or-monitoring-regression');
236
+ if (policy.mode === 'disabled')
237
+ return fallback('disabled');
238
+ if (!evidence || evidence.itemId !== candidate.itemId || evidence.subject !== pruningSubject(candidate))
239
+ return fallback('invalid-evidence');
240
+ if (evidence.status === 'cancelled')
241
+ return fallback('cancelled');
242
+ if (evidence.status === 'incomplete')
243
+ return fallback('incomplete-state');
244
+ if (evidence.status === 'uncalibrated')
245
+ return fallback('uncalibrated');
246
+ if (evidence.status === 'drifted')
247
+ return fallback('drift-or-monitoring-regression');
248
+ if (evidence.status === 'failed')
249
+ return fallback('evaluation-failed');
250
+ if (policy.modelIdentityDigest === null || policy.calibrationDigest === null
251
+ || evidence.modelIdentityDigest === undefined || evidence.calibrationDigest === undefined
252
+ || evidence.modelIdentityDigest !== policy.modelIdentityDigest || evidence.calibrationDigest !== policy.calibrationDigest) {
253
+ return fallback('drift-or-monitoring-regression');
254
+ }
255
+ const confidenceBps = evidence.confidenceBps;
256
+ const marginBps = evidence.marginBps;
257
+ if (evidence.status !== 'success' || evidence.disagreement || evidence.proposedAction === undefined
258
+ || typeof confidenceBps !== 'number' || typeof marginBps !== 'number'
259
+ || !Number.isSafeInteger(confidenceBps) || !Number.isSafeInteger(marginBps)
260
+ || confidenceBps < policy.minimumConfidenceBps || marginBps < policy.minimumMarginBps
261
+ || evidence.calibrated !== true || !evidence.decisionReceiptDigest || !SHA.test(evidence.decisionReceiptDigest)) {
262
+ return fallback(evidence.status === 'uncertain' ? 'uncertain-evidence' : 'invalid-evidence');
263
+ }
264
+ const proposed = evidence.proposedAction;
265
+ if (!policy.allowedDestructiveActions.includes(proposed) && proposed !== 'keep')
266
+ return fallback('policy-denied-action');
267
+ if ((proposed === 'truncate' || proposed === 'summarize') && !validTransformation(evidence.transformation, proposed, candidate.contentDigest)) {
268
+ return fallback('unsupported-transformation');
269
+ }
270
+ return {
271
+ proposedAction: proposed,
272
+ appliedAction: 'keep',
273
+ mode: policy.mode,
274
+ reason: policy.mode === 'shadow' && proposed !== 'keep' ? 'shadow-only' : 'accepted-evidence',
275
+ decisionReceiptDigest: evidence.decisionReceiptDigest,
276
+ transformation: evidence.transformation ?? null,
277
+ };
278
+ }
279
+ function deterministicFallback(action, reason) {
280
+ return {
281
+ proposedAction: action,
282
+ appliedAction: 'keep',
283
+ mode: 'deterministic-fallback',
284
+ reason: reason === 'disabled' ? 'disabled'
285
+ : ['invalid-evidence', 'uncertain-evidence', 'uncalibrated', 'incomplete-state', 'cancelled', 'evaluation-failed',
286
+ 'drift-or-monitoring-regression', 'unsupported-transformation', 'policy-denied-action'].includes(reason)
287
+ ? reason : 'prior-deterministic-fallback',
288
+ decisionReceiptDigest: null,
289
+ transformation: null,
290
+ };
291
+ }
292
+ function buildContextPruningReceipt(candidate, classification, decision, createdAt, runId, pairId) {
293
+ const transformation = decision.transformation ?? null;
294
+ const payload = {
295
+ schemaVersion: CONTEXT_PRUNING_RECEIPT_SCHEMA,
296
+ runId,
297
+ pairId,
298
+ itemId: candidate.itemId,
299
+ locator: candidate.locator,
300
+ originalDigest: candidate.contentDigest,
301
+ originalTokenEstimate: candidate.tokenEstimate,
302
+ classification,
303
+ proposedAction: decision.proposedAction,
304
+ appliedAction: decision.appliedAction,
305
+ mode: decision.mode,
306
+ reason: decision.reason,
307
+ decisionReceiptDigest: decision.decisionReceiptDigest,
308
+ reversibleReference: {
309
+ locator: candidate.locator,
310
+ originalDigest: candidate.contentDigest,
311
+ restorationPath: candidate.locator,
312
+ transformation,
313
+ },
314
+ createdAt,
315
+ };
316
+ return validateContextPruningReceipt({ ...payload, receiptDigest: contextPruningDigest(payload) });
317
+ }
318
+ function validTransformation(value, action, sourceDigest) {
319
+ return Boolean(value && value.action === action && value.qualityCheck === 'passed'
320
+ && value.sourceDigest === sourceDigest && value.locator && SHA.test(value.digest));
321
+ }
322
+ export function computeContextBudgetManagerBaseline(candidates, config) {
323
+ const manager = new ContextBudgetManager(process.cwd(), config);
324
+ for (const candidate of candidates) {
325
+ validateContextPruningCandidate(candidate);
326
+ // ContextBudgetManager sizes item text itself; sizing the digest string would understate real content.
327
+ if (candidate.content === undefined) {
328
+ throw new ContextPruningError(`ContextBudgetManager baseline requires host-owned content for '${candidate.itemId}'`, 'invalid-input');
329
+ }
330
+ // The envelope priority is passed as ContextBudgetManager similarity; the manager derives its own priority.
331
+ manager.addItem(candidate.itemId, candidate.content, sourceTypeForBudget(candidate), candidate.priority);
332
+ }
333
+ const result = manager.degrade();
334
+ // ContextBudgetManager spares only source type 'system'; protected (and dependency-protected) items are
335
+ // retained here so the drop list can be applied as the fallback without removing protected context.
336
+ const classifications = classifyContextPruningCandidates(candidates);
337
+ const isProtected = (id) => classifications.get(id).protected;
338
+ const byId = new Map([...result.kept, ...result.dropped].map(item => [item.id, item]));
339
+ const droppedIds = new Set(result.dropped.filter(item => !isProtected(item.id)).map(item => item.id));
340
+ // Re-adding protected items can exceed the manager's target, so continue its own rule (ascending priority,
341
+ // never system items) over the remaining unprotected items until the target is met or none remain.
342
+ const target = Math.floor(manager.contextBudget * manager.getConfig().warningThreshold);
343
+ let current = candidates.reduce((sum, candidate) => sum + (droppedIds.has(candidate.itemId) ? 0 : byId.get(candidate.itemId).tokens), 0);
344
+ const remaining = candidates.map(candidate => byId.get(candidate.itemId))
345
+ .filter(item => !droppedIds.has(item.id) && !isProtected(item.id) && item.source.type !== 'system')
346
+ .sort((a, b) => a.priority - b.priority);
347
+ for (const item of remaining) {
348
+ if (current <= target)
349
+ break;
350
+ droppedIds.add(item.id);
351
+ current -= item.tokens;
352
+ }
353
+ const kept = candidates.map(candidate => byId.get(candidate.itemId)).filter(item => !droppedIds.has(item.id));
354
+ const dropped = candidates.map(candidate => byId.get(candidate.itemId)).filter(item => droppedIds.has(item.id));
355
+ return {
356
+ source: 'ContextBudgetManager',
357
+ usage: {
358
+ inputTokens: kept.reduce((sum, item) => sum + item.tokens, 0),
359
+ cachedInputTokens: null,
360
+ outputTokens: 0,
361
+ costUsd: null,
362
+ },
363
+ keptItemIds: kept.map(item => item.id).sort(),
364
+ droppedItemIds: dropped.map(item => item.id).sort(),
365
+ protectedRetainedItemIds: result.dropped.filter(item => isProtected(item.id)).map(item => item.id).sort(),
366
+ tokensFreed: dropped.reduce((sum, item) => sum + item.tokens, 0),
367
+ withinBudget: current <= target,
368
+ };
369
+ }
370
+ function validateContextPruningCandidate(candidate) {
371
+ requirePlain(candidate, 'candidate');
372
+ if (candidate.schemaVersion !== CONTEXT_PRUNING_CANDIDATE_SCHEMA || !candidate.itemId || !candidate.locator
373
+ || !SHA.test(candidate.contentDigest) || !candidate.source || !VALID_SOURCE_KINDS.has(candidate.source.kind) || !candidate.source.addedAt
374
+ || !Number.isFinite(Date.parse(candidate.source.addedAt))
375
+ || (candidate.content !== undefined && contextPruningDigest(candidate.content) !== candidate.contentDigest)
376
+ || !Number.isSafeInteger(candidate.tokenEstimate) || candidate.tokenEstimate < 0
377
+ || !Number.isFinite(candidate.priority) || candidate.priority < 0 || candidate.priority > 1
378
+ || !['verified', 'untrusted'].includes(candidate.trust)
379
+ || !['public', 'internal', 'confidential', 'restricted'].includes(candidate.sensitivity)
380
+ || !Array.isArray(candidate.dependencies) || new Set(candidate.dependencies).size !== candidate.dependencies.length
381
+ || candidate.dependencies.some(value => typeof value !== 'string' || !value)
382
+ || !Array.isArray(candidate.protectedHints) || new Set(candidate.protectedHints).size !== candidate.protectedHints.length
383
+ || candidate.protectedHints.some(reason => !VALID_PROTECTED_REASONS.has(reason))
384
+ || !candidate.taskSubject || !candidate.dataPolicy
385
+ || !['allowed', 'denied'].includes(candidate.dataPolicy.externalEvaluation)
386
+ || typeof candidate.dataPolicy.localOnly !== 'boolean'
387
+ || !['none', 'requires-review'].includes(candidate.dataPolicy.legalAction)) {
388
+ throw new ContextPruningError('invalid context candidate', 'schema');
389
+ }
390
+ try {
391
+ admitEntry(candidate);
392
+ }
393
+ catch {
394
+ throw new ContextPruningError('context candidate failed admission', 'schema');
395
+ }
396
+ }
397
+ function validatePolicy(policy) {
398
+ if (!['disabled', 'shadow', 'advisory'].includes(policy.mode)
399
+ || !Number.isSafeInteger(policy.minimumConfidenceBps) || policy.minimumConfidenceBps < 0 || policy.minimumConfidenceBps > 10_000
400
+ || !Number.isSafeInteger(policy.minimumMarginBps) || policy.minimumMarginBps < 0 || policy.minimumMarginBps > 10_000
401
+ || !Array.isArray(policy.allowedDestructiveActions)
402
+ || policy.allowedDestructiveActions.some(action => !['keep', 'drop', 'truncate', 'summarize'].includes(action))
403
+ || (policy.calibrationDigest !== null && !SHA.test(policy.calibrationDigest))
404
+ || (policy.modelIdentityDigest !== null && !SHA.test(policy.modelIdentityDigest))) {
405
+ throw new ContextPruningError('invalid context pruning policy', 'schema');
406
+ }
407
+ }
408
+ function sourceTypeForBudget(candidate) {
409
+ if (candidate.source.kind === 'system' || candidate.source.kind === 'developer' || candidate.source.kind === 'project')
410
+ return 'system';
411
+ if (candidate.source.kind === 'user')
412
+ return 'user';
413
+ if (candidate.protectedHints.includes('explicit-mention'))
414
+ return 'at-mention';
415
+ return 'auto';
416
+ }
417
+ export function uniqueCandidates(candidates) {
418
+ const byId = new Map(candidates.map(candidate => [candidate.itemId, candidate]));
419
+ if (byId.size !== candidates.length)
420
+ throw new ContextPruningError('candidate item IDs must be unique', 'semantic');
421
+ for (const candidate of candidates)
422
+ validateContextPruningCandidate(candidate);
423
+ for (const candidate of candidates) {
424
+ for (const dependencyId of candidate.dependencies) {
425
+ if (!byId.has(dependencyId))
426
+ throw new ContextPruningError(`unknown context dependency '${dependencyId}'`, 'semantic');
427
+ }
428
+ }
429
+ return byId;
430
+ }
431
+ //# sourceMappingURL=context-pruning-pilot.js.map
@@ -0,0 +1,19 @@
1
+ export const CONTEXT_PRUNING_PROTECTED_POLICY_VERSION = 'decision-context-protected/v1';
2
+ export const CONTEXT_PRUNING_CANDIDATE_SCHEMA = 'decision-context-candidate/v1';
3
+ export const CONTEXT_PRUNING_RECEIPT_SCHEMA = 'decision-context-pruning-receipt/v1';
4
+ export const CONTEXT_PRUNING_PREREGISTRATION_SCHEMA = 'decision-context-pruning-preregistration/v1';
5
+ export const CONTEXT_PRUNING_EVALUATION_REPORT_SCHEMA = 'decision-context-pruning-evaluation-report/v1';
6
+ /**
7
+ * Clock-skew allowance for `holdoutAccessedAt` attestations: the recorder that stamps holdout access and the
8
+ * evaluator that builds the report may disagree by up to five minutes. An attestation later than the
9
+ * evaluation clock plus this allowance is a future attestation and is rejected.
10
+ */
11
+ export const CONTEXT_PRUNING_HOLDOUT_CLOCK_SKEW_MS = 5 * 60 * 1_000;
12
+ export const CONTEXT_PRUNING_QUALITY_METRICS = [
13
+ 'downstream-task-success',
14
+ 'requirement-coverage',
15
+ 'factual-coverage',
16
+ 'citation-accuracy',
17
+ 'human-preference',
18
+ ];
19
+ //# sourceMappingURL=context-pruning-types.js.map