create-principles-disciple 1.127.1 → 1.128.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 (114) hide show
  1. package/console/dist/server/config/pd-config-store.js +7 -2
  2. package/console/dist/server/models/HealthCheckModel.d.ts +4 -1
  3. package/console/dist/server/models/HealthCheckModel.js +6 -5
  4. package/console/dist/server/routes/update.js +8 -83
  5. package/console/dist/server/utils/installed-layout.d.ts +21 -0
  6. package/console/dist/server/utils/installed-layout.js +92 -0
  7. package/console/dist/server/utils/pd-backups.d.ts +9 -0
  8. package/console/dist/server/utils/pd-backups.js +5 -1
  9. package/console/dist/ui/pages/settings/UpdatePage.js +2 -1
  10. package/console/dist/web/assets/app.js +975 -824
  11. package/console/dist/web/index.html +4 -0
  12. package/core/dist/runtime-v2/activation/__tests__/production-gate-deps.test.js +69 -0
  13. package/core/dist/runtime-v2/activation/__tests__/production-gate-deps.test.js.map +1 -1
  14. package/core/dist/runtime-v2/activation/production-gate-deps.d.ts.map +1 -1
  15. package/core/dist/runtime-v2/activation/production-gate-deps.js +13 -46
  16. package/core/dist/runtime-v2/activation/production-gate-deps.js.map +1 -1
  17. package/core/dist/runtime-v2/config/__tests__/pd-config-sparse-bootstrap.test.d.ts +2 -0
  18. package/core/dist/runtime-v2/config/__tests__/pd-config-sparse-bootstrap.test.d.ts.map +1 -0
  19. package/core/dist/runtime-v2/config/__tests__/pd-config-sparse-bootstrap.test.js +143 -0
  20. package/core/dist/runtime-v2/config/__tests__/pd-config-sparse-bootstrap.test.js.map +1 -0
  21. package/core/dist/runtime-v2/feature-flags/__tests__/installer-config-parity.test.js +44 -27
  22. package/core/dist/runtime-v2/feature-flags/__tests__/installer-config-parity.test.js.map +1 -1
  23. package/core/dist/runtime-v2/internalization/__tests__/adversarial-feedback.test.js +9 -0
  24. package/core/dist/runtime-v2/internalization/__tests__/adversarial-feedback.test.js.map +1 -1
  25. package/core/dist/runtime-v2/internalization/__tests__/artificer-prompt-builder.test.js +15 -5
  26. package/core/dist/runtime-v2/internalization/__tests__/artificer-prompt-builder.test.js.map +1 -1
  27. package/core/dist/runtime-v2/internalization/__tests__/context-resolution.test.d.ts +2 -0
  28. package/core/dist/runtime-v2/internalization/__tests__/context-resolution.test.d.ts.map +1 -0
  29. package/core/dist/runtime-v2/internalization/__tests__/context-resolution.test.js +377 -0
  30. package/core/dist/runtime-v2/internalization/__tests__/context-resolution.test.js.map +1 -0
  31. package/core/dist/runtime-v2/internalization/__tests__/evaluator-artificer-repair-replay.test.d.ts +2 -0
  32. package/core/dist/runtime-v2/internalization/__tests__/evaluator-artificer-repair-replay.test.d.ts.map +1 -0
  33. package/core/dist/runtime-v2/internalization/__tests__/evaluator-artificer-repair-replay.test.js +413 -0
  34. package/core/dist/runtime-v2/internalization/__tests__/evaluator-artificer-repair-replay.test.js.map +1 -0
  35. package/core/dist/runtime-v2/internalization/__tests__/evaluator-gate-authority.test.js +136 -0
  36. package/core/dist/runtime-v2/internalization/__tests__/evaluator-gate-authority.test.js.map +1 -1
  37. package/core/dist/runtime-v2/internalization/__tests__/progressive-disclosure-spike.test.js +8 -8
  38. package/core/dist/runtime-v2/internalization/__tests__/progressive-disclosure-spike.test.js.map +1 -1
  39. package/core/dist/runtime-v2/internalization/__tests__/repair-replay-resolver.test.d.ts +2 -0
  40. package/core/dist/runtime-v2/internalization/__tests__/repair-replay-resolver.test.d.ts.map +1 -0
  41. package/core/dist/runtime-v2/internalization/__tests__/repair-replay-resolver.test.js +340 -0
  42. package/core/dist/runtime-v2/internalization/__tests__/repair-replay-resolver.test.js.map +1 -0
  43. package/core/dist/runtime-v2/internalization/__tests__/shared-information-plane-runner.test.d.ts +2 -0
  44. package/core/dist/runtime-v2/internalization/__tests__/shared-information-plane-runner.test.d.ts.map +1 -0
  45. package/core/dist/runtime-v2/internalization/__tests__/shared-information-plane-runner.test.js +628 -0
  46. package/core/dist/runtime-v2/internalization/__tests__/shared-information-plane-runner.test.js.map +1 -0
  47. package/core/dist/runtime-v2/internalization/adversarial-feedback.d.ts.map +1 -1
  48. package/core/dist/runtime-v2/internalization/adversarial-feedback.js +7 -1
  49. package/core/dist/runtime-v2/internalization/adversarial-feedback.js.map +1 -1
  50. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.d.ts +9 -2
  51. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.d.ts.map +1 -1
  52. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.js +19 -1
  53. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.js.map +1 -1
  54. package/core/dist/runtime-v2/internalization/artificer-runner.d.ts +23 -0
  55. package/core/dist/runtime-v2/internalization/artificer-runner.d.ts.map +1 -1
  56. package/core/dist/runtime-v2/internalization/artificer-runner.js +184 -16
  57. package/core/dist/runtime-v2/internalization/artificer-runner.js.map +1 -1
  58. package/core/dist/runtime-v2/internalization/context-manifests.d.ts +90 -17
  59. package/core/dist/runtime-v2/internalization/context-manifests.d.ts.map +1 -1
  60. package/core/dist/runtime-v2/internalization/context-manifests.js +124 -27
  61. package/core/dist/runtime-v2/internalization/context-manifests.js.map +1 -1
  62. package/core/dist/runtime-v2/internalization/context-resolution.d.ts +189 -0
  63. package/core/dist/runtime-v2/internalization/context-resolution.d.ts.map +1 -0
  64. package/core/dist/runtime-v2/internalization/context-resolution.js +317 -0
  65. package/core/dist/runtime-v2/internalization/context-resolution.js.map +1 -0
  66. package/core/dist/runtime-v2/internalization/evaluator-output.d.ts +18 -1
  67. package/core/dist/runtime-v2/internalization/evaluator-output.d.ts.map +1 -1
  68. package/core/dist/runtime-v2/internalization/evaluator-output.js +12 -2
  69. package/core/dist/runtime-v2/internalization/evaluator-output.js.map +1 -1
  70. package/core/dist/runtime-v2/internalization/evaluator-runner.d.ts +32 -0
  71. package/core/dist/runtime-v2/internalization/evaluator-runner.d.ts.map +1 -1
  72. package/core/dist/runtime-v2/internalization/evaluator-runner.js +171 -12
  73. package/core/dist/runtime-v2/internalization/evaluator-runner.js.map +1 -1
  74. package/core/dist/runtime-v2/internalization/refiner-sandbox-wrapper.d.ts +18 -1
  75. package/core/dist/runtime-v2/internalization/refiner-sandbox-wrapper.d.ts.map +1 -1
  76. package/core/dist/runtime-v2/internalization/refiner-sandbox-wrapper.js +20 -0
  77. package/core/dist/runtime-v2/internalization/refiner-sandbox-wrapper.js.map +1 -1
  78. package/core/dist/runtime-v2/internalization/repair-replay-resolver.d.ts +112 -0
  79. package/core/dist/runtime-v2/internalization/repair-replay-resolver.d.ts.map +1 -0
  80. package/core/dist/runtime-v2/internalization/repair-replay-resolver.js +332 -0
  81. package/core/dist/runtime-v2/internalization/repair-replay-resolver.js.map +1 -0
  82. package/core/dist/runtime-v2/runner/base-peer-runner.d.ts +62 -17
  83. package/core/dist/runtime-v2/runner/base-peer-runner.d.ts.map +1 -1
  84. package/core/dist/runtime-v2/runner/base-peer-runner.js +116 -10
  85. package/core/dist/runtime-v2/runner/base-peer-runner.js.map +1 -1
  86. package/core/dist/telemetry-event.d.ts +2 -2
  87. package/core/dist/telemetry-event.d.ts.map +1 -1
  88. package/core/dist/telemetry-event.js +61 -0
  89. package/core/dist/telemetry-event.js.map +1 -1
  90. package/core/package.json +1 -1
  91. package/dist/installer.d.ts.map +1 -1
  92. package/dist/installer.js +16 -12
  93. package/dist/installer.js.map +1 -1
  94. package/dist/mvp-config.d.ts +22 -15
  95. package/dist/mvp-config.d.ts.map +1 -1
  96. package/dist/mvp-config.js +48 -106
  97. package/dist/mvp-config.js.map +1 -1
  98. package/host-runtime/package.json +1 -1
  99. package/install-layout/package.json +7 -3
  100. package/package.json +1 -1
  101. package/pd-cli/dist/commands/console.d.ts +13 -0
  102. package/pd-cli/dist/commands/console.d.ts.map +1 -1
  103. package/pd-cli/dist/commands/console.js +104 -0
  104. package/pd-cli/dist/commands/console.js.map +1 -1
  105. package/pd-cli/dist/commands/runtime-init.d.ts.map +1 -1
  106. package/pd-cli/dist/commands/runtime-init.js +8 -12
  107. package/pd-cli/dist/commands/runtime-init.js.map +1 -1
  108. package/pd-cli/dist/commands/runtime-internalization-run-once.d.ts.map +1 -1
  109. package/pd-cli/dist/commands/runtime-internalization-run-once.js +7 -1
  110. package/pd-cli/dist/commands/runtime-internalization-run-once.js.map +1 -1
  111. package/pd-cli/package.json +1 -1
  112. package/plugin/dist/bundle.js +449 -437
  113. package/plugin/dist/governance-audit.js +141 -141
  114. package/plugin/dist/rulehost-evidence.js +153 -153
@@ -0,0 +1,332 @@
1
+ import { hydratePITaskRecord } from './pitask-metadata.js';
2
+ /** Sandbox error enums that legacy artifacts stored inside actualDecision. */
3
+ const LEGACY_SANDBOX_ERROR_TYPES = new Set([
4
+ 'forbidden_pattern',
5
+ 'syntax_error',
6
+ 'runtime_error',
7
+ 'timeout',
8
+ 'validation_failed',
9
+ 'unknown',
10
+ ]);
11
+ /** Real decisions a rule can return — never valid errorType values. */
12
+ const RULEHOST_DECISIONS = new Set([
13
+ 'allow',
14
+ 'block',
15
+ 'requireApproval',
16
+ 'auto_correct',
17
+ ]);
18
+ /** System sentinel prefix/suffix convention (SPEC §17): `__name__`. */
19
+ function isSystemSentinelCaseId(caseId) {
20
+ return caseId.startsWith('__') && caseId.endsWith('__') && caseId.length > 4;
21
+ }
22
+ /**
23
+ * Repair-prompt budget cap for replay evidence (SPEC §29): at most this many
24
+ * failure entries enter the Artificer repair prompt. 16 entries × ~30 tokens
25
+ * stays comfortably inside the existing prompt budget.
26
+ */
27
+ export const MAX_REPLAY_FAILURES_IN_REPAIR = 16;
28
+ function isRecord(value) {
29
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
30
+ }
31
+ function optionalNonEmptyString(value) {
32
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
33
+ }
34
+ /**
35
+ * Normalize one durable failed-case entry (rc-4: element-level validation).
36
+ *
37
+ * Legacy representation (pre PR-A): `actualDecision` carries a sandbox error
38
+ * enum and no `errorType` exists → errorType moves over, actualDecision is
39
+ * dropped (SPEC §21 — readers normalize, no migration).
40
+ *
41
+ * Current representation: `errorType` is authoritative; `actualDecision`
42
+ * appears only when a real decision mismatched and must not be an error enum.
43
+ * Entries that fail structural validation are invalid — the caller fails
44
+ * loud rather than silently dropping evidence (rc-3).
45
+ */
46
+ /** Repair-prompt budget cap for a single failure message (SPEC §23). */
47
+ const MAX_EVIDENCE_MESSAGE_LENGTH = 300;
48
+ function boundMessage(message) {
49
+ return message.length > MAX_EVIDENCE_MESSAGE_LENGTH
50
+ ? `${message.slice(0, MAX_EVIDENCE_MESSAGE_LENGTH)}…`
51
+ : message;
52
+ }
53
+ function normalizeFailedCaseEntry(entry) {
54
+ if (!isRecord(entry))
55
+ return null;
56
+ const caseId = optionalNonEmptyString(entry.caseId);
57
+ if (caseId === undefined)
58
+ return null;
59
+ const rawErrorType = optionalNonEmptyString(entry.errorType);
60
+ const rawActual = optionalNonEmptyString(entry.actualDecision);
61
+ let errorType = rawErrorType;
62
+ let actualDecision = rawActual;
63
+ if (errorType === undefined && rawActual !== undefined) {
64
+ if (LEGACY_SANDBOX_ERROR_TYPES.has(rawActual)) {
65
+ // Legacy drift: actualDecision held the error classification.
66
+ errorType = rawActual;
67
+ actualDecision = undefined;
68
+ }
69
+ else if (RULEHOST_DECISIONS.has(rawActual)) {
70
+ // Legacy decision-mismatch entry: the mismatch was a validation failure.
71
+ errorType = 'validation_failed';
72
+ }
73
+ else {
74
+ errorType = 'unknown';
75
+ }
76
+ }
77
+ if (errorType === undefined)
78
+ errorType = 'unknown';
79
+ // Defense-in-depth on current-shape entries: an errorType value inside
80
+ // actualDecision is always reclassification drift, never a real decision.
81
+ if (actualDecision !== undefined && LEGACY_SANDBOX_ERROR_TYPES.has(actualDecision)) {
82
+ actualDecision = undefined;
83
+ }
84
+ const rationale = optionalNonEmptyString(entry.rationale);
85
+ const message = optionalNonEmptyString(entry.message) ?? rationale;
86
+ return {
87
+ caseId,
88
+ attackType: optionalNonEmptyString(entry.attackType),
89
+ expectedDecision: optionalNonEmptyString(entry.expectedDecision),
90
+ ...(actualDecision !== undefined ? { actualDecision } : {}),
91
+ errorType,
92
+ ...(message !== undefined ? { message: boundMessage(message) } : {}),
93
+ };
94
+ }
95
+ /**
96
+ * Bounded deterministic stratified selection (SPEC §30 as tightened by review
97
+ * 2026-09-02). Trace failures, system failures, and global violations share
98
+ * ONE capacity budget — no evidence class can bypass the prompt bound:
99
+ *
100
+ * 1. system failure representatives (stable order);
101
+ * 2. one global-violation representative for the whole violation group;
102
+ * 3. true decision mismatches FIRST by expected axis — at least one
103
+ * expected=allow, one expected=block, one expected=propose_correction
104
+ * representative each (when present) — so low-value runtime failures can
105
+ * never evict every behavioral mismatch from the prompt;
106
+ * 4. remaining errorType × expectedDecision group representatives
107
+ * (stable first-occurrence order, mismatch-preferring);
108
+ * 5. stable-order fill over trace → system → remaining violations;
109
+ * 6. truncated=true when anything was omitted.
110
+ */
111
+ export function selectBoundedReplayFailures(params) {
112
+ const capacity = Math.max(0, params.capacity);
113
+ let remaining = capacity;
114
+ const chosenFailures = new Set();
115
+ const chosenViolations = new Set();
116
+ // Selected failures are recorded in SELECTION PRIORITY order so the repair
117
+ // prompt renders behavioral mismatches before raw structural errors.
118
+ const traceIdentity = new Set(params.traceFailures);
119
+ const orderedSelected = [];
120
+ const takeFailure = (failure) => {
121
+ if (remaining <= 0 || chosenFailures.has(failure))
122
+ return;
123
+ chosenFailures.add(failure);
124
+ orderedSelected.push(failure);
125
+ remaining -= 1;
126
+ };
127
+ const takeViolation = (violation) => {
128
+ if (remaining <= 0 || chosenViolations.has(violation))
129
+ return;
130
+ chosenViolations.add(violation);
131
+ remaining -= 1;
132
+ };
133
+ // 1. system representatives first.
134
+ for (const systemFailure of params.systemFailures) {
135
+ if (remaining <= 0)
136
+ break;
137
+ takeFailure(systemFailure);
138
+ }
139
+ // 2. one global-violation representative.
140
+ const [firstViolation] = params.globalViolations;
141
+ if (firstViolation !== undefined)
142
+ takeViolation(firstViolation);
143
+ // 3. decision mismatches by expected axis (canonical decision order).
144
+ const mismatchByExpected = new Map();
145
+ for (const failure of params.traceFailures) {
146
+ if (failure.actualDecision === undefined)
147
+ continue;
148
+ const key = failure.expectedDecision ?? 'unknown';
149
+ if (!mismatchByExpected.has(key))
150
+ mismatchByExpected.set(key, failure);
151
+ }
152
+ for (const expectedKey of ['allow', 'block', 'propose_correction']) {
153
+ if (remaining <= 0)
154
+ break;
155
+ const representative = mismatchByExpected.get(expectedKey);
156
+ if (representative !== undefined)
157
+ takeFailure(representative);
158
+ }
159
+ // 4. remaining group representatives (mismatch-preferring, stable order).
160
+ const groups = new Map();
161
+ for (const failure of params.traceFailures) {
162
+ const key = `${failure.errorType}×${failure.expectedDecision ?? 'unknown'}`;
163
+ const existing = groups.get(key);
164
+ if (existing === undefined || (existing.actualDecision === undefined && failure.actualDecision !== undefined)) {
165
+ groups.set(key, failure);
166
+ }
167
+ }
168
+ for (const representative of groups.values()) {
169
+ if (remaining <= 0)
170
+ break;
171
+ takeFailure(representative);
172
+ }
173
+ // 5. stable-order fill: trace → system → remaining violations.
174
+ for (const failure of [...params.traceFailures, ...params.systemFailures]) {
175
+ if (remaining <= 0)
176
+ break;
177
+ takeFailure(failure);
178
+ }
179
+ for (const violation of params.globalViolations) {
180
+ if (remaining <= 0)
181
+ break;
182
+ takeViolation(violation);
183
+ }
184
+ const total = params.traceFailures.length + params.systemFailures.length + params.globalViolations.length;
185
+ const selectedCount = chosenFailures.size + chosenViolations.size;
186
+ return {
187
+ selectedTrace: orderedSelected.filter((f) => traceIdentity.has(f)),
188
+ selectedSystem: orderedSelected.filter((f) => !traceIdentity.has(f)),
189
+ selectedGlobalViolations: params.globalViolations.filter((v) => chosenViolations.has(v)),
190
+ truncated: selectedCount < total,
191
+ };
192
+ }
193
+ /**
194
+ * Resolve the authoritative Evaluator artifact for a repair round.
195
+ *
196
+ * Selection authority (SPEC §26, tightened by review 2026-09-02): the
197
+ * evaluator task's durable completionIntent records the exact run that
198
+ * produced the verdict, and the artifact ID is deterministically
199
+ * `pi-art-<taskId>-<runId>`. When the intent exists, that artifact IS the
200
+ * authority — if it is missing we FAIL LOUD; another run's artifact may never
201
+ * become a fallback authority. Only when no intent exists (legacy tasks) does
202
+ * the exactly-one list rule apply: zero or many → fail loud, never a
203
+ * positional pick.
204
+ */
205
+ async function resolveAuthoritativeEvaluatorArtifact(sourceEvaluatorTaskId, deps) {
206
+ const task = await deps.getTask(sourceEvaluatorTaskId);
207
+ if (!task) {
208
+ return { ok: false, reason: 'task_missing', detail: `evaluator task ${sourceEvaluatorTaskId} not found` };
209
+ }
210
+ const piTask = hydratePITaskRecord(task);
211
+ const intentRunId = piTask?.completionIntent?.sourceRunId;
212
+ if (typeof intentRunId === 'string' && intentRunId.trim() !== '') {
213
+ const artifactId = `pi-art-${sourceEvaluatorTaskId}-${intentRunId}`;
214
+ const artifact = await deps.artifactStore.getArtifactById(artifactId);
215
+ if (artifact) {
216
+ return { ok: true, artifactId: artifact.artifactId, contentJson: artifact.contentJson };
217
+ }
218
+ // The durable authority is KNOWN — a different run's artifact must never
219
+ // be silently promoted into its place (P1 review 2026-09-02).
220
+ return {
221
+ ok: false,
222
+ reason: 'artifact_missing',
223
+ detail: `completionIntent names run ${intentRunId} as authoritative but artifact ${artifactId} does not exist — refusing cross-run fallback`,
224
+ };
225
+ }
226
+ const artifacts = (await deps.artifactStore.listBySourceTaskId(sourceEvaluatorTaskId))
227
+ .filter((a) => a.artifactKind === 'principle');
228
+ if (artifacts.length === 0) {
229
+ return {
230
+ ok: false,
231
+ reason: 'artifact_missing',
232
+ detail: `no principle artifact for evaluator task ${sourceEvaluatorTaskId}`,
233
+ };
234
+ }
235
+ if (artifacts.length > 1) {
236
+ return {
237
+ ok: false,
238
+ reason: 'artifact_ambiguous',
239
+ detail: `evaluator task ${sourceEvaluatorTaskId} has ${artifacts.length} principle artifacts and no resolvable completion intent — authority is ambiguous: ${artifacts.map((a) => a.artifactId).sort().join(', ')}`,
240
+ };
241
+ }
242
+ const [only] = artifacts;
243
+ if (!only) {
244
+ return { ok: false, reason: 'artifact_missing', detail: `no principle artifact for evaluator task ${sourceEvaluatorTaskId}` };
245
+ }
246
+ return { ok: true, artifactId: only.artifactId, contentJson: only.contentJson };
247
+ }
248
+ /**
249
+ * Resolve the bounded, normalized replay-evidence context for a repair round.
250
+ * Pure read + transform: no writes, no telemetry side effects — callers own
251
+ * observability.
252
+ */
253
+ export async function resolveRepairReplayContext(params) {
254
+ const { sourceEvaluatorTaskId, deps } = params;
255
+ const artifactResolution = await resolveAuthoritativeEvaluatorArtifact(sourceEvaluatorTaskId, deps);
256
+ if (!artifactResolution.ok) {
257
+ return artifactResolution;
258
+ }
259
+ const { artifactId, contentJson } = artifactResolution;
260
+ let parsed;
261
+ try {
262
+ parsed = JSON.parse(contentJson);
263
+ }
264
+ catch {
265
+ return { ok: false, reason: 'adversarial_result_invalid', detail: `evaluator artifact ${artifactId} contentJson is unparseable` };
266
+ }
267
+ if (!isRecord(parsed) || !Object.hasOwn(parsed, 'adversarialResult')) {
268
+ return { ok: false, reason: 'adversarial_result_missing', detail: `evaluator artifact ${artifactId} carries no adversarialResult` };
269
+ }
270
+ const { adversarialResult } = parsed;
271
+ if (!isRecord(adversarialResult) || typeof adversarialResult.passed !== 'boolean') {
272
+ return { ok: false, reason: 'adversarial_result_invalid', detail: `evaluator artifact ${artifactId} adversarialResult is malformed (passed must be a boolean)` };
273
+ }
274
+ if (!Object.hasOwn(adversarialResult, 'failedCases') || !Array.isArray(adversarialResult.failedCases)) {
275
+ return { ok: false, reason: 'adversarial_result_invalid', detail: `evaluator artifact ${artifactId} adversarialResult.failedCases is missing or not an array` };
276
+ }
277
+ // rc-4: validate every element; any structurally invalid entry fails loud —
278
+ // dropping evidence silently would re-create the blind-retry hole.
279
+ const normalized = [];
280
+ for (const [index, entry] of adversarialResult.failedCases.entries()) {
281
+ const normalizedEntry = normalizeFailedCaseEntry(entry);
282
+ if (normalizedEntry === null) {
283
+ return {
284
+ ok: false,
285
+ reason: 'adversarial_result_invalid',
286
+ detail: `evaluator artifact ${artifactId} adversarialResult.failedCases[${index}] is structurally invalid`,
287
+ };
288
+ }
289
+ normalized.push(normalizedEntry);
290
+ }
291
+ // Partition by identity (SPEC §17/§18): real trace IDs vs system sentinels
292
+ // vs code-level global violations. Forbidden-pattern entries are counted
293
+ // ONLY as global violations — never also as system failures (review P2
294
+ // 2026-09-02: no double-count in the prompt) — and share the bounded
295
+ // selection budget with everything else.
296
+ const traceFailures = [];
297
+ const systemFailures = [];
298
+ const globalViolations = [];
299
+ for (const failure of normalized) {
300
+ if (failure.caseId === '__forbidden_pattern__') {
301
+ globalViolations.push(failure.message ?? `forbidden pattern (${failure.errorType})`);
302
+ continue;
303
+ }
304
+ if (isSystemSentinelCaseId(failure.caseId)) {
305
+ systemFailures.push(failure);
306
+ continue;
307
+ }
308
+ traceFailures.push(failure);
309
+ }
310
+ const selection = selectBoundedReplayFailures({
311
+ traceFailures,
312
+ systemFailures,
313
+ globalViolations,
314
+ capacity: MAX_REPLAY_FAILURES_IN_REPAIR,
315
+ });
316
+ return {
317
+ ok: true,
318
+ context: {
319
+ sourceEvaluatorTaskId,
320
+ sourceEvaluatorArtifactId: artifactId,
321
+ ran: true,
322
+ passed: adversarialResult.passed,
323
+ failedCaseCount: normalized.length,
324
+ traceFailures: selection.selectedTrace,
325
+ systemFailures: selection.selectedSystem,
326
+ globalViolations: selection.selectedGlobalViolations,
327
+ globalViolationCount: globalViolations.length,
328
+ truncated: selection.truncated,
329
+ },
330
+ };
331
+ }
332
+ //# sourceMappingURL=repair-replay-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repair-replay-resolver.js","sourceRoot":"","sources":["../../../src/runtime-v2/internalization/repair-replay-resolver.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAG3D,8EAA8E;AAC9E,MAAM,0BAA0B,GAAwB,IAAI,GAAG,CAAC;IAC9D,mBAAmB;IACnB,cAAc;IACd,eAAe;IACf,SA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,MAAM;YAChC,eAAe,EAAE,UAAU,CAAC,MAAM;YAClC,aAAa,EAAE,SAAS,CAAC,aAAa;YACtC,cAAc,EAAE,SAAS,CAAC,cAAc;YACxC,gBAAgB,EAAE,SAAS,CAAC,wBAAwB;YACpD,oBAAoB,EAAE,gBAAgB,CAAC,MAAM;YAC7C,SAAS,EAAE,SAAS,CAAC,SAAS;SAC/B;KACF,CAAC;AACJ,CAAC"}
@@ -29,6 +29,32 @@ import type { PeerRunnerOptions, ResolvedPeerRunnerOptions, PeerRunnerDeps, Peer
29
29
  import type { SummaryRunnerKind } from '../internalization/artifact-summary.js';
30
30
  import { type LoadedPredecessorArtifact } from '../internalization/attach-summary-envelope.js';
31
31
  import type { ContextManifest } from '../internalization/context-manifest.js';
32
+ import { type RelatedContextSource } from '../internalization/context-resolution.js';
33
+ /**
34
+ * Outcome of a Layer 1 context-injection resolution.
35
+ *
36
+ * - `focused` — use `fields` (path → preview text) as the focused context.
37
+ * - `fallback` — the caller MUST fall back to the legacy full-predecessor
38
+ * injection (F13). The three original triggers come from `resolveInjection`;
39
+ * PR B adds two:
40
+ * - `required_evidence_unresolved` — the allocation looked healthy but a
41
+ * caller-declared required field never reached the prompt (absent or
42
+ * budget-truncated). This is the "Stage2 enabled + raw silently absent"
43
+ * guard (design §35: no silent thin context).
44
+ * - `lineage_unavailable` — CandidateLineage hit data corruption or a store
45
+ * failure, so required tier2 evidence cannot be served at all (§21).
46
+ * - `disabled` — `context_manifest_budget` is off; caller keeps its assembly.
47
+ */
48
+ export type ContextInjectionOutcome = {
49
+ readonly mode: 'focused';
50
+ readonly fields: Readonly<Record<string, string>>;
51
+ } | {
52
+ readonly mode: 'fallback';
53
+ readonly reason: 'empty_allocation' | 'tier1_all_absent' | 'absent_ratio_exceeded' | 'required_evidence_unresolved' | 'lineage_unavailable';
54
+ readonly unresolvedRequired: readonly string[];
55
+ } | {
56
+ readonly mode: 'disabled';
57
+ };
32
58
  /**
33
59
  * Abstract base class for peer runners.
34
60
  *
@@ -213,32 +239,51 @@ export declare abstract class BasePeerRunner<TContext extends {
213
239
  * Resolve the cross-level context injection for a runner via the Layer 1
214
240
  * manifest + budget path (design §6.2/§6.3/§6.2.2).
215
241
  *
216
- * Single wiring point shared by the 4 peer runners (task 5.9). Returns:
217
- * - `{ mode: 'focused', fields }` — use the manifest-allocated fields as
218
- * the focused context (a `Record<string,string>` of path → preview text)
219
- * - `{ mode: 'fallback' }` — resolution was too sparse; the caller MUST
220
- * fall back to the legacy full-predecessor injection (F13). The fallback
221
- * emits exactly one `manifest_resolution_insufficient` event (rc-9).
222
- * - `{ mode: 'disabled' }` — flag off; caller uses the existing assembly.
242
+ * Single wiring point shared by the peer runners (task 5.9). This SYNC
243
+ * variant resolves only Channel 1 (the predecessor's Layer 0
244
+ * summary/predecessorSummary envelope); it is correct for runners whose
245
+ * manifest declares no tier2 raw field and no related reference. Runners
246
+ * that need tier2/related evidence use `resolveContextInjectionAsync`.
223
247
  *
224
248
  * `predecessorContentJson` is the loaded predecessor artifact's contentJson
225
249
  * (the same object buildContext already holds — zero extra store reads, F3).
226
- * It carries the Layer 0 `summary` / `predecessorSummary` envelope; the
227
- * summary-field-reader extracts the manifest-declared paths from it.
228
250
  *
229
251
  * budgetTokens scope (design §6.2.1): covers ONLY manifest-declared fields.
230
252
  *
231
253
  * `taskId` is used for telemetry event attribution (runnerKind comes from
232
254
  * the manifest itself via event.runnerKind).
233
255
  */
234
- protected resolveContextInjection(taskId: string, manifest: ContextManifest, predecessorContentJson: unknown): {
235
- mode: 'focused';
236
- fields: Readonly<Record<string, string>>;
237
- } | {
238
- mode: 'fallback';
239
- } | {
240
- mode: 'disabled';
241
- };
256
+ protected resolveContextInjection(taskId: string, manifest: ContextManifest, predecessorContentJson: unknown): ContextInjectionOutcome;
257
+ /**
258
+ * Async variant: resolves ALL THREE fact-acquisition channels before running
259
+ * the same allocation + information-floor core (design §6.4/§6.6, PR B).
260
+ *
261
+ * 1. predecessor summary envelope — pure, from `predecessorContentJson`
262
+ * 2. ancestry raw (`<stage>.raw.*`) — `CandidateLineage` from
263
+ * `startArtifactId`; the nearest ancestor of a stage wins
264
+ * 3. related references (`<ns>.summary.*` / `<ns>.raw.*`) — caller-supplied
265
+ * causal references, e.g. the PR-A replay evidence
266
+ *
267
+ * `requiredPaths` is the required-evidence gate (design §33–§37): a listed
268
+ * path that ends up absent OR budget-truncated forces an observable fallback
269
+ * instead of a silently thin focused context. Pass an empty list (or omit it)
270
+ * when tier2 is genuinely optional.
271
+ */
272
+ protected resolveContextInjectionAsync(params: {
273
+ readonly taskId: string;
274
+ readonly manifest: ContextManifest;
275
+ readonly predecessorContentJson: unknown;
276
+ /** Lineage traversal start — normally the predecessor artifact id. */
277
+ readonly startArtifactId?: string;
278
+ readonly relatedSources?: readonly RelatedContextSource[];
279
+ readonly requiredPaths?: readonly string[];
280
+ }): Promise<ContextInjectionOutcome>;
281
+ /**
282
+ * Allocation + information-floor core shared by both variants (design
283
+ * §6.2.2). Allocates, emits the Layer 1 events, then applies PR B's
284
+ * required-evidence gate before reporting `focused`.
285
+ */
286
+ private runResolveInjection;
242
287
  /**
243
288
  * Task 12: Construct an AgentDraftPayload from the permanent-failure
244
289
  * context and write it to pending_agent_drafts via the injected
@@ -1 +1 @@
1
- {"version":3,"file":"base-peer-runner.d.ts","sourceRoot":"","sources":["../../../src/runtime-v2/runner/base-peer-runner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAC7E,OAAO,KAAK,EACV,gBAAgB,EAChB,SAAS,EACT,SAAS,EACT,WAAW,EACZ,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC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CAAC;QACxB,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAC;QACnC,QAAQ,CAAC,sBAAsB,EAAE,OAAO,CAAC;QACzC,sEAAsE;QACtE,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;QAClC,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,oBAAoB,EAAE,CAAC;QAC1D,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;KAC5C,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAoEnC;IAED;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IA0D3B;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,OAAO,CAAC,kCAAkC;CA6D3C"}
@@ -26,6 +26,8 @@ import { attachSummaryEnvelope, } from '../internalization/attach-summary-envelo
26
26
  import { declaredFields } from '../internalization/context-manifest.js';
27
27
  import { resolveInjection } from '../internalization/resolve-injection.js';
28
28
  import { buildAvailableMap } from '../internalization/summary-field-reader.js';
29
+ import { CandidateLineage } from '../internalization/candidate-lineage.js';
30
+ import { findUnresolvedRequiredPaths, mergeContextFields, parseContextPath, partitionTier2Paths, resolveAncestryPaths, resolveRelatedPaths, toRawStageSources, } from '../internalization/context-resolution.js';
29
31
  // ── Defaults ─────────────────────────────────────────────────────────────────
30
32
  const DEFAULT_PEER_RUNNER_OPTIONS = {
31
33
  pollIntervalMs: 5_000,
@@ -925,18 +927,14 @@ export class BasePeerRunner {
925
927
  * Resolve the cross-level context injection for a runner via the Layer 1
926
928
  * manifest + budget path (design §6.2/§6.3/§6.2.2).
927
929
  *
928
- * Single wiring point shared by the 4 peer runners (task 5.9). Returns:
929
- * - `{ mode: 'focused', fields }` — use the manifest-allocated fields as
930
- * the focused context (a `Record<string,string>` of path → preview text)
931
- * - `{ mode: 'fallback' }` — resolution was too sparse; the caller MUST
932
- * fall back to the legacy full-predecessor injection (F13). The fallback
933
- * emits exactly one `manifest_resolution_insufficient` event (rc-9).
934
- * - `{ mode: 'disabled' }` — flag off; caller uses the existing assembly.
930
+ * Single wiring point shared by the peer runners (task 5.9). This SYNC
931
+ * variant resolves only Channel 1 (the predecessor's Layer 0
932
+ * summary/predecessorSummary envelope); it is correct for runners whose
933
+ * manifest declares no tier2 raw field and no related reference. Runners
934
+ * that need tier2/related evidence use `resolveContextInjectionAsync`.
935
935
  *
936
936
  * `predecessorContentJson` is the loaded predecessor artifact's contentJson
937
937
  * (the same object buildContext already holds — zero extra store reads, F3).
938
- * It carries the Layer 0 `summary` / `predecessorSummary` envelope; the
939
- * summary-field-reader extracts the manifest-declared paths from it.
940
938
  *
941
939
  * budgetTokens scope (design §6.2.1): covers ONLY manifest-declared fields.
942
940
  *
@@ -949,6 +947,95 @@ export class BasePeerRunner {
949
947
  }
950
948
  const paths = declaredFields(manifest);
951
949
  const available = buildAvailableMap(paths, predecessorContentJson);
950
+ return this.runResolveInjection({ taskId, manifest, available, requiredPaths: [] });
951
+ }
952
+ /**
953
+ * Async variant: resolves ALL THREE fact-acquisition channels before running
954
+ * the same allocation + information-floor core (design §6.4/§6.6, PR B).
955
+ *
956
+ * 1. predecessor summary envelope — pure, from `predecessorContentJson`
957
+ * 2. ancestry raw (`<stage>.raw.*`) — `CandidateLineage` from
958
+ * `startArtifactId`; the nearest ancestor of a stage wins
959
+ * 3. related references (`<ns>.summary.*` / `<ns>.raw.*`) — caller-supplied
960
+ * causal references, e.g. the PR-A replay evidence
961
+ *
962
+ * `requiredPaths` is the required-evidence gate (design §33–§37): a listed
963
+ * path that ends up absent OR budget-truncated forces an observable fallback
964
+ * instead of a silently thin focused context. Pass an empty list (or omit it)
965
+ * when tier2 is genuinely optional.
966
+ */
967
+ async resolveContextInjectionAsync(params) {
968
+ const { taskId, manifest } = params;
969
+ if (!this.isContextManifestBudgetEnabled()) {
970
+ return { mode: 'disabled' };
971
+ }
972
+ const paths = declaredFields(manifest);
973
+ const requiredPaths = params.requiredPaths ?? [];
974
+ const summaryFields = buildAvailableMap(paths, params.predecessorContentJson);
975
+ const extras = [];
976
+ // Channel 2 — ancestry. Related namespaces are excluded explicitly so a
977
+ // related reference can never be mistaken for an ancestor stage
978
+ // (INV-LINEAGE-SCOPE, design §33).
979
+ const relatedNamespaces = (params.relatedSources ?? []).map((s) => s.namespace);
980
+ const { ancestry: rawAncestryPaths } = partitionTier2Paths(manifest.tier2, relatedNamespaces);
981
+ // Ancestor-declared SUMMARY paths travel the same walk as the raw ones:
982
+ // `readSummaryField` only ever reads the single loaded predecessor, so a
983
+ // manifest naming an ancestor further up the chain (the Evaluator's
984
+ // `scribe.*` / `dreamer.*` / `diagnostician.*`) resolves here or never.
985
+ // Related namespaces are excluded here too — the same INV-LINEAGE-SCOPE
986
+ // discipline partitionTier2Paths applies to tier2 must hold for tier0/1
987
+ // summary declarations (e.g. a repair manifest's `replay.summary.*`).
988
+ const relatedNamespaceSet = new Set(relatedNamespaces);
989
+ const summaryAncestryPaths = [...manifest.tier0, ...manifest.tier1].filter((fieldPath) => {
990
+ const parsed = parseContextPath(fieldPath);
991
+ return parsed !== null && parsed.layer === 'summary' && !relatedNamespaceSet.has(parsed.namespace);
992
+ });
993
+ const ancestryPaths = [...rawAncestryPaths, ...summaryAncestryPaths];
994
+ if (ancestryPaths.length > 0 && params.startArtifactId !== undefined) {
995
+ const lineage = new CandidateLineage({
996
+ artifacts: this.artifactStore,
997
+ tasks: {
998
+ getTaskById: async (id) => {
999
+ const task = await this.stateManager.getTask(id);
1000
+ return task === null ? null : { taskId: id, taskKind: task.taskKind };
1001
+ },
1002
+ },
1003
+ });
1004
+ const chain = await lineage.resolve(params.startArtifactId);
1005
+ if (!chain.ok) {
1006
+ // rc-9: corruption / store failure is observable, never a silent
1007
+ // "no tier2 today". Required evidence cannot be served without it.
1008
+ this.emitEvent('context_lineage_unavailable', taskId, {
1009
+ runnerKind: manifest.runnerKind,
1010
+ manifestId: manifest.manifestId,
1011
+ errorKind: chain.error.kind,
1012
+ detail: chain.error.detail,
1013
+ fallback: 'full_predecessor_injection',
1014
+ nextAction: 'verify_durable_artifact_ancestry_before_tier2_resolution',
1015
+ });
1016
+ if (requiredPaths.length > 0) {
1017
+ return { mode: 'fallback', reason: 'lineage_unavailable', unresolvedRequired: [...requiredPaths] };
1018
+ }
1019
+ }
1020
+ else {
1021
+ extras.push(resolveAncestryPaths(ancestryPaths, toRawStageSources(chain.value.nodes)));
1022
+ }
1023
+ }
1024
+ // Channel 3 — related (causal) references. Never ancestry: a related source
1025
+ // is supplied explicitly by the caller and is not part of the lineage walk.
1026
+ if (params.relatedSources !== undefined && params.relatedSources.length > 0) {
1027
+ extras.push(resolveRelatedPaths(paths, params.relatedSources));
1028
+ }
1029
+ const available = mergeContextFields(summaryFields, extras);
1030
+ return this.runResolveInjection({ taskId, manifest, available, requiredPaths });
1031
+ }
1032
+ /**
1033
+ * Allocation + information-floor core shared by both variants (design
1034
+ * §6.2.2). Allocates, emits the Layer 1 events, then applies PR B's
1035
+ * required-evidence gate before reporting `focused`.
1036
+ */
1037
+ runResolveInjection(params) {
1038
+ const { taskId, manifest, available, requiredPaths } = params;
952
1039
  const emit = (event) => {
953
1040
  if (event.type === 'manifest_resolution_insufficient') {
954
1041
  this.emitEvent('manifest_resolution_insufficient', taskId, {
@@ -972,10 +1059,29 @@ export class BasePeerRunner {
972
1059
  }
973
1060
  };
974
1061
  const result = resolveInjection(manifest, available, emit);
1062
+ // Required-evidence gate (design §33–§37): the allocation can look healthy
1063
+ // while a caller-declared required field is absent OR was dropped by the
1064
+ // budget. That is exactly the "Stage2 enabled + raw silently absent" hole —
1065
+ // it degrades observably, never becomes a thinner prompt.
1066
+ const unresolvedRequired = findUnresolvedRequiredPaths({
1067
+ required: requiredPaths,
1068
+ absent: result.allocated.absent,
1069
+ truncated: result.allocated.truncated,
1070
+ });
1071
+ if (unresolvedRequired.length > 0) {
1072
+ this.emitEvent('required_context_evidence_unresolved', taskId, {
1073
+ runnerKind: manifest.runnerKind,
1074
+ manifestId: manifest.manifestId,
1075
+ requiredPaths: unresolvedRequired,
1076
+ fallback: 'full_predecessor_injection',
1077
+ nextAction: 'verify_durable_ancestry_or_related_reference_availability',
1078
+ });
1079
+ return { mode: 'fallback', reason: 'required_evidence_unresolved', unresolvedRequired };
1080
+ }
975
1081
  if (result.kind === 'focused') {
976
1082
  return { mode: 'focused', fields: result.allocated.fields };
977
1083
  }
978
- return { mode: 'fallback' };
1084
+ return { mode: 'fallback', reason: result.reason, unresolvedRequired: [] };
979
1085
  }
980
1086
  // ── Agent draft injection (Task 12) ────────────────────────────────────────
981
1087
  /**