immune-brain 5.1.0 → 5.1.1

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 (34) hide show
  1. package/package.json +1 -1
  2. package/plugins/immune-brain/.claude-plugin/plugin.json +1 -1
  3. package/plugins/immune-brain/.pi-extension/imm-canary-work.ts +17 -5
  4. package/plugins/immune-brain/.pi-extension/imm-unattended-batch.ts +165 -0
  5. package/plugins/immune-brain/.pi-extension/pi-canary-assurance-progression.ts +66 -3
  6. package/plugins/immune-brain/agents/immune-brain-reviewer.md +11 -1
  7. package/plugins/immune-brain/dist/claude/mcp-server.mjs +542 -79
  8. package/plugins/immune-brain/dist/docs/reference/subagent-dispatch-protocol.md +8 -6
  9. package/plugins/immune-brain/dist/imm-planner.md +4 -1
  10. package/plugins/immune-brain/dist/role-prompts/code-review.md +10 -0
  11. package/plugins/immune-brain/runtime/assurance/coordinator.ts +22 -4
  12. package/plugins/immune-brain/runtime/assurance/review_mediation.ts +107 -0
  13. package/plugins/immune-brain/runtime/assurance/verdict_authority.ts +3 -0
  14. package/plugins/immune-brain/runtime/claude/interaction.ts +10 -0
  15. package/plugins/immune-brain/runtime/claude/kernel_ports.ts +89 -54
  16. package/plugins/immune-brain/runtime/claude/mcp_server.ts +76 -25
  17. package/plugins/immune-brain/runtime/kernel/assurance_projection.ts +4 -1
  18. package/plugins/immune-brain/runtime/kernel/canary_application.ts +9 -2
  19. package/plugins/immune-brain/runtime/kernel/completion.ts +24 -1
  20. package/plugins/immune-brain/runtime/kernel/reducer.ts +15 -2
  21. package/plugins/immune-brain/runtime/kernel/spec_binding.ts +6 -0
  22. package/plugins/immune-brain/runtime/kernel/storage.ts +20 -4
  23. package/plugins/immune-brain/runtime/kernel/storage_paths.ts +33 -3
  24. package/plugins/immune-brain/runtime/kernel/types.ts +7 -0
  25. package/plugins/immune-brain/runtime/kernel/validation.ts +13 -2
  26. package/plugins/immune-brain/runtime/plugin_version.ts +1 -1
  27. package/plugins/immune-brain/runtime/prompts/code-review.md +10 -0
  28. package/plugins/immune-brain/runtime/role_prompt_bridge.ts +1 -1
  29. package/plugins/immune-brain/runtime/unattended/batch_disposition.ts +222 -0
  30. package/plugins/immune-brain/runtime/unattended/batch_lanes.ts +51 -14
  31. package/plugins/immune-brain/runtime/unattended/batch_preflight.ts +8 -12
  32. package/plugins/immune-brain/runtime/unattended/batch_reasons.ts +13 -1
  33. package/plugins/immune-brain/runtime/unattended/batch_runner.ts +2 -0
  34. package/plugins/immune-brain/runtime/unattended/batch_state.ts +44 -6
@@ -26,7 +26,7 @@ import {
26
26
  type BackendClaim,
27
27
  } from "./backend_claim";
28
28
  import { canonicalIntentHash } from "./intent";
29
- import { boundSpecPath, readBoundActiveSpec } from "./spec_binding";
29
+ import { assertValidSpecBinding, boundSpecPath, readBoundActiveSpec } from "./spec_binding";
30
30
  import { parseTaskRecord } from "./validation";
31
31
  import type { TaskIntentIdentityToken } from "./intent_token_registry";
32
32
  import {
@@ -208,6 +208,7 @@ export function createCanaryApplication(
208
208
  const current = readTaskRecordRaw(input.root, input.task_id);
209
209
  if (!current.record)
210
210
  throw new KernelInvariantError([`task ${input.task_id} has no TaskRecord v3`]);
211
+ assertValidSpecBinding(current.record.intent_snapshot);
211
212
  const workspace = readWorkspaceStateRaw(input.root);
212
213
  if (current.record.artifact_state === "frozen")
213
214
  return { revision: current.revision, record: current.record, workspace };
@@ -318,7 +319,13 @@ export function createCanaryApplication(
318
319
  const diffHash = asTaskDiffSnapshot((input.diffProvider ?? taskDeliveryIdentity)(input.root, snapshot.record)).diff_hash;
319
320
  if (operation.op === "stop" && !("capability" in operation))
320
321
  throw new KernelInvariantError(["stop requires user authority capability"]);
321
- const hasBoundSpec = boundSpecPath(snapshot.intent_snapshot) !== undefined;
322
+ // Only a capability-bound breaking revision may recover an invalid prior
323
+ // binding. Validate the replacement before any authority write.
324
+ if (operation.op === "approve_breaking_intent_revision") assertValidSpecBinding(operation.next_intent);
325
+ else assertValidSpecBinding(snapshot.intent_snapshot);
326
+ const hasBoundSpec = operation.op === "approve_breaking_intent_revision"
327
+ ? boundSpecPath(operation.next_intent) !== undefined
328
+ : boundSpecPath(snapshot.intent_snapshot) !== undefined;
322
329
  if (operation.op === "complete" && hasBoundSpec && snapshot.record.artifact_state !== "frozen")
323
330
  throw new KernelInvariantError(["complete requires frozen planning artifacts"]);
324
331
  const artifactTransition =
@@ -1,5 +1,5 @@
1
1
  import { classifyTaskRisk } from "./intent";
2
- import { archivePath, boundSpecPath } from "./spec_binding";
2
+ import { archivePath, boundSpecPath, inspectSpecBinding } from "./spec_binding";
3
3
  import type {
4
4
  ApprovalKind,
5
5
  CompletionDecision,
@@ -49,6 +49,8 @@ export function resolveProjectedRisk(
49
49
  intent: TaskIntentV1,
50
50
  changedPaths: readonly string[] = [],
51
51
  ): TaskIntentV1["risk"] {
52
+ // Invalid bindings have no trusted planning-path exclusions.
53
+ if (!inspectSpecBinding(intent).ok) return classifyTaskRisk(changedPaths, intent.risk);
52
54
  const excluded = ownSidecarPaths(intent);
53
55
  return classifyTaskRisk(
54
56
  changedPaths.filter((path) => !excluded.has(path)),
@@ -182,6 +184,27 @@ export function projectTask(
182
184
  currentIntentContentHash: string,
183
185
  changedPaths: readonly string[] = [],
184
186
  ): TaskProjectionV3 {
187
+ if (record.lifecycle === "active" && !inspectSpecBinding(intent).ok) {
188
+ assertKernelInvariantsV3(intent, record);
189
+ return {
190
+ contract: "assurance_kernel/projection/v3",
191
+ task_id: record.task_id,
192
+ intent_revision: intent.revision,
193
+ lifecycle: record.lifecycle,
194
+ artifact_state: record.artifact_state,
195
+ blocked: true,
196
+ next_obligation: "revise_intent",
197
+ complete: false,
198
+ fresh_acceptance_ids: [],
199
+ missing_acceptance_ids: intent.acceptance.map((item) => item.id),
200
+ stale_attestation_ids: record.attestations.map((item) => item.id),
201
+ missing_approval_kinds: REQUIRED_ATTESTATIONS[resolveProjectedRisk(intent, changedPaths)],
202
+ blocking_finding_ids: record.findings.filter((item) => item.kind === "blocking" && item.status !== "resolved").map((item) => item.id),
203
+ unresolved_user_decision_ids: record.findings.filter((item) => item.kind === "unresolved_user_decision" && item.status === "open").map((item) => item.id),
204
+ replan_required_ids: record.findings.filter((item) => item.kind === "replan_required" && item.status === "open").map((item) => item.id),
205
+ independence_violations: [],
206
+ };
207
+ }
185
208
  const decision = completionDecision(
186
209
  intent,
187
210
  record,
@@ -23,6 +23,7 @@ import {
23
23
  parseTaskRecord,
24
24
  } from "./validation";
25
25
  import { classifyIntentRevision, canonicalIntentHash } from "./intent";
26
+ import { assertValidSpecBinding } from "./spec_binding";
26
27
 
27
28
  const RISK_RANK: Record<TaskIntentV1["risk"], number> = {
28
29
  routine: 0,
@@ -431,15 +432,24 @@ export function reduceTask(
431
432
  const reviewRevision = approval.review_revision;
432
433
  if (reviewRevision && approval.kind !== "review")
433
434
  throw new KernelInvariantError(["review_revision is only valid on review approvals"]);
435
+ if (approval.reviewer_verdict_sha256 && approval.kind !== "review")
436
+ throw new KernelInvariantError(["reviewer_verdict_sha256 is only valid on review approvals"]);
434
437
  if (approval.kind === "review") {
435
438
  if (!reviewRevision)
436
439
  throw new KernelInvariantError(["v4 review approval requires review_revision"]);
437
440
  if (reviewRevision.base_head !== record.git_base_head)
438
441
  throw new KernelInvariantError(["review_revision.base_head must equal the Enrollment git_base_head"]);
439
442
  }
440
- const { review_revision: storedReviewRevision, ...approvalWithoutRevision } = approval;
443
+ // Re-emit the optional review-only fields in the strict parser's emission
444
+ // order so a written attestation stays byte-identical to its parse roundtrip.
445
+ const {
446
+ review_revision: storedReviewRevision,
447
+ advisory_findings: storedAdvisoryFindings,
448
+ reviewer_verdict_sha256: storedReviewerDigest,
449
+ ...approvalWithoutExtras
450
+ } = approval;
441
451
  record.attestations.push({
442
- ...approvalWithoutRevision,
452
+ ...approvalWithoutExtras,
443
453
  acceptance_results: approval.kind === "qa"
444
454
  ? record.intent_snapshot.acceptance.map((item) => ({
445
455
  acceptance_id: item.id,
@@ -448,12 +458,15 @@ export function reduceTask(
448
458
  }))
449
459
  : [],
450
460
  ...(storedReviewRevision ? { review_revision: storedReviewRevision } : {}),
461
+ ...(storedAdvisoryFindings ? { advisory_findings: storedAdvisoryFindings } : {}),
462
+ ...(storedReviewerDigest ? { reviewer_verdict_sha256: storedReviewerDigest } : {}),
451
463
  });
452
464
  appendHistory(record, action, from, approval.id, authorityAudit);
453
465
  break;
454
466
  }
455
467
  case "revise_intent":
456
468
  case "approve_breaking_intent_revision": {
469
+ assertValidSpecBinding(action.next_intent);
457
470
  if (record.lifecycle !== "active")
458
471
  throw new KernelInvariantError([
459
472
  `cannot revise intent while lifecycle is ${record.lifecycle}`,
@@ -57,6 +57,12 @@ export function readBoundActiveSpec(
57
57
  }
58
58
  }
59
59
 
60
+ /** Validate a candidate before it can replace enrolled authority. */
61
+ export function assertValidSpecBinding(intent: TaskIntentV1): void {
62
+ const binding = inspectSpecBinding(intent);
63
+ if (!binding.ok) throw new KernelInvariantError([binding.message]);
64
+ }
65
+
60
66
  export interface BoundSpec {
61
67
  active: string;
62
68
  archive: string;
@@ -53,6 +53,7 @@ import {
53
53
  FILE_STORE_CLAIM_RELATIVE,
54
54
  FILE_STORE_TRANSACTIONS_RELATIVE,
55
55
  FILE_STORE_WORKSPACE_RELATIVE,
56
+ inspectRetiredStateResidue,
56
57
  stateDatabasePath,
57
58
  } from "./storage_paths";
58
59
  import { canonicalRecordHash } from "./reducer";
@@ -262,7 +263,7 @@ function isRetiredFileProvablySuperseded(
262
263
  /**
263
264
  * Refuse mutation while the retired `.imm/state/*.json` file store (or the
264
265
  * pre-cutover `.imm/tasks` layout) still holds authority. The check is bounded
265
- * to `existsSync` paths so it can run on every locked mutation.
266
+ * to retired paths so it can run on every locked mutation.
266
267
  */
267
268
  function assertNoRetiredFileStore(
268
269
  root: string,
@@ -270,11 +271,19 @@ function assertNoRetiredFileStore(
270
271
  taskId?: string | null,
271
272
  ): void {
272
273
  const canonical = canonicalRoot(root);
274
+ let residue: ReturnType<typeof inspectRetiredStateResidue>;
275
+ try {
276
+ residue = inspectRetiredStateResidue(canonical);
277
+ } catch (error) {
278
+ throw new KernelStoreSecurityError(
279
+ `retired file-store residue is invalid: ${error instanceof Error ? error.message : String(error)}`,
280
+ );
281
+ }
273
282
  // Real authority in the retired store: must be imported, never ignored.
274
283
  const retired: Array<[string, string]> = [
275
284
  [".imm/tasks", "pre-cutover task store"],
276
285
  [".imm/workspace.json", "pre-cutover workspace owner"],
277
- [".imm/state/tasks", "task records"],
286
+ ...(residue.task_entries.length > 0 ? [[".imm/state/tasks", "task records"] as [string, string]] : []),
278
287
  ];
279
288
  for (const [path, label] of retired) {
280
289
  if (existsSync(resolve(canonical, path)))
@@ -293,6 +302,7 @@ function assertNoRetiredFileStore(
293
302
  ];
294
303
  for (const [path, label] of derived) {
295
304
  const full = resolve(canonical, path);
305
+ if (path === FILE_STORE_WORKSPACE_RELATIVE && residue.workspace_owner === null) continue;
296
306
  if (!existsSync(full)) continue;
297
307
  if (db === undefined || typeof taskId !== "string" || taskId.length === 0)
298
308
  throw new KernelStoreSecurityError(
@@ -325,10 +335,16 @@ function retiredFileStoreConflict(
325
335
  taskId: string | null,
326
336
  ): string | null {
327
337
  const canonical = canonicalRoot(root);
338
+ let residue: ReturnType<typeof inspectRetiredStateResidue>;
339
+ try {
340
+ residue = inspectRetiredStateResidue(canonical);
341
+ } catch (error) {
342
+ return `retired file-store residue is invalid: ${error instanceof Error ? error.message : String(error)}`;
343
+ }
328
344
  const authority: Array<[string, string]> = [
329
345
  [".imm/tasks", "pre-cutover task store"],
330
346
  [".imm/workspace.json", "pre-cutover workspace owner"],
331
- [".imm/state/tasks", "task records"],
347
+ ...(residue.task_entries.length > 0 ? [[".imm/state/tasks", "task records"] as [string, string]] : []),
332
348
  ];
333
349
  for (const [path, label] of authority)
334
350
  if (existsSync(resolve(canonical, path)))
@@ -340,7 +356,7 @@ function retiredFileStoreConflict(
340
356
  [FILE_STORE_WORKSPACE_RELATIVE, "workspace owner"],
341
357
  ];
342
358
  for (const [path, label] of derived)
343
- if (existsSync(resolve(canonical, path)))
359
+ if ((path !== FILE_STORE_WORKSPACE_RELATIVE || residue.workspace_owner !== null) && existsSync(resolve(canonical, path)))
344
360
  return `retired file-store authority is present (${label}: ${path}); import it with the supported migration before mutating this worktree`;
345
361
  }
346
362
  const transactions = resolve(canonical, FILE_STORE_TRANSACTIONS_RELATIVE);
@@ -382,6 +382,36 @@ function readSmallFile(root: string, relativePath: string): string | null {
382
382
  }
383
383
  }
384
384
 
385
+ /** Shared, bounded classification of the two potentially inert retired paths. */
386
+ export function inspectRetiredStateResidue(root: string): {
387
+ task_entries: string[];
388
+ workspace_owner: string | null;
389
+ } {
390
+ const tasksStatus = entryStatus(root, FILE_STORE_TASKS_RELATIVE);
391
+ if (tasksStatus !== "absent" && tasksStatus !== "directory")
392
+ throw new Error(`${FILE_STORE_TASKS_RELATIVE} is not a regular directory`);
393
+ const entries = tasksStatus === "absent" ? [] : listEntries(root, FILE_STORE_TASKS_RELATIVE);
394
+ if (entries === null) throw new Error(`${FILE_STORE_TASKS_RELATIVE} is unreadable`);
395
+ const workspaceStatus = entryStatus(root, FILE_STORE_WORKSPACE_RELATIVE);
396
+ let owner: string | null = null;
397
+ if (workspaceStatus !== "absent") {
398
+ if (workspaceStatus !== "file")
399
+ throw new Error(`${FILE_STORE_WORKSPACE_RELATIVE} is not a regular file`);
400
+ const content = readSmallFile(root, FILE_STORE_WORKSPACE_RELATIVE);
401
+ if (content === null) throw new Error(`${FILE_STORE_WORKSPACE_RELATIVE} is unreadable`);
402
+ const raw = JSON.parse(content);
403
+ if (
404
+ raw === null || typeof raw !== "object" || Array.isArray(raw) ||
405
+ raw.contract !== "assurance_kernel/workspace/v1" ||
406
+ (raw.current_working !== null &&
407
+ (typeof raw.current_working !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(raw.current_working))) ||
408
+ (raw.current_working === null && Object.keys(raw).some((key) => !["contract", "current_working"].includes(key)))
409
+ ) throw new Error(`${FILE_STORE_WORKSPACE_RELATIVE} has invalid workspace content`);
410
+ owner = raw.current_working;
411
+ }
412
+ return { task_entries: entries, workspace_owner: owner };
413
+ }
414
+
385
415
  interface OldLayoutFacts {
386
416
  old_authority_present: boolean;
387
417
  blocked_active: boolean;
@@ -637,6 +667,7 @@ function inspectFileStoreLayout(root: string): FileStoreFacts {
637
667
  if (stateStatus === "symlink" || stateStatus === "other")
638
668
  throw new Error(`${STATE_RELATIVE} is ${stateStatus}`);
639
669
  if (stateStatus !== "directory") return facts;
670
+ const residue = inspectRetiredStateResidue(root);
640
671
  for (const entry of listEntries(root, STATE_RELATIVE) ?? []) {
641
672
  const full = `${STATE_RELATIVE}/${entry}`;
642
673
  const status = entryStatus(root, full);
@@ -667,13 +698,12 @@ function inspectFileStoreLayout(root: string): FileStoreFacts {
667
698
  continue;
668
699
  }
669
700
  if (full === FILE_STORE_WORKSPACE_RELATIVE) {
670
- const owner = readJsonField(root, full, "current_working");
671
- if (typeof owner === "string" && owner.length > 0) facts.blocked_active = true;
701
+ if (residue.workspace_owner !== null) facts.blocked_active = true;
672
702
  continue;
673
703
  }
674
704
  throw new Error(`unknown file under ${STATE_RELATIVE}: ${entry}`);
675
705
  }
676
- for (const entry of listEntries(root, FILE_STORE_TASKS_RELATIVE) ?? []) {
706
+ for (const entry of residue.task_entries) {
677
707
  const full = `${FILE_STORE_TASKS_RELATIVE}/${entry}`;
678
708
  const status = entryStatus(root, full);
679
709
  if (status === "symlink" || status === "other")
@@ -187,6 +187,13 @@ export interface TaskApprovalV2 {
187
187
  review_revision?: ReviewRevisionIdentityV1;
188
188
  /** Legal only on a review attestation, alongside its revision identity. */
189
189
  advisory_findings?: ReviewAdvisoryFindingV1[];
190
+ /**
191
+ * ADR 0017: sha256 over the reviewer's own result bytes as observed by the
192
+ * host, bound at submission so post-hoc audit can prove the persisted
193
+ * verdict equals what the reviewer produced. Legal only on a review
194
+ * attestation; emitted only when present so legacy records stay stable.
195
+ */
196
+ reviewer_verdict_sha256?: string;
190
197
  }
191
198
 
192
199
  export interface ReviewRevisionIdentityV1 {
@@ -314,7 +314,7 @@ export function parseApprovalV2(
314
314
  const item = objectAt(value, `record.approvals[${index}]`, violations);
315
315
  rejectUnknown(
316
316
  item,
317
- ["id", "kind", "authority_role", "task_revision", "intent_content_hash", "diff_hash", "actor_id", "summary", "advisory_findings",
317
+ ["id", "kind", "authority_role", "task_revision", "intent_content_hash", "diff_hash", "actor_id", "summary", "advisory_findings", "reviewer_verdict_sha256",
318
318
  ...(allowReviewRevision ? ["review_revision"] : [])],
319
319
  `record.approvals[${index}]`,
320
320
  violations,
@@ -365,6 +365,9 @@ export function parseApprovalV2(
365
365
  ),
366
366
  }
367
367
  : {}),
368
+ ...(item.reviewer_verdict_sha256 !== undefined
369
+ ? { reviewer_verdict_sha256: stringAt(item.reviewer_verdict_sha256, `record.approvals[${index}].reviewer_verdict_sha256`, violations) }
370
+ : {}),
368
371
  };
369
372
  }
370
373
 
@@ -419,7 +422,7 @@ function parseAttestationV3(
419
422
  const item = objectAt(value, path, violations);
420
423
  rejectUnknown(
421
424
  item,
422
- ["id", "kind", "authority_role", "task_revision", "intent_content_hash", "diff_hash", "actor_id", "summary", "acceptance_results", "advisory_findings",
425
+ ["id", "kind", "authority_role", "task_revision", "intent_content_hash", "diff_hash", "actor_id", "summary", "acceptance_results", "advisory_findings", "reviewer_verdict_sha256",
423
426
  ...(allowReviewRevision ? ["review_revision"] : [])],
424
427
  path,
425
428
  violations,
@@ -462,6 +465,13 @@ function parseAttestationV3(
462
465
  );
463
466
  if (advisoryFindings !== undefined && kind !== "review")
464
467
  violations.push(`${path}.advisory_findings is only valid on review attestations`);
468
+ const reviewerVerdictSha256 = item.reviewer_verdict_sha256 === undefined
469
+ ? undefined
470
+ : stringAt(item.reviewer_verdict_sha256, `${path}.reviewer_verdict_sha256`, violations);
471
+ if (reviewerVerdictSha256 !== undefined && kind !== "review")
472
+ violations.push(`${path}.reviewer_verdict_sha256 is only valid on review attestations`);
473
+ if (reviewerVerdictSha256 !== undefined && !SHA256_HEX.test(reviewerVerdictSha256))
474
+ violations.push(`${path}.reviewer_verdict_sha256 must be sha256:<64 hex>`);
465
475
  return {
466
476
  id: stringAt(item.id, `${path}.id`, violations),
467
477
  kind,
@@ -474,6 +484,7 @@ function parseAttestationV3(
474
484
  acceptance_results: acceptanceResults,
475
485
  ...(reviewRevision ? { review_revision: reviewRevision } : {}),
476
486
  ...(advisoryFindings !== undefined ? { advisory_findings: advisoryFindings } : {}),
487
+ ...(reviewerVerdictSha256 !== undefined ? { reviewer_verdict_sha256: reviewerVerdictSha256 } : {}),
477
488
  };
478
489
  }
479
490
 
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/plugin_versioning.ts from the root package.json.
2
- export const PLUGIN_VERSION = "5.1.0" as const;
2
+ export const PLUGIN_VERSION = "5.1.1" as const;
@@ -53,6 +53,16 @@ seam, or a seam silently replaced by a different one, is a finding carrying
53
53
  named, its absence is not a finding: candidates written before this rule carries
54
54
  no defect for lacking one.
55
55
 
56
+ Before pass, enumerate the immutable change set and read each complete per-file
57
+ diff, including deletions. Page bounded reads until every hunk is visible; a
58
+ truncated aggregate output or summary is incomplete coverage. Trace changed
59
+ high-risk behavior through its callers and state owner, and inspect a concrete
60
+ negative case against the embedded acceptance. If immutable evidence remains
61
+ unavailable or incomplete, report the concrete acceptance coverage gap in a
62
+ rework finding with required evidence. `inspected_paths` declares coverage; it
63
+ does not itself prove tool reading. Judge quality by evidence, not elapsed time
64
+ or tool-call count.
65
+
56
66
  A required check that is skipped, that matches zero tests, or whose prerequisite
57
67
  is absent does not prove the acceptance; do not accept it as evidence. Full
58
68
  suite coverage reported at a coarse pass count is not per-invariant evidence.
@@ -233,5 +233,5 @@ export const STATIC_REVIEW_RULES = [
233
233
  * to a per-dispatch prompt, because they describe the dispatch itself.
234
234
  */
235
235
  export const REVIEWER_DISPATCH_RULES = [
236
- "A dispatched reviewer is never continued or re-prompted, including through SendMessage. The reserved prompt is dispatched verbatim. A blocked `submit_review` is recovered only through its returned `recovery_action`.",
236
+ "A dispatched reviewer is never continued or re-prompted, including through SendMessage. The reserved prompt is dispatched verbatim. The host binds this reviewer's final result bytes to the reservation, so a Parent may submit them without transcribing them. A blocked `submit_review` is recovered only through its returned `recovery_action`.",
237
237
  ] as const;
@@ -0,0 +1,222 @@
1
+ // Authority-backed disposition for a batch the plan moved past.
2
+ //
3
+ // A batch whose plan changed can neither reconfirm (reconfirmation is eligible
4
+ // only with zero recorded commits) nor continue (its authorization cannot
5
+ // execute the revised plan). Before this module the only exits were editing or
6
+ // deleting the state file by hand, which destroyed the evidence of what the
7
+ // batch had actually delivered — exactly what happened to the batch retired
8
+ // during the parallel-lane Initiative, whose record is no longer on disk.
9
+ //
10
+ // Retiring is one explicit literal-user decision. It writes the record to the
11
+ // terminal `superseded` state under the Kernel store lock, preserves every
12
+ // child state, commit and the batch branch, and grants no handoff: children
13
+ // this batch never executed carry no commit, no batch trailer and no approval,
14
+ // and nothing here infers their delivery from a retired record. The old
15
+ // authorization is never reused for the revised plan; a later batch starts
16
+ // under its own fresh authorization.
17
+ //
18
+ // Authority shape, deliberately: the literal-user native confirmation plus a
19
+ // locked expected-byte check that the record did not move while the gate was
20
+ // open. No Batch Authorization capability is minted, because retiring a record
21
+ // consumes no child and enrolls nothing — the capability exists to authorize
22
+ // child consumption, and minting one here would be ceremony without a property.
23
+ import { readSecureProjectBytes } from "../kernel/storage";
24
+ import { batchStatePath } from "../kernel/storage_paths";
25
+ import { batchReason, type BatchReason } from "./batch_reasons";
26
+ import { findExistingActiveBatch, findSettledBatchRecord, type BatchGateDecision } from "./batch_preflight";
27
+ import {
28
+ isTerminalBatchState,
29
+ replaceAnyBatchRunState,
30
+ writeBatchRunReport,
31
+ type AnyBatchRunStateRecord,
32
+ type BatchLaneRunReport,
33
+ type BatchRunReport,
34
+ type BatchRunState,
35
+ } from "./batch_state";
36
+
37
+ /** Child states whose Kernel run is still live; a live run settles on its own. */
38
+ const SERIAL_IN_FLIGHT: ReadonlySet<string> = new Set(["enrolled", "settled"]);
39
+ const LANE_IN_FLIGHT: ReadonlySet<string> = new Set(["lane_admitted", "enrolled", "settled", "lane_committed"]);
40
+
41
+ /** Evidence-only child projection for the gate; never an execution readiness. */
42
+ export interface StaleBatchChildEvidence {
43
+ task_id: string;
44
+ slice_id: string;
45
+ state: string;
46
+ commit: string | null;
47
+ lane_branch: string | null;
48
+ }
49
+
50
+ /** The exact record identity the literal user is asked to retire. */
51
+ export interface StaleBatchFacts {
52
+ batch_id: string;
53
+ initiative_slug: string;
54
+ batch_state: BatchRunState;
55
+ plan_digest: string;
56
+ branch: string;
57
+ base_head: string;
58
+ confirmation_time: string;
59
+ /** Commits this batch itself produced, in child order. */
60
+ recorded_commits: string[];
61
+ children: StaleBatchChildEvidence[];
62
+ }
63
+
64
+ export type StaleBatchLookup =
65
+ /** No active record for this Initiative. */
66
+ | { kind: "none" }
67
+ | { kind: "corrupt"; path: string }
68
+ | { kind: "terminal"; batch_id: string }
69
+ | { kind: "in_flight"; batch_id: string; task_id: string }
70
+ | { kind: "retirable"; record: AnyBatchRunStateRecord; facts: StaleBatchFacts };
71
+
72
+ const RETIRE_REASON =
73
+ "Retired by an explicit literal-user disposition: the batch plan moved past this record, so its authorization could neither reconfirm nor continue. " +
74
+ "Recorded child commits, child states and the batch branch are preserved as evidence. " +
75
+ "Children this batch never executed carry no commit, no batch trailer and no approval; nothing infers their delivery from this record.";
76
+
77
+ const RETIRE_NEXT_ACTION =
78
+ "The Initiative has no active batch. Run each remaining child with imm-run under its own authorization, or start a new batch for this Initiative after checking out its batch branch.";
79
+
80
+ function childEvidenceOf(record: AnyBatchRunStateRecord): StaleBatchChildEvidence[] {
81
+ if (record.contract === "assurance_kernel/batch_run_state/v2")
82
+ return record.children.map((child) => ({
83
+ task_id: child.task_id,
84
+ slice_id: child.slice_id,
85
+ state: child.state,
86
+ commit: child.commit,
87
+ lane_branch: child.lane?.branch ?? null,
88
+ }));
89
+ return record.children.map((child) => ({
90
+ task_id: child.task_id,
91
+ slice_id: child.slice_id,
92
+ state: child.state,
93
+ commit: child.commit,
94
+ lane_branch: null,
95
+ }));
96
+ }
97
+
98
+ function inFlightChildOf(record: AnyBatchRunStateRecord): { task_id: string } | null {
99
+ const inFlight = record.contract === "assurance_kernel/batch_run_state/v2" ? LANE_IN_FLIGHT : SERIAL_IN_FLIGHT;
100
+ return record.children.find((child) => inFlight.has(child.state)) ?? null;
101
+ }
102
+
103
+ /**
104
+ * The Initiative's active batch record as retirement evidence, or why it cannot
105
+ * be retired. Read-only; a terminal record is not a batch to dispose.
106
+ */
107
+ export function readStaleBatchLookup(root: string, initiativeSlug: string): StaleBatchLookup {
108
+ const found = findExistingActiveBatch(root, initiativeSlug);
109
+ if (found === null) {
110
+ const settled = findSettledBatchRecord(root, initiativeSlug);
111
+ if (settled) return { kind: "terminal", batch_id: settled.batch_id };
112
+ return { kind: "none" };
113
+ }
114
+ if (found.corrupt) return { kind: "corrupt", path: found.path };
115
+ const record = found.record;
116
+ if (isTerminalBatchState(record.batch_state)) return { kind: "terminal", batch_id: record.batch_id };
117
+ const inFlight = inFlightChildOf(record);
118
+ if (inFlight) return { kind: "in_flight", batch_id: record.batch_id, task_id: inFlight.task_id };
119
+ return {
120
+ kind: "retirable",
121
+ record,
122
+ facts: {
123
+ batch_id: record.batch_id,
124
+ initiative_slug: record.initiative_slug,
125
+ batch_state: record.batch_state,
126
+ plan_digest: record.plan_digest,
127
+ branch: record.branch ?? `imm/${record.initiative_slug}`,
128
+ base_head: record.base_head,
129
+ confirmation_time: record.confirmation_time,
130
+ recorded_commits: [...record.commits],
131
+ children: childEvidenceOf(record),
132
+ },
133
+ };
134
+ }
135
+
136
+ export type RetireStaleBatchOutcome<HostRejection> =
137
+ | {
138
+ outcome: "retired";
139
+ batch_id: string;
140
+ record: AnyBatchRunStateRecord;
141
+ report: BatchRunReport | BatchLaneRunReport;
142
+ }
143
+ | { outcome: "rejected"; rejection: BatchReason }
144
+ | { outcome: "host_rejection"; value: HostRejection };
145
+
146
+ /**
147
+ * Retire one Initiative's active batch record after a literal-user gate. The
148
+ * gate receives the record's own evidence; a declined, cancelled or failed
149
+ * interaction writes nothing. Between the gate and the write the record is
150
+ * re-read and must be byte-identical, so a record that moved while the gate was
151
+ * open is never retired under a stale decision.
152
+ */
153
+ export async function retireStaleBatch<HostRejection>(options: {
154
+ root: string;
155
+ initiative_slug: string;
156
+ now: string;
157
+ gate: (facts: StaleBatchFacts) => Promise<BatchGateDecision<HostRejection>>;
158
+ }): Promise<RetireStaleBatchOutcome<HostRejection>> {
159
+ const { root, initiative_slug: initiativeSlug, now } = options;
160
+ const lookup = readStaleBatchLookup(root, initiativeSlug);
161
+ if (lookup.kind === "none")
162
+ return { outcome: "rejected", rejection: batchReason("stale_batch_absent", `Initiative ${initiativeSlug} has no active batch`) };
163
+ if (lookup.kind === "corrupt")
164
+ return { outcome: "rejected", rejection: batchReason("batch_state_unreadable", lookup.path) };
165
+ if (lookup.kind === "terminal")
166
+ return {
167
+ outcome: "rejected",
168
+ rejection: batchReason("stale_batch_absent", `batch ${lookup.batch_id} already reached a terminal state`),
169
+ };
170
+ if (lookup.kind === "in_flight")
171
+ return {
172
+ outcome: "rejected",
173
+ rejection: batchReason("stale_batch_in_flight", `batch ${lookup.batch_id}, child ${lookup.task_id}`),
174
+ };
175
+
176
+ const { record, facts } = lookup;
177
+ const expected = readSecureProjectBytes(root, batchStatePath(record.batch_id));
178
+ const decision = await options.gate(facts);
179
+ if (decision.kind === "host_rejection") return { outcome: "host_rejection", value: decision.value };
180
+ // A decline or a cancel is the Host's own envelope (batchReason
181
+ // confirmation_declined / confirmation_cancelled), so it arrives here as a
182
+ // host_rejection: nothing is written and the record stays parked.
183
+
184
+ // Confirmation cannot adopt a record that moved while the gate was open.
185
+ if (!readSecureProjectBytes(root, batchStatePath(record.batch_id)).equals(expected))
186
+ return { outcome: "rejected", rejection: batchReason("plan_changed", record.batch_id) };
187
+
188
+ // Children, commits and branch are carried over untouched: the disposition
189
+ // records what the batch did and did not do, and invents neither.
190
+ const retired: AnyBatchRunStateRecord = { ...record, batch_state: "superseded" };
191
+ const stored = replaceAnyBatchRunState(root, expected, retired, () => {
192
+ if (!readSecureProjectBytes(root, batchStatePath(record.batch_id)).equals(expected))
193
+ throw new Error("batch state changed before the disposition was applied");
194
+ });
195
+ const report =
196
+ stored.contract === "assurance_kernel/batch_run_state/v2"
197
+ ? writeBatchRunReport(root, {
198
+ contract: "assurance_kernel/batch_run_report/v1",
199
+ batch_id: stored.batch_id,
200
+ initiative_slug: stored.initiative_slug,
201
+ batch_state: stored.batch_state,
202
+ max_parallel: stored.max_parallel,
203
+ children: stored.children,
204
+ commits: stored.commits,
205
+ reason: RETIRE_REASON,
206
+ handoffs: [],
207
+ next_action: RETIRE_NEXT_ACTION,
208
+ created_at: now,
209
+ } satisfies BatchLaneRunReport)
210
+ : writeBatchRunReport(root, {
211
+ contract: "assurance_kernel/batch_run_report/v1",
212
+ batch_id: stored.batch_id,
213
+ initiative_slug: stored.initiative_slug,
214
+ batch_state: stored.batch_state,
215
+ children: stored.children,
216
+ commits: stored.commits,
217
+ reason: RETIRE_REASON,
218
+ next_action: RETIRE_NEXT_ACTION,
219
+ created_at: now,
220
+ } satisfies BatchRunReport);
221
+ return { outcome: "retired", batch_id: stored.batch_id, record: stored, report };
222
+ }