@sema-agent/core 7.62.0 → 7.63.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 (193) hide show
  1. package/CHANGELOG.md +528 -0
  2. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  3. package/dist/agents/subagent-transcript-placement.js +14 -0
  4. package/dist/agents/subagent.js +82 -51
  5. package/dist/brain/route-adjudicator.js +9 -4
  6. package/dist/core/approval-object.js +1 -1
  7. package/dist/core/arg-summary.js +1 -1
  8. package/dist/core/ask-question.d.ts +2 -2
  9. package/dist/core/canonical-json.d.ts +23 -13
  10. package/dist/core/canonical-json.js +4 -4
  11. package/dist/core/checkpoint-queries.d.ts +47 -4
  12. package/dist/core/checkpoint-queries.js +36 -16
  13. package/dist/core/checkpoint-requirements.d.ts +3 -3
  14. package/dist/core/checkpoint-requirements.js +2 -1
  15. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  16. package/dist/core/checkpoint-row-verdict.js +22 -2
  17. package/dist/core/checkpoint-store.d.ts +23 -10
  18. package/dist/core/checkpoint-store.js +45 -4
  19. package/dist/core/compliance.d.ts +6 -2
  20. package/dist/core/compliance.js +3 -3
  21. package/dist/core/engine-attestation.d.ts +1 -1
  22. package/dist/core/engine-notice.d.ts +19 -4
  23. package/dist/core/git-worktree-env.d.ts +62 -3
  24. package/dist/core/git-worktree-env.js +91 -30
  25. package/dist/core/governance-codes.d.ts +7 -3
  26. package/dist/core/governance-codes.js +13 -3
  27. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  28. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  29. package/dist/core/memory-engine/consolidation.d.ts +73 -10
  30. package/dist/core/memory-engine/consolidation.js +167 -11
  31. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  32. package/dist/core/memory-engine/data-plane.js +11 -6
  33. package/dist/core/memory-engine/delegation-settlement.d.ts +37 -35
  34. package/dist/core/memory-engine/delegation-settlement.js +53 -59
  35. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  36. package/dist/core/memory-engine/dual-root.js +9 -5
  37. package/dist/core/memory-engine/engine.d.ts +98 -35
  38. package/dist/core/memory-engine/engine.js +477 -380
  39. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  40. package/dist/core/memory-engine/entry-scan.js +3 -0
  41. package/dist/core/memory-engine/file-backend.d.ts +29 -3
  42. package/dist/core/memory-engine/file-backend.js +66 -35
  43. package/dist/core/memory-engine/index.d.ts +7 -7
  44. package/dist/core/memory-engine/index.js +6 -6
  45. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  46. package/dist/core/memory-engine/landing-admission.js +3 -3
  47. package/dist/core/memory-engine/layout.d.ts +121 -45
  48. package/dist/core/memory-engine/layout.js +252 -102
  49. package/dist/core/memory-engine/memory-backend-contract.d.ts +19 -1
  50. package/dist/core/memory-engine/memory-backend-contract.js +320 -0
  51. package/dist/core/memory-engine/memory-deployment.d.ts +31 -8
  52. package/dist/core/memory-engine/memory-deployment.js +26 -12
  53. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  54. package/dist/core/memory-engine/scope-contract.js +68 -19
  55. package/dist/core/memory-engine/session-write-home.d.ts +3 -1
  56. package/dist/core/memory-engine/session-write-home.js +1 -1
  57. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  58. package/dist/core/memory-engine/sync-client.js +7 -0
  59. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  60. package/dist/core/memory-engine/sync-report.js +6 -2
  61. package/dist/core/memory-engine/tools.d.ts +2 -2
  62. package/dist/core/memory-engine/tools.js +10 -10
  63. package/dist/core/memory-engine/types.d.ts +118 -19
  64. package/dist/core/memory-engine/types.js +1 -0
  65. package/dist/core/memory.js +15 -6
  66. package/dist/core/mods/stations.d.ts +20 -1
  67. package/dist/core/mods/stations.js +21 -2
  68. package/dist/core/park-selfcheck.js +2 -2
  69. package/dist/core/pause-registry.d.ts +2 -0
  70. package/dist/core/pause-registry.js +3 -0
  71. package/dist/core/permission-rule-consent.d.ts +10 -3
  72. package/dist/core/permission-rule-consent.js +37 -24
  73. package/dist/core/permission-rule-store.d.ts +35 -1
  74. package/dist/core/permission-rule-store.js +27 -8
  75. package/dist/core/read-only-shell.js +3 -2
  76. package/dist/core/redaction-marks.d.ts +8 -0
  77. package/dist/core/redaction-marks.js +6 -0
  78. package/dist/core/remote-env.d.ts +12 -1
  79. package/dist/core/remote-env.js +3 -0
  80. package/dist/core/runner/child-tree.d.ts +29 -3
  81. package/dist/core/runner/child-tree.js +39 -16
  82. package/dist/core/runner/contracts.d.ts +18 -9
  83. package/dist/core/runner/gate-exit.js +2 -2
  84. package/dist/core/runner/inherited-ask-grants.js +1 -1
  85. package/dist/core/runner/memory-consolidation-driver.d.ts +6 -3
  86. package/dist/core/runner/memory-consolidation-driver.js +4 -4
  87. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  88. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  89. package/dist/core/runner/person-path-rows.d.ts +8 -3
  90. package/dist/core/runner/person-path-rows.js +5 -1
  91. package/dist/core/runner/placement-fence.d.ts +12 -0
  92. package/dist/core/runner/placement-fence.js +20 -6
  93. package/dist/core/runner/prepare-ask-lane.js +2 -2
  94. package/dist/core/runner/prepare-caps-and-workflow.d.ts +4 -1
  95. package/dist/core/runner/prepare-caps-and-workflow.js +5 -2
  96. package/dist/core/runner/prepare-execution-env.js +17 -6
  97. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  98. package/dist/core/runner/prepare-hands-readface.js +4 -3
  99. package/dist/core/runner/prepare-inherited-gate.d.ts +10 -8
  100. package/dist/core/runner/prepare-inherited-gate.js +8 -4
  101. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  102. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  103. package/dist/core/runner/prepare-memory.d.ts +3 -2
  104. package/dist/core/runner/prepare-memory.js +28 -20
  105. package/dist/core/runner/prepare-park-ask.js +4 -3
  106. package/dist/core/runner/prepare-task.js +15 -12
  107. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  108. package/dist/core/runner/run-leg.js +1 -1
  109. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  110. package/dist/core/runner/terminal-account.js +1 -1
  111. package/dist/core/runner-deps.d.ts +6 -2
  112. package/dist/core/secret-env.d.ts +1 -1
  113. package/dist/core/secret-env.js +4 -4
  114. package/dist/core/session-checkout.d.ts +108 -0
  115. package/dist/core/session-checkout.js +485 -0
  116. package/dist/core/session-store.d.ts +12 -4
  117. package/dist/core/session-store.js +23 -3
  118. package/dist/core/session.d.ts +16 -2
  119. package/dist/core/session.js +3 -0
  120. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  121. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  122. package/dist/core/store-contracts/session-store-contract.js +39 -0
  123. package/dist/core/task-event.d.ts +21 -0
  124. package/dist/core/task-notification.d.ts +9 -1
  125. package/dist/core/task-notification.js +6 -0
  126. package/dist/core/task-registry-agent.d.ts +14 -2
  127. package/dist/core/task-registry-agent.js +45 -19
  128. package/dist/core/task-registry-shared.d.ts +26 -11
  129. package/dist/core/task-registry.d.ts +15 -9
  130. package/dist/core/task-registry.js +9 -10
  131. package/dist/core/task-spec-members.js +1 -1
  132. package/dist/core/task-spec.d.ts +20 -0
  133. package/dist/core/tool-policy.d.ts +14 -12
  134. package/dist/core/tool-policy.js +11 -10
  135. package/dist/core/tool-spec.d.ts +38 -19
  136. package/dist/core/types.d.ts +1 -1
  137. package/dist/core/untrusted-egress.d.ts +15 -4
  138. package/dist/core/untrusted-egress.js +23 -22
  139. package/dist/core/workspace-snapshot.d.ts +3 -1
  140. package/dist/core/workspace-snapshot.js +1 -0
  141. package/dist/engine/harness/types.d.ts +66 -1
  142. package/dist/engine/harness/types.js +108 -0
  143. package/dist/engine/session/import-validate.js +6 -1
  144. package/dist/engine/session/session.d.ts +24 -1
  145. package/dist/engine/session/session.js +45 -1
  146. package/dist/index.d.ts +7 -4
  147. package/dist/index.js +7 -4
  148. package/dist/internal/harness-types.d.ts +1 -1
  149. package/dist/orchestration/run-workflow-tool.d.ts +4 -1
  150. package/dist/orchestration/run-workflow-tool.js +1 -0
  151. package/dist/orchestration/workflow.d.ts +3 -0
  152. package/dist/orchestration/workflow.js +3 -1
  153. package/dist/stores/file/session-store.js +2 -1
  154. package/dist/tools/fs/bash-program-position.js +3 -3
  155. package/dist/tools/fs/program-read-model.d.ts +34 -10
  156. package/dist/tools/fs/program-read-model.js +37 -7
  157. package/dist/tools/fs/program-read-model.rows.js +13 -2
  158. package/dist/tools/fs/read-deny.d.ts +13 -1
  159. package/dist/tools/fs/read-deny.js +10 -2
  160. package/dist/tools/fs/removal-targets.js +3 -3
  161. package/dist/tools/fs/safety.d.ts +2 -0
  162. package/dist/tools/fs/safety.js +1 -1
  163. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  164. package/dist/tools/fs/shell-read-argv.js +34 -29
  165. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  166. package/dist/tools/fs/shell-read-bindings.js +5 -1
  167. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  168. package/dist/tools/fs/shell-read-brace.js +79 -0
  169. package/dist/tools/fs/shell-read-check.js +10 -8
  170. package/dist/tools/fs/shell-read-establish.js +23 -16
  171. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  172. package/dist/tools/fs/shell-read-judge.js +3 -3
  173. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  174. package/dist/tools/fs/shell-read-plan.js +189 -93
  175. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  176. package/dist/tools/fs/shell-read-start.js +20 -12
  177. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  178. package/dist/tools/fs/shell-read-word.js +9 -5
  179. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  180. package/dist/tools/fs/shell-read-workdir.js +73 -12
  181. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  182. package/dist/tools/worktree.d.ts +3 -2
  183. package/dist/tools/worktree.js +7 -35
  184. package/package.json +3 -2
  185. package/test/export-surface.snapshot.json +73 -11
  186. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  187. package/wire-changes/core@7.63.0.json +3523 -0
  188. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  189. package/wire-changes/primitives@7.63.0.json +445 -0
  190. package/dist/core/credential-vocabulary.d.ts +0 -176
  191. package/dist/core/credential-vocabulary.js +0 -190
  192. package/dist/core/redaction-passes.d.ts +0 -82
  193. package/dist/core/redaction-passes.js +0 -377
@@ -1,3 +1,6 @@
1
+ import type { ConsolidationGateRow, ConsolidationIntentCredentialRow, ConsolidationPlanFile, ConsolidationPlanRead } from "./consolidation.js";
2
+ import type { ConsolidationDriverRunRow } from "./consolidation-driver.js";
3
+ import type { LlmConsolidationPlan } from "./distiller.js";
1
4
  /**
2
5
  * design/336 §2.1 — the closed `cause` vocabulary of {@link MemoryEntryOrigin}. Mechanical facts
3
6
  * only (no free text, no tool names, no session ids — those stay on the control plane):
@@ -89,8 +92,9 @@ export interface MemoryEntryFrontmatter {
89
92
  description?: string;
90
93
  /** CC `metadata.type`: user | feedback | project | reference (unknown strings degrade, design/65). */
91
94
  type?: string;
92
- /** design/138 §2.4 删除防线 — the EXPLICIT tombstone. A file that merely disappears is NEVER a
93
- * delete; only `deleted: true` in frontmatter produces a delete patch. */
95
+ /** design/138 §2.4 — the frontmatter tombstone: `deleted: true` reads as the entry's deletion (the
96
+ * sync channel and the inclusion ladder carry deletions in this form). On the harvest's write face
97
+ * it is one of two spellings of the same delete — the other is removing the file. */
94
98
  deleted?: boolean;
95
99
  /**
96
100
  * design-A C-5 (AGENTS.md×ingest, [A1]) — TYPED provenance for entries an INGEST producer minted
@@ -409,7 +413,99 @@ export interface MemoryBackend {
409
413
  /** design/84 Seam B cursor pair, migrated verbatim onto the entry-id plane (S2 rewires consolidation). */
410
414
  getConsolidationCursor(scope: string): Promise<string | undefined>;
411
415
  setConsolidationCursor(scope: string, cursor: string): Promise<void>;
416
+ /** The consolidation state's store (gate rows, plan workbook, intent credentials, driver run account, mint archive):
417
+ * present ⇒ the engine keeps that state here, beside this backend's entries; absent ⇒ the engine keeps it in the
418
+ * replica's own control plane (`fileGovernanceStore` over it). The File backend always carries it, over its own
419
+ * control plane, byte for byte what the files were. Whether the state a consolidation reads survives the replica
420
+ * is answered by `memoryGovernanceDurability`, never by probing this member. */
421
+ readonly governance?: MemoryGovernanceStore;
412
422
  }
423
+ /**
424
+ * One transaction over the consolidation gate rows (every scope's row — one document) and the plan workbook: `fn`
425
+ * runs once, synchronously, over the rows and the plans named in `planIds` as they stood when the transaction took
426
+ * its serialization; its plan writes and — when it answers `writeGate: true` — its row changes are written after it
427
+ * returns, plans first, then the rows (a throw inside `fn` writes nothing and propagates unchanged). A failure while
428
+ * those writes land is not rolled back: the File store leaves the plans already written, as 7.62.0 did, and the
429
+ * engine never asks one transaction for a plan write and a row write together (each of its plan writes is its own
430
+ * transaction), so no reader meets half of one. Nobody else's transaction lands between the reads it saw and its
431
+ * writes: the plan owner fence (read the applier, then write the plan) relies on it.
432
+ */
433
+ export interface ConsolidationTx {
434
+ /** Every scope's gate row, mutable in place (a row added here is written when the transaction answers `writeGate`). */
435
+ readonly scopes: Record<string, ConsolidationGateRow>;
436
+ /** A plan named in the transaction's `planIds` as it stood (a plan not named ⇒ throws: it was not read under the transaction). */
437
+ plan(planId: string): ConsolidationPlanRead;
438
+ /** Stage a plan write; committed with the transaction. */
439
+ writePlan(plan: ConsolidationPlanFile): void;
440
+ }
441
+ /**
442
+ * The consolidation state's store contract ({@link MemoryBackend.governance}). Every read of a malformed record throws
443
+ * `ControlPlaneCorruptError` (fail-closed); a record that was never written reads as absent / empty — a missing row is
444
+ * never a corrupt one, and a corrupt one is never read as missing. `memoryGovernanceStoreContract` (the kit) states
445
+ * each clause as a case.
446
+ */
447
+ export interface MemoryGovernanceStore {
448
+ /** See {@link ConsolidationTx}. */
449
+ transact<T>(planIds: readonly string[], fn: (tx: ConsolidationTx) => {
450
+ writeGate: boolean;
451
+ result: T;
452
+ }): Promise<T>;
453
+ /** Every scope's gate row as last committed. */
454
+ readGate(): Promise<Record<string, ConsolidationGateRow>>;
455
+ /** A plan as last committed (`corrupt` carries the reason; an id outside the plan-id grammar reads `absent`). The one
456
+ * dual-form read: a store that answers synchronously (the File store) lets the engine confirm the plan's holder
457
+ * under a landing-admitting backend's lock, before each commit; a Promise answer has each patch applied alone, the
458
+ * holder read before each. */
459
+ readPlan(planId: string): ConsolidationPlanRead | Promise<ConsolidationPlanRead>;
460
+ /** The workbook's plan ids (custody copies excluded). */
461
+ listPlanIds(): Promise<string[]>;
462
+ /** Move a plan the valve discards aside, never deleting its bytes; answers the custody name, `undefined` when there was nothing to move. */
463
+ quarantinePlan(planId: string): Promise<string | undefined>;
464
+ /** Record intent credentials, idempotent on requestId (a standing row wins); answers the requestIds written. */
465
+ recordIntents(rows: readonly ConsolidationIntentCredentialRow[]): Promise<string[]>;
466
+ readIntents(): Promise<Record<string, ConsolidationIntentCredentialRow>>;
467
+ /** The run claim, one compare-and-set: a pending run of the scope is resumed (its `attempt` bumped — the writer
468
+ * takeover), otherwise `fresh()` opens a new one. */
469
+ claimRun(scope: string, fresh: () => ConsolidationDriverRunRow): Promise<{
470
+ row: ConsolidationDriverRunRow;
471
+ resumed: boolean;
472
+ }>;
473
+ readRun(scope: string): Promise<ConsolidationDriverRunRow | undefined>;
474
+ /** Write a run row only while the scope's standing claim is this row's `(runId, attempt)`; a newer claim refuses
475
+ * `memory.consolidation_driver_superseded` and writes nothing. */
476
+ writeRun(row: ConsolidationDriverRunRow): Promise<void>;
477
+ /** Archive one mint (what the model was shown and answered, verbatim) under the claim's name; answers the name. */
478
+ archiveMint(runId: string, attempt: number, plan: LlmConsolidationPlan): Promise<string>;
479
+ /** A mint archive by name (`undefined` when there is none). */
480
+ readMint(name: string): Promise<LlmConsolidationPlan | undefined>;
481
+ /** Erase a mint archive (its bytes gone, not moved); answers whether one was there. */
482
+ eraseMint(name: string): Promise<boolean>;
483
+ /** A governance document ({@link MEMORY_GOVERNANCE_DOC_NAMES}) as last committed, parsed but not judged: `undefined`
484
+ * when it was never written; a document that cannot be read or parsed throws `ControlPlaneCorruptError` — never
485
+ * read as missing. The engine judges the shape (each document's one reader lives in core). */
486
+ readDoc(name: MemoryGovernanceDocName): Promise<unknown>;
487
+ /** One serialized read-modify-write of a governance document: `coerce` judges what was committed (`undefined` when
488
+ * never written; it throws `ControlPlaneCorruptError` on a shape it refuses), `fn` runs once, synchronously, over
489
+ * that value, and `next` — when it answers one — is written before the call settles. A throw in `coerce` or `fn`
490
+ * writes nothing and propagates unchanged. Nobody else's update of the same document lands between the read `fn`
491
+ * saw and its write; a store that retries a serialization failure runs `coerce` and `fn` again over a fresh read. */
492
+ updateDoc<S, T>(name: MemoryGovernanceDocName, coerce: (raw: unknown) => S, fn: (current: S) => {
493
+ next?: S;
494
+ result: T;
495
+ }): Promise<T>;
496
+ }
497
+ /** The governance documents a {@link MemoryGovernanceStore} keeps (closed set): the harvest lineage ledger, the challenge
498
+ * ledger, the delegation-settlement ledger, the session-account ledger and the memory announcement queue (the notices
499
+ * a session's first injection reads, one bounded queue per scope — {@link import("./layout.js").enqueueMemoryAnnouncement}).
500
+ * One law for all five: the store refuses what it cannot read; what a document means, the queue's leniency over a
501
+ * malformed record included, is core's. The instruction-hold ledger is not one of them: a hold row and its captured
502
+ * bytes are one record, the bytes are files in the engine's control plane, so the row stays beside them there (on
503
+ * several replicas the holds are each replica's own). */
504
+ export declare const MEMORY_GOVERNANCE_DOC_NAMES: readonly ["lineage", "challenges", "settlements", "session-accounts", "announcements"];
505
+ /** One of {@link MEMORY_GOVERNANCE_DOC_NAMES}. */
506
+ export type MemoryGovernanceDocName = (typeof MEMORY_GOVERNANCE_DOC_NAMES)[number];
507
+ /** The part of a {@link MemoryGovernanceStore} the governance documents are kept through. */
508
+ export type MemoryGovernanceDocs = Pick<MemoryGovernanceStore, "readDoc" | "updateDoc">;
413
509
  /** One file the engine materialized into the session memory directory. */
414
510
  export interface MaterializedFile {
415
511
  /** Absolute canonical path of the projected file. */
@@ -482,8 +578,6 @@ export interface MemorySessionHandle {
482
578
  * scopes have a key; the tool faces derive their own LIVE answer per call, so a stale snapshot
483
579
  * can mis-report a number, never mis-serve an entry. */
484
580
  shadowedByScope?: ReadonlyMap<string, number>;
485
- /** Lines of the derived MEMORY.md at materialize time (the index-cleared fuse baseline). */
486
- indexBaselineLines: number;
487
581
  /** 评审 M6 — the derived index TEXT as of materialize. `inject` reads THIS when no on-disk
488
582
  * MEMORY.md exists (a read-only layering never writes one), so first-session read-only injection
489
583
  * works without a disk round-trip. */
@@ -577,9 +671,9 @@ export interface ScanFinding {
577
671
  }
578
672
  /**
579
673
  * design/138 S2-B — one queued memory-change announcement, drained into the NEXT session's first
580
- * injection (时机① only; there is no in-run delivery lane — O-F2/C-F4 裁撤). Queued via the
581
- * journaled control-plane queue ({@link import("./layout.js").enqueueMemoryAnnouncement}) so
582
- * concurrent writers never overwrite each other (O-F6/C-F5).
674
+ * injection (时机① only; there is no in-run delivery lane — O-F2/C-F4 裁撤). Queued in the governance
675
+ * store's `announcements` document ({@link import("./layout.js").enqueueMemoryAnnouncement}, one
676
+ * serialized update) so concurrent writers never overwrite each other (O-F6/C-F5).
583
677
  */
584
678
  export interface MemoryAnnouncement {
585
679
  /** `gate` = engine gate/harvest events (rejections, quarantine, incidents, restores, conflicts,
@@ -606,7 +700,7 @@ export interface MemoryAnnouncement {
606
700
  *
607
701
  * STRUCTURE-ONLY, deliberately: {@link import("./engine.js").renderAnnouncements} does not read
608
702
  * it, so the model-visible block is byte-for-byte what it always was. The consumer is a host
609
- * reading the queue (`drainMemoryAnnouncements` / `peekMemoryAnnouncements`), which can now join
703
+ * reading the queue (`drainMemoryAnnouncements` / `peekMemoryAnnouncements` over the governance store that keeps it), which can now join
610
704
  * a queued line to the `memory.harvest_quarantined` / `memory.hold_*` notices of the same
611
705
  * harvest instead of guessing from counts.
612
706
  *
@@ -673,7 +767,7 @@ export interface HarvestReport {
673
767
  /** Set when a fuse tripped (§2.4 删除防线 / B3 fail-closed): the harvest is refused wholesale, NO
674
768
  * patches (especially no deletes) are produced, and the report is surfaced as an alert. */
675
769
  incident?: {
676
- kind: "mass_deletion" | "index_cleared" | "dir_missing" | "sidecar_corrupt";
770
+ kind: "mass_deletion" | "dir_missing" | "sidecar_corrupt";
677
771
  detail: string;
678
772
  };
679
773
  /** Patch counts actually APPLIED by the backend. */
@@ -701,17 +795,22 @@ export interface HarvestReport {
701
795
  contained: boolean;
702
796
  detail: string;
703
797
  }>;
704
- /** Materialized files absent at harvest. NOT deletes (§2.4: 文件缺失≠删除). Files whose entry id
705
- * re-appears at another path (a RENAME) are NOT counted here (验收 M1 — a rename is an id-keyed
706
- * update, never a missing file, and never feeds the deletion fuse). */
798
+ /** Materialized files gone at harvest — absent, or blank (a blank file holds no entry). On the write
799
+ * face each is this session's removal of that entry, which the harvest commits as a delete (the
800
+ * deletion right is the write right) unless the deletion fuse refuses the whole harvest or a
801
+ * containment arm withholds it; on a read-only layer it is only listed — the session holds no
802
+ * write right there, so it is no delete and the entry stays committed. Files whose entry id
803
+ * re-appears at another path (a RENAME) are NOT counted here
804
+ * (验收 M1 — a rename is an id-keyed update, never a removal, and never feeds the deletion fuse). */
707
805
  missing: string[];
708
- /** B1 committed-shadow recovery: missing (non-tombstoned) files RESTORED onto disk from the
709
- * committed copy (backend/shadow). Disclosed here (the restore is an engine action, never silent).
710
- * Restored paths also appear in {@link missing} (the honest record of what vanished) — EXCEPT
711
- * the design/336 §4 hold arm: an UPDATE-form instruction hold captures the session's edit and
712
- * restores the committed bytes onto the plane seat it vacated (zero-copy: the file is the
713
- * storage), so those paths appear here beside {@link containment}.heldInstruction, never in
714
- * `missing` (the file never vanished — its edit is in custody). */
806
+ /** Files RESTORED onto disk from the committed copy (backend/shadow), disclosed here (the restore is
807
+ * an engine action, never silent): a read-only layer's edited files, and the write-face
808
+ * removals a containment arm withheld (a session that commits nothing; an instruction-form entry
809
+ * under the hard gate). Restored paths also appear in {@link missing} (the honest record of what
810
+ * vanished) — EXCEPT the design/336 §4 hold arm: an UPDATE-form instruction hold captures the
811
+ * session's edit and restores the committed bytes onto the plane seat it vacated (zero-copy: the
812
+ * file is the storage), so those paths appear here beside {@link containment}.heldInstruction,
813
+ * never in `missing` (the file never vanished — its edit is in custody). */
715
814
  restored: string[];
716
815
  /** The other outcome of the same restore: a path whose committed baseline was NOT written back, because
717
816
  * another writer held the file when the restore reached it. The newer bytes stand, the baseline is
@@ -1,4 +1,5 @@
1
1
  export const MEMORY_ORIGIN_CAUSES = Object.freeze(["observed", "derived", "static", "unattributed"]);
2
+ export const MEMORY_GOVERNANCE_DOC_NAMES = Object.freeze(["lineage", "challenges", "settlements", "session-accounts", "announcements"]);
2
3
  export function writableRootOf(handle) {
3
4
  if (handle.writableRoot === null)
4
5
  throw new Error("memory session handle has no write face (writeScope is null) — writableRoot is not available");
@@ -4,7 +4,7 @@ import { termSet } from "./memory-vector.js";
4
4
  import { attrEscape } from "./task-notification.js";
5
5
  import { sanitizeUntrustedText, ENGINE_AUTHORITY_ENVELOPE_TAGS } from "./untrusted-text.js";
6
6
  import { thrownText } from "./thrown-value.js";
7
- import { CREDENTIAL_VOCABULARY, refuseWriteView } from "./credential-vocabulary.js";
7
+ import { CREDENTIAL_VOCABULARY, scanSecrets } from "@sema-agent/primitives";
8
8
  export function supportsConsolidation(store) {
9
9
  return (typeof store.searchScored === "function" &&
10
10
  typeof store.update === "function" &&
@@ -39,14 +39,23 @@ export class MemoryProjectionError extends Error {
39
39
  function hasPromotableMarker(note) {
40
40
  return note.outcomeStats !== undefined;
41
41
  }
42
- const REFUSE_WRITE_FORMS = refuseWriteView(CREDENTIAL_VOCABULARY);
42
+ const REFUSE_WRITE_POLICY = Object.freeze({
43
+ grade: "strict",
44
+ readings: Object.freeze([Object.freeze({ kind: "raw" })]),
45
+ urlUserinfo: "keep-username",
46
+ onUnresolvedReading: "secret",
47
+ });
48
+ const refuseLabel = (id) => id.replaceAll("-", "_");
43
49
  export function detectSecret(text) {
44
50
  if (!text)
45
51
  return null;
46
- for (const form of REFUSE_WRITE_FORMS) {
47
- if (form.re.test(text))
48
- return form.label;
49
- }
52
+ const scan = scanSecrets(text, REFUSE_WRITE_POLICY);
53
+ if (scan.outcome === "whole")
54
+ return refuseLabel(scan.reason);
55
+ const found = new Set(scan.spans.map((s) => s.family));
56
+ for (const row of CREDENTIAL_VOCABULARY.values)
57
+ if (row.strict !== undefined && found.has(row.id))
58
+ return refuseLabel(row.id);
50
59
  return null;
51
60
  }
52
61
  export function enforceSecretWriteGate(body) {
@@ -234,9 +234,28 @@ export interface TextChanges {
234
234
  * `prompt.submit`): a handler is named for the change it made — handing a different text on, or answering a different text
235
235
  * than the one that came up to it — never for carrying another handler's change up. */
236
236
  export declare function textChanges(original: string): TextChanges;
237
+ /** The stations a prompt's screen is — `prompt.submit`, and `classic.UserPromptSubmit` raised in its bottom. The one list:
238
+ * the entrances raise these and nothing else on a prompt, and every reading of "is the screen heard" reads it, so a station
239
+ * added here is heard by all of them. Both are the engine bus's (`MOD_EVENT_TABLE`). */
240
+ export declare const PROMPT_SCREEN_STATIONS: readonly ModEventName[];
237
241
  /** The four entrances' one predicate: does the leg hear a prompt's screen — `prompt.submit`, or `classic.UserPromptSubmit`
238
- * raised in its bottom? */
242
+ * raised in its bottom? The bus's reading of {@link promptScreenHeard}; {@link promptScreenDeclaredBy} is the registrations'. */
239
243
  export declare function promptScreenHasHandlers(bus: LegModBus): boolean;
244
+ /**
245
+ * Whether a set of registrations declares a prompt screen: some `uses.events` pattern — an event name or a `<prefix>.*`,
246
+ * expanded on the engine bus as admission expands it (`expandOnSide`) — selects `prompt.submit` or `classic.UserPromptSubmit`
247
+ * ({@link PROMPT_SCREEN_STATIONS}). The reading for a host that holds registrations before any bus is admitted (an acceptance
248
+ * seat that must know, before it writes a byte, whether the prompt will be screened); the bus's reading is
249
+ * {@link promptScreenHasHandlers} over what the admitted registrations hung. A declaration is the upper bound on what a
250
+ * registration hangs, so a registration that declares a station and hangs nothing on it is declared here and unheard there.
251
+ * A pattern admission would refuse (not a name, not a list, a name no bus reads) selects nothing here — admission refuses the
252
+ * registration itself, with `config.mods_invalid`.
253
+ */
254
+ export declare function promptScreenDeclaredBy(registrations: readonly {
255
+ readonly uses: {
256
+ readonly events: readonly string[];
257
+ };
258
+ }[]): boolean;
240
259
  /**
241
260
  * A prompt's screen at one of the four entrances (objective, live steer, a wake's message before its claim, a parked steer
242
261
  * redelivered): `prompt.submit` over `e` with the prompt as `text`, its bottom raising `classic.UserPromptSubmit` on the text
@@ -6,7 +6,7 @@ import { deliverEngineNotice } from "../engine-notice.js";
6
6
  import { extensionWords } from "../untrusted-egress.js";
7
7
  import { askApproverIdentity, describeThrown, ownArgs } from "../tool-policy.js";
8
8
  import { agentIdOf } from "../leg-identity.js";
9
- import { admitMods } from "./kernel/index.js";
9
+ import { admitMods, expandOnSide } from "./kernel/index.js";
10
10
  import { legBusOf } from "./extension-call.js";
11
11
  import { validateOverlay } from "../../prompt-assembly/overlay.js";
12
12
  import { modsInvalid } from "./kernel/registration.js";
@@ -221,8 +221,27 @@ export function textChanges(original) {
221
221
  rewrittenBy: () => Object.freeze([...changers]),
222
222
  };
223
223
  }
224
+ export const PROMPT_SCREEN_STATIONS = Object.freeze(["prompt.submit", "classic.UserPromptSubmit"]);
225
+ function promptScreenHeard(hears) {
226
+ return PROMPT_SCREEN_STATIONS.some(hears);
227
+ }
224
228
  export function promptScreenHasHandlers(bus) {
225
- return bus.hasHandlers("prompt.submit") || bus.hasHandlers("classic.UserPromptSubmit");
229
+ return promptScreenHeard((station) => bus.hasHandlers(station));
230
+ }
231
+ export function promptScreenDeclaredBy(registrations) {
232
+ const selected = new Set();
233
+ for (const registration of registrations) {
234
+ const patterns = registration?.uses?.events;
235
+ if (!Array.isArray(patterns))
236
+ continue;
237
+ for (const pattern of patterns) {
238
+ const expanded = expandOnSide(pattern, "engine");
239
+ if ("names" in expanded)
240
+ for (const name of expanded.names)
241
+ selected.add(name);
242
+ }
243
+ }
244
+ return promptScreenHeard((station) => selected.has(station));
226
245
  }
227
246
  const PROMPT_SUBMIT_FORM = "prompt.submit takes { text } (a string) or { drop: <reason> }";
228
247
  function readSubmitAnswer(a) {
@@ -1,4 +1,4 @@
1
- import { boundInputHashOf, canonicalize } from "./canonical-json.js";
1
+ import { canonicalize, exactBoundInputHashOf } from "./canonical-json.js";
2
2
  import { mintCheckpointId, mintCheckpointToken, resolveCheckpointStore, resolveDeclaredFidelity } from "./checkpoint-store.js";
3
3
  import { stampCheckpointRequirements } from "./checkpoint-requirements.js";
4
4
  import { resolveDeclaredDurability } from "./wiring-manifest.js";
@@ -70,7 +70,7 @@ function syntheticCheckpoint(scope, fidelity) {
70
70
  toolCallId: `${scope}:call`,
71
71
  toolName: "SelfCheck",
72
72
  args: { probe: true, nested: { depth: 2, list: [1, 2, 3] } },
73
- boundInputHash: boundInputHashOf({ probe: true, nested: { depth: 2, list: [1, 2, 3] } }),
73
+ boundInputHash: exactBoundInputHashOf("SelfCheck", { probe: true, nested: { depth: 2, list: [1, 2, 3] } }),
74
74
  hasBidiControls: true,
75
75
  preview: { probe: true, note: "park wiring self-check display stub" },
76
76
  previewWithheld: "oversize",
@@ -82,6 +82,8 @@ export type PendingKind = (typeof PAUSE_REGISTRY)[GateKind]["pending"];
82
82
  export type ResumeGate = (typeof PAUSE_REGISTRY)[GateKind]["resume"] | "wake";
83
83
  /** Runtime twin of {@link GateKind}. */
84
84
  export declare function isGateKind(v: unknown): v is GateKind;
85
+ /** Runtime twin of {@link PendingKind}: a word of the registry's `pending` column. */
86
+ export declare function isPendingKind(v: unknown): v is PendingKind;
85
87
  /**
86
88
  * The approval cards whose parked row takes another deadline semantic than its gate kind's: a question parked under an
87
89
  * approval gate kind is not an approval, so its deadline voids it (`B`) instead of denying it (`A`). Read only on an
@@ -10,6 +10,9 @@ export const PAUSE_REGISTRY = {
10
10
  export function isGateKind(v) {
11
11
  return typeof v === "string" && Object.prototype.hasOwnProperty.call(PAUSE_REGISTRY, v);
12
12
  }
13
+ export function isPendingKind(v) {
14
+ return Object.values(PAUSE_REGISTRY).some((row) => row.pending === v);
15
+ }
13
16
  export const CARD_FACET_OVERRIDES = Object.freeze({ question: "B" });
14
17
  export function facetOf(gate) {
15
18
  const reading = parkedApprovalCardOf(gate);
@@ -32,6 +32,7 @@ import { type RuleOwner } from "./rule-owner.js";
32
32
  import type { RuleOfferShapeProblem } from "./rule-offer-read.js";
33
33
  import type { AssertAllKeysHandled } from "./ask-origin.js";
34
34
  import { type PermissionRuleStoreProvider } from "./permission-rule-provider.js";
35
+ import { type RuleRefusalCode, type RuleWriteCommitted } from "./permission-rule-store.js";
35
36
  /** One candidate rule inside an approval record: what it says (`behavior`), the exact text and where it
36
37
  * would apply. A card mints `allow` candidates only (a card is one person's yes); the settings import
37
38
  * carries all three behaviors, each entry under the list it was read from. */
@@ -597,8 +598,12 @@ export interface ImportPreview {
597
598
  * independent `alreadyRedeemed` axis (the single-leg replay marker: a dot-recorded-but-unlanded
598
599
  * retry is `alreadyRedeemed: true` AND `persisted`; a rule that pre-existed in the store is
599
600
  * `false` AND `deduped` — the two axes answer different questions and neither implies the other).
600
- * A refused row always carries its `reason`. `deduped` counts as LANDED: an equivalent rule
601
- * already standing means the consent is already in effect.
601
+ * A refused row always carries its `reason` (a sentence for a person, never parsed) and two closed words: `code`, the
602
+ * cause ({@link RuleRefusalCode}), and `committed`, what may be claimed about the bytes ({@link RuleWriteCommitted}) —
603
+ * `no` when the member's rule does not stand because of this call (nothing was written, or the store answered that
604
+ * nothing landed, or the rule's dot is no longer live), `unknown` when the write or the read-back that would have settled
605
+ * it did not settle, so the caller reconciles with `list()` rather than retrying blind. `deduped` counts as LANDED: an
606
+ * equivalent rule already standing means the consent is already in effect.
602
607
  *
603
608
  * design/382 §4.3 — on a SESSION-scope member the two landed words mean the same thing about a
604
609
  * different home: landed in / already in the session's OVERLAY (a session rule's home store), never
@@ -620,6 +625,8 @@ export type RedeemedBatchMember = {
620
625
  readonly rule: string;
621
626
  readonly scope: RuleScope;
622
627
  readonly status: "refused";
628
+ readonly code: RuleRefusalCode;
629
+ readonly committed: RuleWriteCommitted;
623
630
  readonly reason: string;
624
631
  };
625
632
  /**
@@ -688,7 +695,7 @@ export declare function prepareStarterBatch(opts: {
688
695
  * dot reuse included; the walk adds no concurrency primitive of its own;
689
696
  * · a refused member does NOT fold the batch: "all or nothing" is the CONFIRMATION's semantics
690
697
  * (one yes covered the whole offer), not the landing's transaction shape — the walk continues
691
- * and the member's row says refused, with the reason;
698
+ * and the member's row says refused, with its reason, cause (`code`) and claim (`committed`);
692
699
  * · resuming a partial walk IS re-walking: already-landed members answer `alreadyRedeemed: true`
693
700
  * and reuse their recorded dots (two concurrent walkers converge on one dot set, zero double
694
701
  * mints), unlanded members mint on;
@@ -657,51 +657,58 @@ async function confirmEditedCandidate(rec, edit, deps) {
657
657
  }
658
658
  return { ok: true, mintedCandidate: { index, rule: checked.canonicalRule, ticket: mintRuleTicket(rec.id, index) } };
659
659
  }
660
+ function refusal(code, reason, committed = "no") {
661
+ return { status: "refused", code, committed, reason };
662
+ }
660
663
  export async function redeemRuleTicket(opts) {
664
+ const res = await redeemTicketLeg(opts);
665
+ return res.status === "refused" ? { status: "refused", reason: res.reason } : res;
666
+ }
667
+ async function redeemTicketLeg(opts) {
661
668
  const caller = resolveCallerOwner(opts.principal, opts.owner, "redeemRuleTicket");
662
669
  const parsed = parseRuleTicket(opts.ticket);
663
670
  if (parsed === undefined)
664
- return { status: "refused", reason: "malformed ticket" };
671
+ return refusal("ticket_invalid", "malformed ticket");
665
672
  const rec = await opts.deps.approvals.get(parsed.recordId);
666
673
  if (rec === undefined)
667
- return { status: "refused", reason: "no such approval record" };
674
+ return refusal("record_missing", "no such approval record");
668
675
  const recOwner = ownerOfRecord(rec);
669
676
  if (recOwner === undefined || !sameRuleOwner(recOwner, caller))
670
- return { status: "refused", reason: "the ticket belongs to a different principal" };
677
+ return refusal("wrong_principal", "the ticket belongs to a different principal");
671
678
  if (isStale(rec))
672
- return { status: "refused", reason: `record_schema_stale: ${STALE_RECORD_MESSAGE}` };
679
+ return refusal("record_schema_stale", `record_schema_stale: ${STALE_RECORD_MESSAGE}`);
673
680
  if (rec.state === "pending")
674
- return { status: "refused", reason: "the approval record has not been confirmed" };
681
+ return refusal("not_confirmed", "the approval record has not been confirmed");
675
682
  const damage = approvalRecordDamageOf(rec);
676
683
  if (damage !== undefined)
677
- return { status: "refused", reason: `the approval record is malformed: ${damage}` };
684
+ return refusal("record_malformed", `the approval record is malformed: ${damage}`);
678
685
  const candidate = rec.candidates[parsed.index];
679
686
  if (candidate === undefined)
680
- return { status: "refused", reason: "the ticket names no candidate on this record" };
687
+ return refusal("ticket_invalid", "the ticket names no candidate on this record");
681
688
  const chosen = rec.selectedOffer;
682
689
  const chosenOffer = chosen !== undefined && Number.isInteger(chosen) ? rec.offers[chosen] : undefined;
683
690
  if (chosenOffer === undefined) {
684
- return { status: "refused", reason: "the approval record is malformed: it is settled but names no valid chosen offer" };
691
+ return refusal("record_malformed", "the approval record is malformed: it is settled but names no valid chosen offer");
685
692
  }
686
693
  if (!offerMembersOf(chosenOffer).includes(parsed.index)) {
687
- return { status: "refused", reason: "the ticket names an option the person did not choose" };
694
+ return refusal("not_chosen", "the ticket names an option the person did not choose");
688
695
  }
689
696
  const siblingsOf = candidate.behavior === "allow" ? { rec, offer: chosenOffer, index: parsed.index } : undefined;
690
697
  const parsedRule = parseRuleText(candidate.rule, candidate.behavior);
691
698
  if ("reject" in parsedRule)
692
- return { status: "refused", reason: `${parsedRule.reject.code}: ${parsedRule.reject.message}` };
699
+ return refusal("parse_rejected", `${parsedRule.reject.code}: ${parsedRule.reject.message}`);
693
700
  if (rec.kind === "import" && !importCarries(candidate.scope, parsedRule.rule))
694
- return { status: "refused", reason: LAYER_ROOT_RECORD_REASON };
701
+ return refusal("unsupported.layer_root", LAYER_ROOT_RECORD_REASON);
695
702
  let store;
696
703
  try {
697
704
  store = storeForOwner(opts.deps.provider, caller);
698
705
  }
699
706
  catch (err) {
700
- return { status: "refused", reason: errText(err) };
707
+ return refusal("store_unavailable", errText(err));
701
708
  }
702
709
  const writer = writerOf(store);
703
710
  if (writer === undefined)
704
- return { status: "refused", reason: "the resolved permission-rule store has no write face" };
711
+ return refusal("store_unavailable", "the resolved permission-rule store has no write face");
705
712
  const known = rec.redeemedDots?.[parsed.index];
706
713
  const dot = known ?? (await writer.nextDot());
707
714
  if (known === undefined) {
@@ -716,7 +723,7 @@ export async function redeemRuleTicket(opts) {
716
723
  const again = await opts.deps.approvals.get(rec.id);
717
724
  const theirs = again === undefined || isStale(again) ? undefined : again.redeemedDots?.[parsed.index];
718
725
  if (theirs === undefined)
719
- return { status: "refused", reason: "the approval record changed state concurrently" };
726
+ return refusal("record_changed", "the approval record changed state concurrently");
720
727
  return await applyRedemption({ deps: opts.deps, owner: caller, candidate, parsedRule: parsedRule.rule, dot: theirs, recordId: rec.id, kind: rec.kind, replay: true, ...(siblingsOf !== undefined ? { siblingsOf } : {}) });
721
728
  }
722
729
  }
@@ -745,11 +752,11 @@ async function applyRedemption(args) {
745
752
  store = storeForOwner(args.deps.provider, args.owner);
746
753
  }
747
754
  catch (err) {
748
- return { status: "refused", reason: errText(err) };
755
+ return refusal("store_unavailable", errText(err));
749
756
  }
750
757
  const writer = writerOf(store);
751
758
  if (writer === undefined)
752
- return { status: "refused", reason: "the resolved permission-rule store has no write face" };
759
+ return refusal("store_unavailable", "the resolved permission-rule store has no write face");
753
760
  const origin = originOfRecordKind(args.kind);
754
761
  const siblings = args.siblingsOf;
755
762
  const landing = await landRuleAdd({
@@ -778,7 +785,7 @@ async function applyRedemption(args) {
778
785
  : {}),
779
786
  });
780
787
  if (!landing.landed)
781
- return { status: "refused", reason: landing.reason };
788
+ return refusal(landing.code, landing.reason, landing.committed);
782
789
  return { status: "redeemed", behavior: args.parsedRule.behavior, rule: args.parsedRule.rule, scope: args.candidate.scope, dot: args.dot, rev: landing.rev, alreadyRedeemed: args.replay };
783
790
  }
784
791
  function originOfRecordKind(kind) {
@@ -976,7 +983,7 @@ export async function redeemRuleBatch(opts) {
976
983
  const candidate = rec.candidates[candidateIndex];
977
984
  const row = { candidateIndex, behavior: candidate.behavior, rule: candidate.rule, scope: candidate.scope };
978
985
  if (candidate.behavior === "allow" && tighteningFailed !== undefined) {
979
- members.push({ ...row, status: "refused", reason: `withheld: candidate ${tighteningFailed} (a deny/ask member of this batch) did not land, and an allow must not stand wider than the list that was confirmed — redeem the batch again once the store accepts the tightening member` });
986
+ members.push({ ...row, status: "refused", code: "withheld", committed: "no", reason: `withheld: candidate ${tighteningFailed} (a deny/ask member of this batch) did not land, and an allow must not stand wider than the list that was confirmed — redeem the batch again once the store accepts the tightening member` });
980
987
  continue;
981
988
  }
982
989
  let alreadyThere = false;
@@ -987,34 +994,40 @@ export async function redeemRuleBatch(opts) {
987
994
  alreadyThere = snap.rules.some((r) => r.behavior === candidate.behavior && r.rule === candidate.rule && sameScope(r.scope, candidate.scope));
988
995
  }
989
996
  catch (err) {
990
- members.push({ ...row, status: "refused", reason: `could not read the permission-rule store: ${errText(err)}` });
997
+ members.push({ ...row, status: "refused", code: "store_read", committed: "no", reason: `could not read the permission-rule store: ${errText(err)}` });
991
998
  if (candidate.behavior !== "allow")
992
999
  tighteningFailed ??= candidateIndex;
993
1000
  continue;
994
1001
  }
995
1002
  }
996
- const res = await redeemRuleTicket({
1003
+ const res = await redeemTicketLeg({
997
1004
  ticket: mintRuleTicket(rec.id, candidateIndex),
998
1005
  ...(caller.kind === "principal" ? { principal: caller.principal } : { owner: caller }),
999
1006
  deps: opts.deps,
1000
1007
  });
1001
1008
  if (res.status === "refused") {
1002
- members.push({ ...row, status: "refused", reason: res.reason });
1009
+ members.push({ ...row, status: "refused", code: res.code, committed: res.committed, reason: res.reason });
1003
1010
  if (candidate.behavior !== "allow")
1004
1011
  tighteningFailed ??= candidateIndex;
1005
1012
  continue;
1006
1013
  }
1007
1014
  if (candidate.behavior !== "allow") {
1008
1015
  let live = false;
1016
+ let unreadable;
1009
1017
  try {
1010
1018
  const snap = await effectiveOrThrow(store, candidate.scope.kind === "session" ? { sessionId: candidate.scope.sessionId } : undefined);
1011
1019
  live = snap.rules.some((r) => r.behavior === candidate.behavior && r.rule === candidate.rule && sameScope(r.scope, candidate.scope) && r.adds.some((a) => a.dot.actor === res.dot.actor && a.dot.counter === res.dot.counter));
1012
1020
  }
1013
- catch {
1014
- live = false;
1021
+ catch (err) {
1022
+ unreadable = errText(err);
1023
+ }
1024
+ if (unreadable !== undefined) {
1025
+ members.push({ ...row, status: "refused", code: "store_read", committed: "unknown", reason: `could not read the permission-rule store to confirm this ${candidate.behavior} member stands after its redemption: ${unreadable}` });
1026
+ tighteningFailed ??= candidateIndex;
1027
+ continue;
1015
1028
  }
1016
1029
  if (!live) {
1017
- members.push({ ...row, status: "refused", reason: `this ${candidate.behavior} member's redeemed dot ${res.dot.actor}#${res.dot.counter} is not live in the store (removed since it was redeemed) — a removed rule is not re-landed by replaying its record; a new consent is required` });
1030
+ members.push({ ...row, status: "refused", code: "dot_removed", committed: "no", reason: `this ${candidate.behavior} member's redeemed dot ${res.dot.actor}#${res.dot.counter} is not live in the store (removed since it was redeemed) — a removed rule is not re-landed by replaying its record; a new consent is required` });
1018
1031
  tighteningFailed ??= candidateIndex;
1019
1032
  continue;
1020
1033
  }
@@ -608,6 +608,37 @@ export type RemovalLiveness = (typeof REMOVAL_LIVENESS_WORDS)[number];
608
608
  */
609
609
  export declare const RULE_WRITE_COMMITTED_WORDS: readonly ["no", "unknown"];
610
610
  export type RuleWriteCommitted = (typeof RULE_WRITE_COMMITTED_WORDS)[number];
611
+ /**
612
+ * WHY a redemption was refused — the cause, spelled once and read by every refused row: the single-ticket leg, the
613
+ * member table of a batch walk, and the landing under both. A refusal carries a `reason` for a person AND one of these
614
+ * words, so a consumer that has to branch on the cause reads a word and never the start of a sentence. One word per
615
+ * CAUSE, every place that refuses names one, and there is deliberately no catch-all: a refusal nobody classified is a
616
+ * compile error at the place that mints it, never an `other`.
617
+ *
618
+ * It rides beside {@link RuleWriteCommitted}, and the two answer different questions. The code says what stopped the
619
+ * redemption; `committed` says what may be claimed about the bytes. The same code can carry both words (`store_read`:
620
+ * a read before any write says `no`, a read-back after one that could not be taken says `unknown`).
621
+ *
622
+ * - `unsupported.layer_root` — an import record's global rule written from `/`, which no stored row can hold
623
+ * - `ticket_invalid` — the ticket does not name a candidate (unparseable, or an index the record has none at)
624
+ * - `record_missing` — no approval record is stored under the ticket's id
625
+ * - `wrong_principal` — the record belongs to another owner than the caller
626
+ * - `record_schema_stale` — the record predates the current form, so the decision it carried is not read
627
+ * - `not_confirmed` — the record is still pending; nobody has said yes
628
+ * - `record_malformed` — the record fails the structural precondition, or is settled but names no chosen offer
629
+ * - `not_chosen` — the candidate is outside the offer the person chose
630
+ * - `parse_rejected` — the candidate's rule text no longer passes the one validator
631
+ * - `store_unavailable` — the owner's store cannot be resolved, or has no write face
632
+ * - `record_changed` — the record moved under this redemption and the dot it needed is not there
633
+ * - `withheld` — held back because the batch's deny/ask members do not all stand, and an allow may not stand wider
634
+ * - `store_read` — a permission-rule store read failed (before the write: `no`; the read-back after it: `unknown`)
635
+ * - `store_write` — the write threw, answered unreadably, or was reported landed with no trace of its dot (`unknown`)
636
+ * - `session_ended` — a session-scope rule whose session has ended; a late redemption cannot revive it
637
+ * - `occ` — every optimistic-concurrency attempt lost its compare-and-set
638
+ * - `dot_removed` — the member's redeemed dot is no longer live in the store (the rule was removed since)
639
+ */
640
+ export declare const RULE_REFUSAL_CODES: readonly ["unsupported.layer_root", "ticket_invalid", "record_missing", "wrong_principal", "record_schema_stale", "not_confirmed", "record_malformed", "not_chosen", "parse_rejected", "store_unavailable", "record_changed", "withheld", "store_read", "store_write", "session_ended", "occ", "dot_removed"];
641
+ export type RuleRefusalCode = (typeof RULE_REFUSAL_CODES)[number];
611
642
  /**
612
643
  * The result of a removal.
613
644
  *
@@ -686,11 +717,14 @@ export type RuleAddLanding = {
686
717
  /** `committed` is what the caller may CLAIM afterwards. `"no"` means the store itself answered — a
687
718
  * read that failed before any write, a refused preflight, an epoch seal, or a compare-and-set that
688
719
  * lost every attempt: each of those is the store saying nothing landed. `"unknown"` means the apply
689
- * THREW, which proves nothing either way: a backend can commit and then lose its acknowledgement. */
720
+ * THREW, which proves nothing either way: a backend can commit and then lose its acknowledgement.
721
+ * `code` is the cause ({@link RuleRefusalCode}); this path mints five of them (`withheld`, `store_read`,
722
+ * `store_write`, `session_ended`, `occ`), so a door never reads the cause out of `reason`. */
690
723
  | {
691
724
  landed: false;
692
725
  reason: string;
693
726
  committed: RuleWriteCommitted;
727
+ code: RuleRefusalCode;
694
728
  };
695
729
  /**
696
730
  * Land ONE add — the terminal write both doors take (the consent protocol's redemption and the