@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
@@ -15,12 +15,18 @@ export declare function encodeScopeSegment(raw: string): string;
15
15
  * exactly what the encoder produces — safe chars stay bare (so `%41` for `A` is refused: two
16
16
  * spellings of one identity must not mint two keys), `%XX` sequences must decode as valid UTF-8
17
17
  * (fatal decoder — no U+FFFD smoothing), and the 64-char cap holds here too (parse side enforces
18
- * what the format side promised).
18
+ * what the format side promised). Every refusal carries `config.memory_scope_key`.
19
19
  */
20
20
  export declare function decodeScopeSegment(encoded: string): string;
21
21
  export type ParsedScopeKey = {
22
22
  kind: "user";
23
23
  principal: string;
24
+ }
25
+ /** A principal's layer that never leaves the store it is written in: personal plane, never replicated
26
+ * ({@link isReplicableScope}). */
27
+ | {
28
+ kind: "userlocal";
29
+ principal: string;
24
30
  } | {
25
31
  kind: "org";
26
32
  tenant: string;
@@ -39,14 +45,18 @@ export type ParsedScopeKey = {
39
45
  raw: string;
40
46
  };
41
47
  export declare function formatUserScope(principal: string): string;
48
+ export declare function formatUserLocalScope(principal: string): string;
42
49
  export declare function formatOrgScope(tenant: string): string;
43
50
  export declare function formatProjScope(tenant: string, projectId: string): string;
44
51
  export declare function formatUserProjScope(principal: string, projectId: string): string;
45
52
  /**
46
53
  * Parse a scope key under the v2 contract. A key carrying a recognized prefix MUST be well-formed
47
54
  * (fail-loud — a malformed `proj:` key under an explicit opt-in is a config error, not an opaque
48
- * scope); anything without a recognized prefix parses as `{ kind: "legacy" }` and keeps today's
49
- * opaque behavior. NEVER call this on a deployment that has not opted in (see module header).
55
+ * scope), and so must a key that spells one of the five without carrying it exactly — another case,
56
+ * a full-width colon, surrounding whitespace: the prefixes are reserved, so such a spelling is neither
57
+ * read as the kind it imitates nor left to pass as an opaque scope (`config.memory_scope_key`).
58
+ * Anything else parses as `{ kind: "legacy" }` and keeps today's opaque behavior. NEVER call this on a
59
+ * deployment that has not opted in (see module header).
50
60
  */
51
61
  export declare function parseScopeKey(key: string): ParsedScopeKey;
52
62
  /**
@@ -59,25 +69,56 @@ export declare function parseScopeKey(key: string): ParsedScopeKey;
59
69
  * pattern restated outside core answers a different question and disagrees on exactly those inputs.
60
70
  */
61
71
  export declare function isOrgScopeKey(key: string): boolean;
62
- /** True when a v2-parsed key belongs to a PERSONAL plane (`user:` / `userproj:`). */
72
+ /** True when a v2-parsed key is a principal's own layer (`user:` / `userlocal:` / `userproj:`). */
63
73
  export declare function isPersonalScope(parsed: ParsedScopeKey): boolean;
64
- /** True when the key's AUTHORITY is central (design/142 §2 表: user/userproj/org rows) — these keys
65
- * must never project into an in-repo memory dir (they would leak to every collaborator AND enter
66
- * commit history; extended the F9 gate from personal to org). `proj:`/legacy stay
67
- * repo-planed.
74
+ /** True when the key's layer lives on the PERSONAL plane (the home mount, design/142 §2 表: the
75
+ * user/userproj/org rows, and `userlocal:`) — these keys must never project into an in-repo memory dir (they
76
+ * would leak to every collaborator AND enter commit history; extended the F9 gate from personal to org).
77
+ * `proj:`/legacy stay repo-planed. The plane says where a layer may NOT be projected, not where its
78
+ * authority is: `org:` is owned by the center, `userlocal:` by the store it is written in
79
+ * ({@link isReplicableScope}).
68
80
  *
69
81
  * @contract memory.identity_absence.opaque_key — the memory of an owner with no identity is keyed by an opaque,
70
82
  * unprefixed key the deployment chooses (such as `local`) and never by a sentinel principal: no `user:` key stands for
71
83
  * identity absence (a `user:local` key is the key of a principal named `local`), so this function answers `false`
72
- * for that layer — its authority is not central. The engine mints no key for identity absence. Read as an
84
+ * for that layer — it stays on the project plane. The engine mints no key for identity absence. Read as an
73
85
  * owner, it is the `local-owner` arm of `RuleOwner` (core/rule-owner.ts), not a principal. A principal's memory is
74
86
  * keyed by that principal's keys (`user:<P>` and the principal's project layers); moving this layer to a principal
75
87
  * is a re-keying of its entries (`migrateScope`), and the engine never reads the opaque name as a principal.
76
88
  * Admission authorizes by the caller's principal (`MemoryScopeAdmissionInput`), never by a layer's owner. */
77
- export declare function isCentralAuthorityScope(parsed: ParsedScopeKey): boolean;
89
+ export declare function isPersonalPlaneScope(parsed: ParsedScopeKey): boolean;
90
+ /** Who owns a memory layer, for a question asked of its owner rather than of whoever acts on it: a principal (its own
91
+ * layers), a tenant (the organization's layers), or the deployment itself (an opaque key). */
92
+ export type MemoryScopeOwner = {
93
+ kind: "principal";
94
+ principal: string;
95
+ } | {
96
+ kind: "tenant";
97
+ tenant: string;
98
+ } | {
99
+ kind: "deployment";
100
+ };
101
+ /**
102
+ * THE owner reading of a scope key: `user:` / `userlocal:` / `userproj:` are a principal's own layers, `org:` / `proj:` a
103
+ * tenant's, and an opaque key the deployment's — every key of a session without the v2 contract (where `user:42` is an
104
+ * opaque spelling, never principal `42`), and an unprefixed key under it. Under v2 a malformed reserved key throws
105
+ * `config.memory_scope_key`, as {@link parseScopeKey} does. A kind the switch does not handle is a compile error.
106
+ */
107
+ export declare function memoryScopeOwnerOf(scope: string, scopeContract: "v2" | undefined): MemoryScopeOwner;
108
+ /**
109
+ * THE replication judge: may a sync carry `key`'s entries to another store? Every key may, except the
110
+ * `userlocal:` family — read as the parser reads a key's reserved prefix ({@link reservedPrefixOf}: exactly, else
111
+ * folded — another case, a full-width colon, compatibility letters, surrounding whitespace), well-formed or not,
112
+ * and under any scope contract: the prefix is reserved, so a deployment that never opted in to v2 is
113
+ * answered by the spelling too (the safe direction for a layer its owner keeps off every other store). A key
114
+ * the parser refuses as a `userlocal:` spelling is therefore never replicable: one reading, two askers.
115
+ * `syncMemoryScope` refuses such a scope before any read or request (`config.memory_scope_key`), and
116
+ * `memoryTravelGapOf` reports it `local_only`. A value that is not a string is not a key and throws.
117
+ */
118
+ export declare function isReplicableScope(key: string): boolean;
78
119
  /**
79
120
  * design/142 §7 S1 hard gate (复审 F9): until S1b per-scope physical roots land, ALL scopes of a
80
- * session materialize under ONE root — so a v2 session mixing `user:*`/`userproj:*` keys with an
121
+ * session materialize under ONE root — so a v2 session mixing personal-plane keys ({@link isPersonalPlaneScope}) with an
81
122
  * IN-REPO memory dir would project personal memory into the repo (the exact §2.7 leak shape:
82
123
  * personal notes committed to a shared/open repo). Fail-loud, never fail-open: this throws a
83
124
  * `config.`-coded error the prepare path must NOT swallow.
@@ -49,12 +49,17 @@ function isWellFormedString(s) {
49
49
  return true;
50
50
  }
51
51
  const FATAL_UTF8 = new TextDecoder("utf-8", { fatal: true });
52
+ function scopeKeyRefusal(message) {
53
+ const e = new Error(message);
54
+ e.code = "config.memory_scope_key";
55
+ return e;
56
+ }
52
57
  export function decodeScopeSegment(encoded) {
53
58
  if (encoded.length > SCOPE_SEGMENT_MAX_ENCODED) {
54
- throw new Error(`scope segment exceeds ${SCOPE_SEGMENT_MAX_ENCODED} encoded chars (${encoded.length})`);
59
+ throw scopeKeyRefusal(`scope segment exceeds ${SCOPE_SEGMENT_MAX_ENCODED} encoded chars (${encoded.length})`);
55
60
  }
56
61
  if (!/^(?:[A-Za-z0-9._-]|%[0-9A-F]{2})*$/.test(encoded)) {
57
- throw new Error(`malformed scope segment: ${encoded}`);
62
+ throw scopeKeyRefusal(`malformed scope segment: ${encoded}`);
58
63
  }
59
64
  const bytes = [];
60
65
  for (let i = 0; i < encoded.length; i++) {
@@ -71,16 +76,26 @@ export function decodeScopeSegment(encoded) {
71
76
  decoded = FATAL_UTF8.decode(Uint8Array.from(bytes));
72
77
  }
73
78
  catch {
74
- throw new Error(`malformed scope segment (invalid UTF-8 in %XX sequence): ${encoded}`);
79
+ throw scopeKeyRefusal(`malformed scope segment (invalid UTF-8 in %XX sequence): ${encoded}`);
80
+ }
81
+ let reencoded;
82
+ try {
83
+ reencoded = encodeScopeSegment(decoded);
84
+ }
85
+ catch (e) {
86
+ throw scopeKeyRefusal(`non-canonical scope segment (${thrownText(e)}): ${encoded}`);
75
87
  }
76
- if (encodeScopeSegment(decoded) !== encoded) {
77
- throw new Error(`non-canonical scope segment (re-encode mismatch): ${encoded}`);
88
+ if (reencoded !== encoded) {
89
+ throw scopeKeyRefusal(`non-canonical scope segment (re-encode mismatch): ${encoded}`);
78
90
  }
79
91
  return decoded;
80
92
  }
81
93
  export function formatUserScope(principal) {
82
94
  return `user:${encodeScopeSegment(principal)}`;
83
95
  }
96
+ export function formatUserLocalScope(principal) {
97
+ return `${USERLOCAL_PREFIX}${encodeScopeSegment(principal)}`;
98
+ }
84
99
  export function formatOrgScope(tenant) {
85
100
  return `org:${encodeScopeSegment(tenant)}`;
86
101
  }
@@ -90,13 +105,23 @@ export function formatProjScope(tenant, projectId) {
90
105
  export function formatUserProjScope(principal, projectId) {
91
106
  return `userproj:${encodeScopeSegment(principal)}/${encodeScopeSegment(projectId)}`;
92
107
  }
93
- const ONE_SEGMENT = /^(user|org):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
108
+ const USERLOCAL_PREFIX = "userlocal:";
109
+ const ONE_SEGMENT = /^(user|userlocal|org):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
94
110
  const TWO_SEGMENT = /^(proj|userproj):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)\/((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
111
+ const RESERVED_PREFIX = /^(user|userlocal|org|proj|userproj):/;
112
+ const foldedSpelling = (key) => String(key).trim().normalize("NFKC").toLowerCase();
113
+ function reservedPrefixOf(key) {
114
+ const exact = RESERVED_PREFIX.exec(key);
115
+ if (exact)
116
+ return { kind: exact[1], exact: true };
117
+ const folded = RESERVED_PREFIX.exec(foldedSpelling(key));
118
+ return folded ? { kind: folded[1], exact: false } : undefined;
119
+ }
95
120
  export function parseScopeKey(key) {
96
121
  const m1 = ONE_SEGMENT.exec(key);
97
122
  if (m1) {
98
123
  const seg = decodeScopeSegment(m1[2]);
99
- return m1[1] === "user" ? { kind: "user", principal: seg } : { kind: "org", tenant: seg };
124
+ return m1[1] === "org" ? { kind: "org", tenant: seg } : { kind: m1[1], principal: seg };
100
125
  }
101
126
  const m2 = TWO_SEGMENT.exec(key);
102
127
  if (m2) {
@@ -104,13 +129,12 @@ export function parseScopeKey(key) {
104
129
  const b = decodeScopeSegment(m2[3]);
105
130
  return m2[1] === "proj" ? { kind: "proj", tenant: a, projectId: b } : { kind: "userproj", principal: a, projectId: b };
106
131
  }
107
- const prefix = /^(user|org|proj|userproj):/.exec(key);
108
- if (prefix) {
109
- const e = new Error(`malformed v2 scope key "${key}": prefix "${prefix[1]}:" is reserved by the scope contract ` +
110
- `(design/142 §1.2) — segments must be encoded with encodeScopeSegment (charset [A-Za-z0-9._-] + %XX), ` +
111
- `"${prefix[1]}" takes ${prefix[1] === "proj" || prefix[1] === "userproj" ? "two segments (a/b)" : "one segment"}.`);
112
- e.code = "config.memory_scope_key";
113
- throw e;
132
+ const reserved = reservedPrefixOf(key);
133
+ if (reserved) {
134
+ throw scopeKeyRefusal(`malformed v2 scope key "${key}": prefix "${reserved.kind}:" is reserved by the scope contract ` +
135
+ `(design/142 §1.2) — ${reserved.exact ? "" : "the key spells it with another case, a full-width colon or surrounding whitespace; the prefix is matched exactly, never folded to its kind — "}` +
136
+ `segments must be encoded with encodeScopeSegment (charset [A-Za-z0-9._-] + %XX), ` +
137
+ `"${reserved.kind}" takes ${reserved.kind === "proj" || reserved.kind === "userproj" ? "two segments (a/b)" : "one segment"}.`);
114
138
  }
115
139
  return { kind: "legacy", raw: key };
116
140
  }
@@ -123,24 +147,49 @@ export function isOrgScopeKey(key) {
123
147
  }
124
148
  }
125
149
  export function isPersonalScope(parsed) {
126
- return parsed.kind === "user" || parsed.kind === "userproj";
150
+ return parsed.kind === "user" || parsed.kind === "userlocal" || parsed.kind === "userproj";
127
151
  }
128
- export function isCentralAuthorityScope(parsed) {
152
+ export function isPersonalPlaneScope(parsed) {
129
153
  return isPersonalScope(parsed) || parsed.kind === "org";
130
154
  }
155
+ export function memoryScopeOwnerOf(scope, scopeContract) {
156
+ if (scopeContract !== "v2")
157
+ return { kind: "deployment" };
158
+ const parsed = parseScopeKey(scope);
159
+ switch (parsed.kind) {
160
+ case "user":
161
+ case "userlocal":
162
+ case "userproj":
163
+ return { kind: "principal", principal: parsed.principal };
164
+ case "org":
165
+ case "proj":
166
+ return { kind: "tenant", tenant: parsed.tenant };
167
+ case "legacy":
168
+ return { kind: "deployment" };
169
+ default: {
170
+ const unhandled = parsed;
171
+ return unhandled;
172
+ }
173
+ }
174
+ }
175
+ export function isReplicableScope(key) {
176
+ if (typeof key !== "string")
177
+ throw new TypeError(`isReplicableScope: a scope key is a string (got ${key === null ? "null" : typeof key})`);
178
+ return reservedPrefixOf(key)?.kind !== "userlocal";
179
+ }
131
180
  export function assertScopeContractPlacement(args) {
132
181
  if (!args.repoRoot)
133
182
  return;
134
- const personal = args.parsedScopes.filter(isCentralAuthorityScope);
183
+ const personal = args.parsedScopes.filter(isPersonalPlaneScope);
135
184
  if (personal.length === 0)
136
185
  return;
137
186
  const rootSegs = pathSegmentsDualFamily(canonicalize(resolve(args.repoRoot))).map(foldPathCase);
138
187
  const dirSegs = pathSegmentsDualFamily(canonicalize(resolve(args.memoryDir))).map(foldPathCase);
139
188
  if (rootSegs.length <= dirSegs.length && rootSegs.every((s, i) => s === dirSegs[i])) {
140
- const e = new Error(`memory scope contract v2: central-authority scope(s) ${personal
189
+ const e = new Error(`memory scope contract v2: personal-plane scope(s) ${personal
141
190
  .map((p) => `"${p.kind}"`)
142
191
  .join(", ")} cannot materialize into an IN-REPO memory dir (${args.memoryDir}) — ` +
143
- `a user/userproj/org layer projected under the repo root would leak non-repo memory to every ` +
192
+ `a user/userlocal/userproj/org layer projected under the repo root would leak non-repo memory to every ` +
144
193
  `collaborator (and into commit history). Move the memory dir out of the repo, or drop those scopes.`);
145
194
  e.code = "config.memory_scope_placement";
146
195
  throw e;
@@ -18,10 +18,12 @@
18
18
  * answers absent before either source is read, so no read here goes through a face whose layout seat would finish the move
19
19
  * first and then name a post-move home.
20
20
  */
21
- import type { MemoryEntry } from "./types.js";
21
+ import type { MemoryEntry, MemoryGovernanceDocs } from "./types.js";
22
22
  export declare function sessionWriteHomeOf(input: {
23
23
  memoryDir: string;
24
24
  controlDir: string;
25
+ /** Where the session-account ledger is kept (the engine's governance store). */
26
+ docs: MemoryGovernanceDocs;
25
27
  sessionId: string;
26
28
  /** The caller's lineage read: entry id → this session's `lastAt` on it (undefined ⇔ that read faulted). */
27
29
  contributions: ReadonlyMap<string, number> | undefined;
@@ -12,7 +12,7 @@ export async function sessionWriteHomeOf(input) {
12
12
  if (newest === undefined || at > newest.at || (at === newest.at && id > newest.id))
13
13
  newest = { id, at };
14
14
  }
15
- const account = sessionAccountWriteHome(controlDir, sessionId);
15
+ const account = await sessionAccountWriteHome(input.docs, sessionId);
16
16
  const sources = [];
17
17
  const fromAccount = async () => account?.writeScope;
18
18
  const fromNewest = async () => (newest === undefined ? undefined : (await input.readEntries([newest.id])).find((e) => e.id === newest.id)?.scope);
@@ -123,7 +123,9 @@ export interface MemorySyncClientConflict {
123
123
  export interface SyncMemoryScopeOptions {
124
124
  /** The LOCAL authority plane (TOC: the File backend). */
125
125
  backend: MemoryBackend;
126
- /** The scope this round syncs (one round = one scope, mirroring the server route). */
126
+ /** The scope this round syncs (one round = one scope, mirroring the server route). A scope that is not
127
+ * replicable ({@link isReplicableScope}: the `userlocal:` family) is refused with `config.memory_scope_key`
128
+ * before any read or request. */
127
129
  scope: string;
128
130
  /** The injected seam to the peer; its `peer` is the round's peer. */
129
131
  transport: MemorySyncTransport;
@@ -8,6 +8,7 @@ import { directoryPinOf } from "./dual-root.js";
8
8
  import { landingPathOf } from "./layout.js";
9
9
  import { egressText } from "../untrusted-egress.js";
10
10
  import { REDACTION_MARKS } from "../redaction-marks.js";
11
+ import { isReplicableScope } from "./scope-contract.js";
11
12
  const DROP_THE_CURSOR = "drop the cursor to accept re-convergence from an empty baseline — entries changed on both sides are reported as conflicts, " +
12
13
  "and entries deleted on one side since the last round come back from the other side";
13
14
  const REFUSAL_ROWS = {
@@ -349,6 +350,12 @@ export async function syncMemoryScope(opts) {
349
350
  const { backend, scope, transport, cursor } = opts;
350
351
  if (!namesSomething(scope))
351
352
  throw new Error("memory sync: scope must be a non-empty string");
353
+ if (!isReplicableScope(scope)) {
354
+ const e = new Error(egressText("same-principal", `memory sync: scope ${quoted(scope)} is a userlocal: key — its layer never leaves the store it is written in, so no sync carries it; ` +
355
+ "nothing was read or sent. Leave this layer out of the sync (isReplicableScope)."));
356
+ e.code = "config.memory_scope_key";
357
+ throw e;
358
+ }
352
359
  const peer = transport?.peer;
353
360
  if (!namesSomething(peer))
354
361
  throw new Error("memory sync: transport.peer must be a non-empty string — a transport is { peer, post }, peer = the identity of the peer it reaches");
@@ -74,7 +74,7 @@ type RoundRefusal = {
74
74
  readonly code: "session_active";
75
75
  readonly message: string;
76
76
  };
77
- type GapWhy = "refused" | "failed" | "incomplete" | "not_replicated" | "not_read_at_destination";
77
+ type GapWhy = "local_only" | "refused" | "failed" | "incomplete" | "not_replicated" | "not_read_at_destination";
78
78
  /**
79
79
  * THE report of a memory sync — the one reading of how its `syncMemoryScope` calls settled, for every host that runs or
80
80
  * relays one. Give it the destination (`target`), the source revision, the source session's read set (`scopes`), and
@@ -93,7 +93,8 @@ export declare function memorySyncReportOf(round: {
93
93
  })): MemorySyncRoundReport;
94
94
  /**
95
95
  * What of a session's memory does not travel with it: every scope of the report's read set that did not arrive whole,
96
- * once, with why — `refused` (the sync, or its layer's last call, was refused and wrote nothing on either side), `failed`, `incomplete`,
96
+ * once, with why — `local_only` (the scope never replicates, {@link isReplicableScope}: whatever the sync did, its layer
97
+ * stays in the store it is written in), `refused` (the sync, or its layer's last call, was refused and wrote nothing on either side), `failed`, `incomplete`,
97
98
  * `not_replicated` (no layer was run for it), or `not_read_at_destination` (its layer synced, and the destination's
98
99
  * read set, when given, does not hold it). A scope absent from the result travelled. Keys are compared as written. A
99
100
  * report that is not one this engine's `memorySyncReportOf` could have minted (a layer with no scope, outside the read
@@ -1,5 +1,6 @@
1
1
  import { carriesCredential, readSyncRefusal } from "./sync-client.js";
2
2
  import { egressText, egressThrownText } from "../untrusted-egress.js";
3
+ import { isReplicableScope } from "./scope-contract.js";
3
4
  const OUTCOMES = new Set(["synced", "incomplete", "refused", "failed"]);
4
5
  const text = (s) => egressText("same-principal", s);
5
6
  function requireNamed(what, v) {
@@ -91,8 +92,9 @@ export function memoryTravelGapOf(report, readAtDestination) {
91
92
  throw new TypeError("memory travel gap: report must be a memory sync report");
92
93
  const scopes = requireNames("report.scopes", report.scopes);
93
94
  const destination = readAtDestination === undefined ? undefined : new Set(requireNames("readAtDestination", readAtDestination));
95
+ const localOnly = (scope) => !isReplicableScope(scope);
94
96
  if (!hasExactlyOne(report, "layers", "refused", "a sync report"))
95
- return scopes.map((scope) => ({ scope, why: "refused" }));
97
+ return scopes.map((scope) => ({ scope, why: localOnly(scope) ? "local_only" : "refused" }));
96
98
  const layers = report.layers;
97
99
  if (!Array.isArray(layers))
98
100
  throw new TypeError("memory travel gap: report.layers must be an array");
@@ -108,7 +110,9 @@ export function memoryTravelGapOf(report, readAtDestination) {
108
110
  const gap = [];
109
111
  for (const scope of scopes) {
110
112
  const layer = byScope.get(scope);
111
- if (layer === undefined)
113
+ if (localOnly(scope))
114
+ gap.push({ scope, why: "local_only" });
115
+ else if (layer === undefined)
112
116
  gap.push({ scope, why: "not_replicated" });
113
117
  else if (layer.outcome !== "synced")
114
118
  gap.push({ scope, why: layer.outcome });
@@ -69,11 +69,11 @@ export interface MemoryEnginePlane {
69
69
  * ledger must never read as "nothing withheld"). Absent ⇒ a plane with no control plane (direct
70
70
  * hosts / tests) — no exclusion, v1 behavior byte-identical.
71
71
  */
72
- challengeExclusions?: () => ReadonlyMap<string, {
72
+ challengeExclusions?: () => Promise<ReadonlyMap<string, {
73
73
  code: "challenged" | "lineage_pending";
74
74
  generation?: number;
75
75
  at?: number;
76
- }>;
76
+ }>>;
77
77
  /**
78
78
  * design/336 §5.5 — the recall-taint propagation seat, fired at the ONE tool-face content
79
79
  * delivery point of a marked entry (`memory_get`'s successful delivery; the search list never
@@ -5,7 +5,7 @@ import { defuseFenceMarkers, delimitUntrusted, FENCED_LANE_ENVELOPE_TAGS, inline
5
5
  import { formatMemoryAge } from "../memory-recall.js";
6
6
  import { committedOriginOf } from "./frontmatter.js";
7
7
  import { MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, MEMORY_PROVENANCE_INDEX_SENTENCE, MEMORY_PROVENANCE_SEARCH_SENTENCE, MEMORY_SEARCH_BAND_ORDER_HEADER } from "./provenance-wording.js";
8
- import { deriveSupersededSet, memorySupersededNote, MEMORY_SEARCH_SUPERSEDED_TAG } from "./consolidation.js";
8
+ import { deriveSupersededSet, memorySupersededNote, MEMORY_CHALLENGED_ENTRY_GUIDANCE, MEMORY_SEARCH_SUPERSEDED_TAG } from "./consolidation.js";
9
9
  import { deriveShadowedSet, memoryShadowedNote, shadowNamesOf, MEMORY_SEARCH_SHADOWED_TAG } from "./shadowing.js";
10
10
  import { mountRuleFace, toolFace } from "../tool-catalog-entries.js";
11
11
  export const MEMORY_SEARCH_TOOL_NAME = "memory_search";
@@ -251,7 +251,7 @@ export function createMemoryEngineTools(opts) {
251
251
  const exclusions = [];
252
252
  for (const plane of planes) {
253
253
  try {
254
- exclusions.push(plane.challengeExclusions?.());
254
+ exclusions.push(await plane.challengeExclusions?.());
255
255
  }
256
256
  catch {
257
257
  return refusedSearch("challenge_ledger_unavailable", "Memory search is unavailable: the challenge ledger for a mounted memory plane cannot be read (fail-closed). Report this to the operator.", "failed");
@@ -321,7 +321,7 @@ export function createMemoryEngineTools(opts) {
321
321
  }
322
322
  let terminalExclusions;
323
323
  try {
324
- terminalExclusions = planes.map((plane) => plane.challengeExclusions?.());
324
+ terminalExclusions = await Promise.all(planes.map((plane) => plane.challengeExclusions?.()));
325
325
  }
326
326
  catch {
327
327
  return refusedSearch("challenge_ledger_unavailable", "Memory search is unavailable: the challenge ledger for a mounted memory plane cannot be read (fail-closed). Report this to the operator.", "failed");
@@ -451,7 +451,7 @@ export function createMemoryEngineTools(opts) {
451
451
  pollutionSentence(), "not_found", { slug: slug, ...(scope !== undefined ? { scope } : {}) });
452
452
  }
453
453
  try {
454
- const names = await shadowNamesAcross(planes.map((plane) => plane.challengeExclusions?.()));
454
+ const names = await shadowNamesAcross(await Promise.all(planes.map((plane) => plane.challengeExclusions?.())));
455
455
  const [shadowed] = await pruneUndeliverableCarriers([shadowedOf(matches.map((m) => m.header), names)]);
456
456
  const standing = matches.filter((m) => shadowed?.has(m.header.id) !== true);
457
457
  if (standing.length > 0 && standing.length < matches.length) {
@@ -484,7 +484,7 @@ export function createMemoryEngineTools(opts) {
484
484
  }
485
485
  let withheld;
486
486
  try {
487
- withheld = entryPlane?.challengeExclusions?.().get(entry.id);
487
+ withheld = (await entryPlane?.challengeExclusions?.())?.get(entry.id);
488
488
  }
489
489
  catch {
490
490
  return refusedGet("challenge_ledger_unavailable", "Memory read is unavailable: the challenge ledger for this memory plane cannot be read (fail-closed). Report this to the operator.", "failed");
@@ -492,7 +492,7 @@ export function createMemoryEngineTools(opts) {
492
492
  if (withheld !== undefined) {
493
493
  const genClause = withheld.generation !== undefined ? ` (challenge generation ${withheld.generation})` : "";
494
494
  const message = withheld.code === "challenged"
495
- ? `Memory entry ${entry.id} is withheld${genClause}: it has been challenged and its content is not available through memory tools. If the fact is still needed, verify it with the user and record a fresh entry from their current statement; tombstone the old entry.`
495
+ ? `Memory entry ${entry.id} is withheld${genClause}: it has been challenged and its content is not available through memory tools. ${MEMORY_CHALLENGED_ENTRY_GUIDANCE}`
496
496
  : `Memory entry ${entry.id} is withheld: its commit bookkeeping is unsettled (an interrupted transaction). It stays unavailable until the account reconciles or the host adjudicates.`;
497
497
  return refusedGet(withheld.code, message, "refused", {
498
498
  id: entry.id,
@@ -504,7 +504,7 @@ export function createMemoryEngineTools(opts) {
504
504
  let supersededBy;
505
505
  if (entryPlane !== undefined) {
506
506
  try {
507
- supersededBy = (await supersededOf(entryPlane, entryPlane.challengeExclusions?.())).get(entry.id);
507
+ supersededBy = (await supersededOf(entryPlane, await entryPlane.challengeExclusions?.())).get(entry.id);
508
508
  }
509
509
  catch {
510
510
  supersededBy = undefined;
@@ -513,7 +513,7 @@ export function createMemoryEngineTools(opts) {
513
513
  let shadowedBy;
514
514
  if (entryHeader !== undefined) {
515
515
  try {
516
- const names = await shadowNamesAcross(planes.map((plane) => plane.challengeExclusions?.()));
516
+ const names = await shadowNamesAcross(await Promise.all(planes.map((plane) => plane.challengeExclusions?.())));
517
517
  const [pruned] = await pruneUndeliverableCarriers([shadowedOf([entryHeader], names)]);
518
518
  shadowedBy = pruned?.get(entry.id);
519
519
  }
@@ -659,7 +659,7 @@ export function createMemoryEngineTools(opts) {
659
659
  const exclusions = [];
660
660
  for (const plane of planes) {
661
661
  try {
662
- exclusions.push(plane.challengeExclusions?.());
662
+ exclusions.push(await plane.challengeExclusions?.());
663
663
  }
664
664
  catch {
665
665
  return refusedIndex("challenge_ledger_unavailable", "Memory listing is unavailable: the challenge ledger for a mounted memory plane cannot be read (fail-closed). Report this to the operator.", "failed");
@@ -774,7 +774,7 @@ export function createMemoryEngineTools(opts) {
774
774
  }
775
775
  let terminalExclusions;
776
776
  try {
777
- terminalExclusions = planes.map((plane) => plane.challengeExclusions?.());
777
+ terminalExclusions = await Promise.all(planes.map((plane) => plane.challengeExclusions?.()));
778
778
  }
779
779
  catch {
780
780
  return refusedIndex("challenge_ledger_unavailable", "Memory listing is unavailable: the challenge ledger for a mounted memory plane cannot be read (fail-closed). Report this to the operator.", "failed");