@sema-agent/core 7.71.0 → 7.72.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 (158) hide show
  1. package/CHANGELOG.md +193 -0
  2. package/dist/agents/cross-session-ref.d.ts +2 -2
  3. package/dist/agents/cross-session-ref.js +7 -2
  4. package/dist/agents/inherited-tool-pool.d.ts +4 -1
  5. package/dist/agents/inherited-tool-pool.js +7 -5
  6. package/dist/agents/send-message-tool.js +6 -2
  7. package/dist/agents/subagent.js +5 -1
  8. package/dist/agents/verify.js +1 -0
  9. package/dist/core/a2a.d.ts +24 -3
  10. package/dist/core/a2a.js +27 -8
  11. package/dist/core/agent-state.d.ts +28 -7
  12. package/dist/core/agent-state.js +19 -6
  13. package/dist/core/approval-object.d.ts +7 -3
  14. package/dist/core/approval-object.js +30 -9
  15. package/dist/core/checkpoint-features.d.ts +13 -3
  16. package/dist/core/checkpoint-features.js +34 -5
  17. package/dist/core/checkpoint-requirements.d.ts +14 -1
  18. package/dist/core/checkpoint-row-verdict.d.ts +1 -1
  19. package/dist/core/checkpoint-row-verdict.js +3 -3
  20. package/dist/core/checkpoint-store.d.ts +4 -0
  21. package/dist/core/effective-path-target.d.ts +19 -0
  22. package/dist/core/effective-path-target.js +95 -38
  23. package/dist/core/engine-notice.d.ts +4 -1
  24. package/dist/core/engine-version.js +1 -1
  25. package/dist/core/file-history-store.d.ts +15 -4
  26. package/dist/core/file-history-store.js +53 -23
  27. package/dist/core/gate-fold.js +3 -1
  28. package/dist/core/governance-codes.d.ts +4 -1
  29. package/dist/core/governance-codes.js +4 -0
  30. package/dist/core/judged-read.d.ts +57 -0
  31. package/dist/core/judged-read.js +1 -0
  32. package/dist/core/mcp-host-seat.d.ts +5 -0
  33. package/dist/core/mcp-host-seat.js +7 -1
  34. package/dist/core/mcp.js +3 -1
  35. package/dist/core/memory-engine/index.d.ts +1 -1
  36. package/dist/core/memory-engine/index.js +1 -1
  37. package/dist/core/memory-engine/layout.js +6 -4
  38. package/dist/core/memory-engine/scope-contract.d.ts +59 -6
  39. package/dist/core/memory-engine/scope-contract.js +90 -25
  40. package/dist/core/mounted-mcp.d.ts +7 -2
  41. package/dist/core/mounted-mcp.js +10 -1
  42. package/dist/core/param-rule-reach.d.ts +8 -3
  43. package/dist/core/param-rule-reach.js +9 -1
  44. package/dist/core/parent-spec-seat.d.ts +11 -1
  45. package/dist/core/parent-spec-seat.js +14 -0
  46. package/dist/core/peer-registration.d.ts +52 -0
  47. package/dist/core/peer-registration.js +37 -0
  48. package/dist/core/peer-seat.d.ts +3 -1
  49. package/dist/core/permission-rule-model.js +1 -1
  50. package/dist/core/runner/chain-mismatch.d.ts +32 -0
  51. package/dist/core/runner/chain-mismatch.js +29 -0
  52. package/dist/core/runner/changes-history.d.ts +1 -0
  53. package/dist/core/runner/changes-history.js +2 -2
  54. package/dist/core/runner/contracts.d.ts +3 -0
  55. package/dist/core/runner/file-history-restore.d.ts +3 -1
  56. package/dist/core/runner/file-history-restore.js +9 -6
  57. package/dist/core/runner/loaded-skills.d.ts +2 -0
  58. package/dist/core/runner/loaded-skills.js +10 -0
  59. package/dist/core/runner/person-path-rows.d.ts +2 -4
  60. package/dist/core/runner/person-path-rows.js +2 -3
  61. package/dist/core/runner/prepare-caps-and-workflow.d.ts +4 -0
  62. package/dist/core/runner/prepare-caps-and-workflow.js +7 -2
  63. package/dist/core/runner/prepare-file-history.js +1 -1
  64. package/dist/core/runner/prepare-hands-readface.d.ts +5 -0
  65. package/dist/core/runner/prepare-hands-readface.js +24 -21
  66. package/dist/core/runner/prepare-inherited-gate.d.ts +2 -2
  67. package/dist/core/runner/prepare-inherited-gate.js +1 -1
  68. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -2
  69. package/dist/core/runner/prepare-memory-engine-session.js +2 -2
  70. package/dist/core/runner/prepare-memory.js +3 -15
  71. package/dist/core/runner/prepare-project-context.d.ts +1 -1
  72. package/dist/core/runner/prepare-project-context.js +3 -7
  73. package/dist/core/runner/prepare-protocol-tools.d.ts +5 -0
  74. package/dist/core/runner/prepare-protocol-tools.js +2 -2
  75. package/dist/core/runner/prepare-task.js +20 -16
  76. package/dist/core/runner/prepare-wiring-manifest.d.ts +2 -0
  77. package/dist/core/runner/prepare-wiring-manifest.js +4 -3
  78. package/dist/core/runner/read-session-changes.js +1 -1
  79. package/dist/core/runner/resume-checkpoint-screen.d.ts +8 -7
  80. package/dist/core/runner/resume-checkpoint-screen.js +7 -6
  81. package/dist/core/runner/rewind-files.js +3 -2
  82. package/dist/core/runner/run-leg.js +6 -2
  83. package/dist/core/runner/terminal-account.d.ts +4 -0
  84. package/dist/core/runner/terminal-account.js +7 -2
  85. package/dist/core/runner/tool-face-overlay.d.ts +2 -11
  86. package/dist/core/runner/tool-face-overlay.js +39 -0
  87. package/dist/core/runner/trim-stretch.js +7 -2
  88. package/dist/core/scheduler.d.ts +47 -7
  89. package/dist/core/scheduler.js +19 -7
  90. package/dist/core/secret-env.d.ts +7 -0
  91. package/dist/core/secret-env.js +1 -1
  92. package/dist/core/sensitive-path-policy.js +14 -7
  93. package/dist/core/shell-read-silence.js +1 -0
  94. package/dist/core/store-contracts/checkpoint-store-contract.js +7 -0
  95. package/dist/core/task-event.d.ts +4 -3
  96. package/dist/core/task-notification.d.ts +2 -1
  97. package/dist/core/task-spec.d.ts +13 -5
  98. package/dist/core/tool-catalog-entries.js +2 -0
  99. package/dist/core/tool-face-reader.js +1 -1
  100. package/dist/core/tool-face.d.ts +7 -0
  101. package/dist/core/tool-face.js +1 -0
  102. package/dist/core/tool-mount-facts.d.ts +4 -2
  103. package/dist/core/tool-mount-facts.js +3 -3
  104. package/dist/core/tool-mount-plan.d.ts +4 -2
  105. package/dist/core/tool-mount-plan.js +5 -5
  106. package/dist/core/tool-mount-static.d.ts +1 -1
  107. package/dist/core/tool-mount-static.js +25 -13
  108. package/dist/core/tool-registry.d.ts +33 -1
  109. package/dist/core/tool-registry.js +33 -0
  110. package/dist/core/tool-roster.d.ts +16 -0
  111. package/dist/core/tool-roster.js +6 -0
  112. package/dist/core/tool-spec.d.ts +4 -2
  113. package/dist/core/tools.d.ts +6 -0
  114. package/dist/core/tools.js +1 -1
  115. package/dist/core/wiring-manifest.d.ts +66 -12
  116. package/dist/core/wiring-manifest.js +37 -1
  117. package/dist/engine/harness/messages.d.ts +1 -1
  118. package/dist/engine/harness/messages.js +2 -1
  119. package/dist/engine/loop/types.d.ts +2 -0
  120. package/dist/engine/session/session.js +1 -1
  121. package/dist/index.d.ts +11 -7
  122. package/dist/index.js +9 -6
  123. package/dist/orchestration/workflow.js +2 -1
  124. package/dist/stores/file/adoption/marker.d.ts +2 -27
  125. package/dist/stores/file/adoption/marker.js +12 -0
  126. package/dist/stores/file/index.d.ts +1 -1
  127. package/dist/stores/file/index.js +1 -1
  128. package/dist/tools/artifact/artifact-tool.js +11 -6
  129. package/dist/tools/fs/file-read-check.d.ts +45 -11
  130. package/dist/tools/fs/file-read-check.js +200 -57
  131. package/dist/tools/fs/judged-reads.d.ts +51 -0
  132. package/dist/tools/fs/judged-reads.js +68 -0
  133. package/dist/tools/fs/safety.d.ts +8 -0
  134. package/dist/tools/fs/safety.js +12 -1
  135. package/dist/tools/fs/shell-read-check.d.ts +16 -3
  136. package/dist/tools/fs/shell-read-check.js +4 -1
  137. package/dist/tools/fs/shell-read-establish.js +13 -3
  138. package/dist/tools/scheduler-store-move.d.ts +74 -0
  139. package/dist/tools/scheduler-store-move.js +103 -0
  140. package/dist/tools/scheduler-tools.d.ts +43 -29
  141. package/dist/tools/scheduler-tools.js +161 -118
  142. package/package.json +2 -2
  143. package/test/export-surface.snapshot.json +47 -3
  144. package/wire-changes/answers/core-stores-sql@7.72.0.json +12 -0
  145. package/wire-changes/answers/core@7.72.0.json +84 -0
  146. package/wire-changes/answers/mods-kernel@7.72.0.json +7 -0
  147. package/wire-changes/answers/primitives@7.72.0.json +6 -0
  148. package/wire-changes/answers/wiki-gate@7.72.0.json +7 -0
  149. package/wire-changes/core-stores-sql@7.71.1.json +40 -0
  150. package/wire-changes/core-stores-sql@7.72.0.json +215 -0
  151. package/wire-changes/core@7.71.1.json +118 -0
  152. package/wire-changes/core@7.72.0.json +2426 -0
  153. package/wire-changes/mods-kernel@7.71.1.json +40 -0
  154. package/wire-changes/mods-kernel@7.72.0.json +147 -0
  155. package/wire-changes/primitives@7.71.1.json +40 -0
  156. package/wire-changes/primitives@7.72.0.json +143 -0
  157. package/wire-changes/wiki-gate@7.71.1.json +40 -0
  158. package/wire-changes/wiki-gate@7.72.0.json +145 -0
@@ -35,7 +35,13 @@ export function hostSeatLine(what, serverLabel, seat, writeTail) {
35
35
  : `${what} on MCP server "${serverLabel}" ended without an outcome the host could report: ${seat.condition}. The request may or may not have executed on the server — the outcome is unknown.${writeTail}`;
36
36
  }
37
37
  export function hostSeatMissing(server) {
38
- return Object.assign(new Error(`MCP server "${inlineUntrusted(server, 120)}" is declared with a host-supplied transport, and this leg holds no host seat of that name (RunInternals.mcpHostSeats) — not dialed`), { code: "config.mcp_host_seat_missing" });
38
+ return Object.assign(new Error(`MCP server "${inlineUntrusted(server, 120)}" is declared with a host-supplied transport, and this leg holds no host seat of that name (RunInternals.mcpHostSeats) — not dialed`), { code: MCP_HOST_SEAT_MISSING });
39
+ }
40
+ const MCP_HOST_SEAT_MISSING = "config.mcp_host_seat_missing";
41
+ export function hostSeatNotHandedLine(servers) {
42
+ const names = servers.map((s) => `"${inlineUntrusted(s, 120)}"`).join(", ");
43
+ const many = servers.length > 1;
44
+ return `Its MCP server${many ? "s" : ""} ${names} ${many ? "are" : "is"} declared with a host-supplied transport, and this leg hands no host seat for ${many ? "them" : "it"} (a leg hands a seat only for a server it declares with a host-supplied transport and holds a seat for) — not dialed on this wake (${MCP_HOST_SEAT_MISSING}).`;
39
45
  }
40
46
  export function hostMount(ms, run) {
41
47
  const bound = ms ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
package/dist/core/mcp.js CHANGED
@@ -20,6 +20,7 @@ import { LIST_MCP_RESOURCES, MCP_FACE_WORD_DROP_REASON, MCP_RESOURCE_LIST_ALLOW,
20
20
  import { MCP_CHARS_PER_TOKEN, fetchMcpAnswer, mcpHostReadPorts, mcpMaxOutputTokens, notServed, readMcpListing } from "./mcp-host-read.js";
21
21
  import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
22
22
  import { authorizationClause, authorizationOwed, describeHttpTransportFailure, failureFields, livenessOf, lostInFlight, namingLostSession, owesAuthorization, readMcpFailure, sessionGone, unauthorizedLine } from "./mcp-failure.js";
23
+ import { mcpPeerRegistration, peerRegistrationDigestOf } from "./peer-registration.js";
23
24
  import { DEFAULT_REQUEST_TIMEOUT_MSEC } from "@modelcontextprotocol/client";
24
25
  import { mediaBlockTypeOf } from "./image-admission.js";
25
26
  import { keepBytesWith, mediaTypePhrase, noteKeptPiece, withKeptPieces } from "./tool-result-bytes.js";
@@ -1825,6 +1826,7 @@ async function connectServer(spec, principal, onElicit, binarySeat, reminderDisc
1825
1826
  }
1826
1827
  function intakeListedTools(listed, spec, link, declared, validator, binarySeat, reminderDisclosure, through = OPEN_DOOR, transportKind, seat, echo = NO_CREDENTIAL_ECHO, onSubtreeActivity) {
1827
1828
  const declaredContentOrigin = spec.contentOrigin;
1829
+ const registration = peerRegistrationDigestOf("mcp", mcpPeerRegistration(spec, transportKind));
1828
1830
  const serverTools = [];
1829
1831
  const serverAxes = [];
1830
1832
  const gates = new Map();
@@ -1913,7 +1915,7 @@ function intakeListedTools(listed, spec, link, declared, validator, binarySeat,
1913
1915
  ...(mcpMaxResultSizeChars !== undefined ? { mcpMaxResultSizeChars } : {}),
1914
1916
  ...(mcpAlwaysLoad ? { mcpAlwaysLoad: true } : {}),
1915
1917
  ...gateFace,
1916
- mcpRemoteName: remoteName, ...boundaryFlowFace(spec.toolAxes?.[remoteName]), permissionSeat: "passthrough",
1918
+ mcpRemoteName: remoteName, ...boundaryFlowFace(spec.toolAxes?.[remoteName]), permissionSeat: "passthrough", peerRegistration: registration,
1917
1919
  execute: async (toolCallId, params, signal) => {
1918
1920
  const what = `The call to tool ${foreignLine(remoteName)}`;
1919
1921
  if (taskRequired) {
@@ -20,7 +20,7 @@ export { MEMORY_CONTROL_OBJECT_KINDS, MEMORY_GOVERNANCE_DOC_NAMES, MEMORY_ORIGIN
20
20
  export { adoptReplicaControlPlane, replicaControlPlaneStrays, type ControlPlaneAdoptionReport, type ReplicaControlPlaneStrays } from "./control-plane-adoption.js";
21
21
  export type { ConsolidationTx, MemoryBackend, MemoryGovernanceStore, MemoryControlObjectKind, MemoryGovernanceDocName, MemoryGovernanceDocs, MemoryEntry, MemoryEntryFrontmatter, MemoryEntryOrigin, MemoryOriginCause, MemoryScopeEnumeration, MemoryEntryDistilled, MemoryEntryDistilledInput, MemoryEntryHeader, ScoredMemoryEntry, NotePatch, PatchReport, MaterializedFile, MemorySessionHandle, HarvestReport, HarvestRejection, HarvestRejectionCode, MemoryAnnouncement, ScanFinding, } from "./types.js";
22
22
  export { memoryBackendContract, assertMemoryBackendSearchEquivalence, memoryGovernanceStoreContract, type MemoryBackendContractHooks, type MemoryGovernanceStoreContractHooks, } from "./memory-backend-contract.js";
23
- export { SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatUserLocalScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, isReplicableScope, isOrgScopeKey, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, type ParsedScopeKey, } from "./scope-contract.js";
23
+ export { SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatUserLocalScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, isReplicableScope, isOrgScopeKey, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, PROJECT_IDENTITY_REFUSAL_KINDS, PROJECT_MARKER_UNREADABLE_REASONS, type ProjectIdentityRefusalKind, type ProjectMarkerUnreadableReason, type ProjectIdentityRefusalDetail, type ParsedScopeKey, } from "./scope-contract.js";
24
24
  export { migrateScope, type MigrateScopeReport } from "./migrate.js";
25
25
  export { materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, type RemoteMemoryFile, type RemoteMemoryBaseline, type RemoteMaterialization, type RemoteHarvestResult, type InboundEntryFinding, } from "./data-plane.js";
26
26
  export { reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, type MemorySyncCursor, type MemorySyncConflict, type MemorySyncPlan, type RecallSource, } from "./sync.js";
@@ -18,7 +18,7 @@ export { CONSOLIDATION_WRITE_REFUSED_CODE, runMemoryConsolidationDriver, } from
18
18
  export { MEMORY_CONTROL_OBJECT_KINDS, MEMORY_GOVERNANCE_DOC_NAMES, MEMORY_ORIGIN_CAUSES, writableRootOf } from "./types.js";
19
19
  export { adoptReplicaControlPlane, replicaControlPlaneStrays } from "./control-plane-adoption.js";
20
20
  export { memoryBackendContract, assertMemoryBackendSearchEquivalence, memoryGovernanceStoreContract, } from "./memory-backend-contract.js";
21
- export { SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatUserLocalScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, isReplicableScope, isOrgScopeKey, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, } from "./scope-contract.js";
21
+ export { SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatUserLocalScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, isReplicableScope, isOrgScopeKey, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, PROJECT_IDENTITY_REFUSAL_KINDS, PROJECT_MARKER_UNREADABLE_REASONS, } from "./scope-contract.js";
22
22
  export { migrateScope } from "./migrate.js";
23
23
  export { materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, } from "./data-plane.js";
24
24
  export { reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, } from "./sync.js";
@@ -6,6 +6,7 @@ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } fr
6
6
  import { MEMORY_GOVERNANCE_DOC_NAMES, MEMORY_ORIGIN_CAUSES } from "./types.js";
7
7
  import { parseEntryFile } from "./frontmatter.js";
8
8
  import { carriesEntry, MEMORY_INDEX_FILENAME } from "./entry-scan.js";
9
+ import { normalizeProjectId } from "./scope-contract.js";
9
10
  import { PRIVATE_FILE_MODE, openExclusiveTemp } from "../exclusive-temp.js";
10
11
  import { physicalPathOf, physicalPathOfExisting, priorCallerCasedPathOf } from "../physical-path.js";
11
12
  import { dataRootSpelling, splitSpellingOf } from "../data-root.js";
@@ -163,10 +164,10 @@ export function deriveRepoMemoryDir(configRoot, repoRoot) {
163
164
  return join(configRoot, deriveRepoKey(repoRoot), "memory");
164
165
  }
165
166
  export function deriveProjectMemoryDir(configRoot, projectId) {
166
- return join(configRoot, `proj-${projectId.toLowerCase()}`, "memory");
167
+ return join(configRoot, `proj-${normalizeProjectId(projectId)}`, "memory");
167
168
  }
168
169
  export function deriveProjectControlDir(configRoot, projectId) {
169
- return join(configRoot, `proj-${projectId.toLowerCase()}`, CONTROL_PLANE_DIR);
170
+ return join(configRoot, `proj-${normalizeProjectId(projectId)}`, CONTROL_PLANE_DIR);
170
171
  }
171
172
  export const PROJECT_ID_HINTS_FILE = "project-id-hints.json";
172
173
  export function recordProjectIdHint(configRoot, repoRoot, projectId) {
@@ -181,9 +182,10 @@ export function recordProjectIdHint(configRoot, repoRoot, projectId) {
181
182
  catch {
182
183
  }
183
184
  const key = resolve(repoRoot);
184
- if (hints[key] === projectId.toLowerCase())
185
+ const norm = normalizeProjectId(projectId);
186
+ if (hints[key] === norm)
185
187
  return;
186
- hints[key] = projectId.toLowerCase();
188
+ hints[key] = norm;
187
189
  ensureDirExists(configRoot);
188
190
  atomicWriteFileSync(path, `${JSON.stringify(hints, null, 2)}\n`);
189
191
  }
@@ -136,8 +136,16 @@ export declare const PROJECT_MARKER_PATH = ".sema/project";
136
136
  * 历史 v4;铸造面 formatProjectMarker / center mint 统一产 uuidv7)。center 侧自持镜像+dev-only
137
137
  * drift 锁对着这条(registry-core coreTypes 先例)。 */
138
138
  export declare const PROJECT_ID_REGEX: RegExp;
139
+ /** Canonicalize a project UUID for equality comparisons across markers, declarations, and v2 write keys. */
140
+ export declare function normalizeProjectId(projectId: string): string;
139
141
  /** Serialize a marker file body (scaffold-side helper; the engine itself never writes one). */
140
142
  export declare function formatProjectMarker(projectId: string): string;
143
+ /** Closed discriminant words carried on project-identity and v2 memory project-write refusal details (`terminal.detail = { kind: "coded", detail }`). */
144
+ export declare const PROJECT_IDENTITY_REFUSAL_KINDS: readonly ["mismatch", "marker_unreadable", "write_project_mismatch", "write_without_verdict"];
145
+ export type ProjectIdentityRefusalKind = (typeof PROJECT_IDENTITY_REFUSAL_KINDS)[number];
146
+ /** Closed reason words carried on `{ kind: "marker_unreadable" }` refusal details (no file content, no error prose, no out-of-workspace path). */
147
+ export declare const PROJECT_MARKER_UNREADABLE_REASONS: readonly ["io_error", "unparseable", "not_uuid", "nested", "repo_root_unreadable"];
148
+ export type ProjectMarkerUnreadableReason = (typeof PROJECT_MARKER_UNREADABLE_REASONS)[number];
141
149
  /** Parse a marker body: TOML-subset `key = value` lines, `#` comments and blank lines ignored,
142
150
  * optional quotes around the value. Unknown keys are ignored (forward-compatible).
143
151
  * ANY line that starts a `projectId` assignment but is not one canonical UUID assignment is a
@@ -159,6 +167,34 @@ export declare const hostProjectMarkerFs: ProjectMarkerFs;
159
167
  * declares it is the no-I/O placeholder (`performsIo` is `false`: a leg with no env, or one handed none). An undeclared env
160
168
  * is read through, never past. */
161
169
  export declare function projectMarkerFsOf(env: ExecutionEnv): ProjectMarkerFs;
170
+ /** Machine-readable detail carried on project-identity and v2 memory project-write refusals
171
+ * (`terminal.detail = { kind: "coded", detail }`), unified on the closed `kind` discriminant
172
+ * ({@link PROJECT_IDENTITY_REFUSAL_KINDS}). */
173
+ export type ProjectIdentityRefusalDetail = {
174
+ readonly kind: "mismatch";
175
+ readonly declared: string;
176
+ readonly marker: string;
177
+ readonly markerPath: string;
178
+ } | {
179
+ readonly kind: "marker_unreadable";
180
+ /** The marker's path when it sits at the task root itself (`<task root>/.sema/project`); absent for one at a directory above it
181
+ * (the repository root above a task root, a nested level between them) — a path outside the workspace is not carried. */
182
+ readonly markerPath?: string;
183
+ readonly reason: Exclude<ProjectMarkerUnreadableReason, "repo_root_unreadable">;
184
+ } | {
185
+ readonly kind: "marker_unreadable";
186
+ readonly reason: "repo_root_unreadable";
187
+ } | {
188
+ readonly kind: "write_project_mismatch";
189
+ readonly writeScope: string;
190
+ readonly writeProjectId: string;
191
+ readonly verdictProjectId: string;
192
+ readonly verdictSource: "marker" | "declared";
193
+ } | {
194
+ readonly kind: "write_without_verdict";
195
+ readonly writeScope: string;
196
+ readonly writeProjectId: string;
197
+ };
162
198
  /**
163
199
  * design/142 §1.1 — resolve a project's identity. READS ONLY THE MARKER (复审 F2: never derives an
164
200
  * identity from a git remote; remote-URL normalization is a scaffold-side minting heuristic, not an
@@ -193,13 +229,30 @@ export interface SessionProjectVerdict {
193
229
  * `userproj:` keys). A leg that DECLARED a project consumes it, so there the fault is thrown. */
194
230
  readonly markerFault?: Error & {
195
231
  code: string;
232
+ detail?: ProjectIdentityRefusalDetail;
196
233
  };
197
234
  }
235
+ /** Project the manifest-face unreadable-marker fact from a `SessionProjectVerdict.markerFault` (same mint as P-e detail, zero second read). */
236
+ export declare function projectMarkerUnreadableOf(fault: SessionProjectVerdict["markerFault"]): {
237
+ readonly reason: ProjectMarkerUnreadableReason;
238
+ readonly markerPath?: string;
239
+ } | undefined;
240
+ /**
241
+ * The leg's ONE project-identity judge, called once per leg on the task root. Precedence:
242
+ * 1. `declared` (`TaskSpec.projectId`): validated UUID (`config.project_id_invalid`); checked against any workspace
243
+ * marker (`config.project_identity_mismatch` on disagreement, marker's own code on unreadable marker).
244
+ * 2. The leg's own workspace marker (`.sema/project`): decides when present (`source: "marker"`), even over an
245
+ * inherited `defaultProjectId`; an unreadable marker on a leg with no `declared` yields `{ root, markerFault }`
246
+ * (no project verdict — identical to a root leg).
247
+ * 3. `defaultProjectId` (a delegated child's inherited parent verdict, passed via trusted internals): used ONLY when
248
+ * both (1) and (2) yield none (`source: "declared"`), never compared against the child's marker.
249
+ */
250
+ export declare function resolveSessionProject(fs: ProjectMarkerFs, taskRoot: string, declared: string | undefined, defaultProjectId?: string): Promise<SessionProjectVerdict>;
198
251
  /**
199
- * The leg's ONE project-identity judge, called once per leg on the task root. The marker decides when the
200
- * checkout carries one; `declared` (`TaskSpec.projectId`) is the identity only where it does not. Refuses the leg when
201
- * `declared` is not a UUID (`config.project_id_invalid`), when it names a different project than the marker
202
- * (`config.project_identity_mismatch` — never file the session under the wrong project), and when the marker cannot be
203
- * read while a declaration needs checking against it (the marker's own code).
252
+ * Under `scopeContract: "v2"`, enforce project-identity consistency for a memory session against the leg's ONE
253
+ * verdict ({@link SessionProjectVerdict}): rethrow an unreadable-marker fault for sessions consuming project identity
254
+ * (`proj:` / `userproj:` scopes or writeScope), and refuse a project-scoped `writeScope` when the leg has no verdict
255
+ * (`write_without_verdict`) or targets a different project (`write_project_mismatch`, case-insensitive via
256
+ * {@link normalizeProjectId}). Called before any on-disk adoption or hint write so a refused leg mutates nothing.
204
257
  */
205
- export declare function resolveSessionProject(fs: ProjectMarkerFs, taskRoot: string, declared: string | undefined): Promise<SessionProjectVerdict>;
258
+ export declare function assertMemoryProjectVerdict(sessionProject: SessionProjectVerdict, scopes: readonly string[], writeScope: string | null): void;
@@ -5,7 +5,7 @@ import { performsIo } from "../remote-env.js";
5
5
  import { thrownText } from "../thrown-value.js";
6
6
  import { envErrorDetail } from "../../tools/fs/env-error-detail.js";
7
7
  import { describeRejectedValue } from "../tool-search-setting.js";
8
- import { canonicalize } from "./layout.js";
8
+ import { physicalPathOfExisting } from "../physical-path.js";
9
9
  function pathSegmentsDualFamily(p) {
10
10
  return p.split(/[\\/]/).filter(Boolean);
11
11
  }
@@ -185,8 +185,8 @@ export function assertScopeContractPlacement(args) {
185
185
  const personal = args.parsedScopes.filter(isPersonalPlaneScope);
186
186
  if (personal.length === 0)
187
187
  return;
188
- const rootSegs = pathSegmentsDualFamily(canonicalize(resolve(args.repoRoot))).map(foldPathCase);
189
- const dirSegs = pathSegmentsDualFamily(canonicalize(resolve(args.memoryDir))).map(foldPathCase);
188
+ const rootSegs = pathSegmentsDualFamily(physicalPathOfExisting(resolve(args.repoRoot))).map(foldPathCase);
189
+ const dirSegs = pathSegmentsDualFamily(physicalPathOfExisting(resolve(args.memoryDir))).map(foldPathCase);
190
190
  if (rootSegs.length <= dirSegs.length && rootSegs.every((s, i) => s === dirSegs[i])) {
191
191
  const e = new Error(`memory scope contract v2: personal-plane scope(s) ${personal
192
192
  .map((p) => `"${p.kind}"`)
@@ -200,15 +200,33 @@ export function assertScopeContractPlacement(args) {
200
200
  export const PROJECT_MARKER_PATH = ".sema/project";
201
201
  export const PROJECT_ID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
202
202
  const UUID_RE = PROJECT_ID_REGEX;
203
+ export function normalizeProjectId(projectId) {
204
+ return projectId.toLowerCase();
205
+ }
203
206
  export function formatProjectMarker(projectId) {
204
207
  if (!UUID_RE.test(projectId))
205
208
  throw new Error(`projectId must be a UUID, got: ${projectId}`);
206
- return `projectId = ${projectId.toLowerCase()}\n`;
209
+ return `projectId = ${normalizeProjectId(projectId)}\n`;
207
210
  }
211
+ export const PROJECT_IDENTITY_REFUSAL_KINDS = Object.freeze([
212
+ "mismatch",
213
+ "marker_unreadable",
214
+ "write_project_mismatch",
215
+ "write_without_verdict",
216
+ ]);
217
+ export const PROJECT_MARKER_UNREADABLE_REASONS = Object.freeze([
218
+ "io_error",
219
+ "unparseable",
220
+ "not_uuid",
221
+ "nested",
222
+ "repo_root_unreadable",
223
+ ]);
224
+ const CORRUPT_MARKER_REASON = new WeakMap();
208
225
  export function parseProjectMarker(body) {
209
- const corrupt = (detail) => {
226
+ const corrupt = (detail, reason) => {
210
227
  const e = new Error(`corrupt project marker: ${detail}`);
211
228
  e.code = "config.memory_project_marker";
229
+ CORRUPT_MARKER_REASON.set(e, reason);
212
230
  throw e;
213
231
  };
214
232
  let projectId;
@@ -220,13 +238,14 @@ export function parseProjectMarker(body) {
220
238
  continue;
221
239
  const m = /^projectId\s*=\s*(?:"([^"]*)"|([^"\s]+))\s*$/.exec(t);
222
240
  if (!m)
223
- corrupt(`unparseable projectId line (${t.slice(0, 48)})`);
241
+ corrupt(`unparseable projectId line (${t.slice(0, 48)})`, "unparseable");
224
242
  const value = m[1] ?? m[2] ?? "";
225
243
  if (!UUID_RE.test(value))
226
- corrupt(`projectId is not a UUID (${value.slice(0, 48) || "<empty>"})`);
227
- if (projectId !== undefined && projectId !== value.toLowerCase())
228
- corrupt("duplicate conflicting projectId lines");
229
- projectId = value.toLowerCase();
244
+ corrupt(`projectId is not a UUID (${value.slice(0, 48) || "<empty>"})`, "not_uuid");
245
+ const norm = normalizeProjectId(value);
246
+ if (projectId !== undefined && projectId !== norm)
247
+ corrupt("duplicate conflicting projectId lines", "unparseable");
248
+ projectId = norm;
230
249
  }
231
250
  if (projectId === undefined)
232
251
  return null;
@@ -254,12 +273,17 @@ export const hostProjectMarkerFs = {
254
273
  export function projectMarkerFsOf(env) {
255
274
  return performsIo(env) === false ? hostProjectMarkerFs : env;
256
275
  }
257
- function identityError(code, message) {
276
+ function identityError(code, message, detail) {
258
277
  const e = new Error(message);
259
278
  e.code = code;
279
+ if (detail !== undefined)
280
+ e.detail = detail;
260
281
  return e;
261
282
  }
262
- async function readOrFault(path, read) {
283
+ function markerUnreadable(taskDir, markerDir, reason) {
284
+ return markerDir === taskDir ? { kind: "marker_unreadable", markerPath: join(markerDir, PROJECT_MARKER_PATH), reason } : { kind: "marker_unreadable", reason };
285
+ }
286
+ async function readOrFault(path, read, detail) {
263
287
  let r;
264
288
  try {
265
289
  r = await read();
@@ -268,10 +292,10 @@ async function readOrFault(path, read) {
268
292
  r = { ok: false, error: { message: thrownText(e) } };
269
293
  }
270
294
  if (!r.ok)
271
- throw identityError("config.memory_project_marker", `project marker lookup could not read ${path}: ${envErrorDetail(r.error.message)}`);
295
+ throw identityError("config.memory_project_marker", `project marker lookup could not read ${path}: ${envErrorDetail(r.error.message)}`, detail);
272
296
  return r.value;
273
297
  }
274
- const existsOrFault = (fs, path) => readOrFault(path, () => fs.exists(path));
298
+ const existsOrFault = (fs, path, detail) => readOrFault(path, () => fs.exists(path), detail);
275
299
  function isMarkerFault(e) {
276
300
  const code = e instanceof Error ? e.code : undefined;
277
301
  return code === "config.memory_project_marker" || code === "config.memory_project_marker_nested";
@@ -279,7 +303,7 @@ function isMarkerFault(e) {
279
303
  async function gitRootOf(fs, dir) {
280
304
  let cur = resolve(dir);
281
305
  for (;;) {
282
- if (await existsOrFault(fs, join(cur, ".git")))
306
+ if (await existsOrFault(fs, join(cur, ".git"), { kind: "marker_unreadable", reason: "repo_root_unreadable" }))
283
307
  return cur;
284
308
  const parent = dirname(cur);
285
309
  if (parent === cur)
@@ -294,9 +318,10 @@ export async function resolveProjectId(fs, rootDir) {
294
318
  if (gitRoot !== undefined) {
295
319
  let cur = dir;
296
320
  while (cur !== gitRoot) {
297
- if (await existsOrFault(fs, join(cur, PROJECT_MARKER_PATH))) {
298
- throw identityError("config.memory_project_marker_nested", `nested project marker: ${join(cur, PROJECT_MARKER_PATH)} sits below the repo root (${gitRoot}) — ` +
299
- `this version supports ONE marker, at the repo root; remove the nested marker or split the repo.`);
321
+ const nestedPath = join(cur, PROJECT_MARKER_PATH);
322
+ if (await existsOrFault(fs, nestedPath, markerUnreadable(dir, cur, "io_error"))) {
323
+ throw identityError("config.memory_project_marker_nested", `nested project marker: ${nestedPath} sits below the repo root (${gitRoot}) — ` +
324
+ `this version supports ONE marker, at the repo root; remove the nested marker or split the repo.`, markerUnreadable(dir, cur, "nested"));
300
325
  }
301
326
  const parent = dirname(cur);
302
327
  if (parent === cur)
@@ -305,18 +330,35 @@ export async function resolveProjectId(fs, rootDir) {
305
330
  }
306
331
  }
307
332
  const markerFile = join(projectRoot, PROJECT_MARKER_PATH);
308
- if (!(await existsOrFault(fs, markerFile)))
333
+ if (!(await existsOrFault(fs, markerFile, markerUnreadable(dir, projectRoot, "io_error"))))
309
334
  return null;
310
- const parsed = parseProjectMarker(await readOrFault(markerFile, () => fs.readTextFile(markerFile)));
335
+ const body = await readOrFault(markerFile, () => fs.readTextFile(markerFile), markerUnreadable(dir, projectRoot, "io_error"));
336
+ let parsed;
337
+ try {
338
+ parsed = parseProjectMarker(body);
339
+ }
340
+ catch (e) {
341
+ if (isMarkerFault(e)) {
342
+ const reason = CORRUPT_MARKER_REASON.get(e) ?? "unparseable";
343
+ throw identityError("config.memory_project_marker", e.message, markerUnreadable(dir, projectRoot, reason));
344
+ }
345
+ throw e;
346
+ }
311
347
  if (!parsed)
312
348
  return null;
313
349
  return { projectId: parsed.projectId, markerDir: projectRoot };
314
350
  }
315
- export async function resolveSessionProject(fs, taskRoot, declared) {
351
+ export function projectMarkerUnreadableOf(fault) {
352
+ const d = fault?.detail;
353
+ if (d === undefined || d.kind !== "marker_unreadable")
354
+ return undefined;
355
+ return d.reason === "repo_root_unreadable" || d.markerPath === undefined ? { reason: d.reason } : { reason: d.reason, markerPath: d.markerPath };
356
+ }
357
+ export async function resolveSessionProject(fs, taskRoot, declared, defaultProjectId) {
316
358
  if (declared !== undefined && (typeof declared !== "string" || !UUID_RE.test(declared))) {
317
359
  throw identityError("config.project_id_invalid", `TaskSpec.projectId must be a project UUID (the id a \`.sema/project\` marker carries), got ${describeRejectedValue(declared)}; the leg is refused rather than filed under no project.`);
318
360
  }
319
- const declaredId = declared?.toLowerCase();
361
+ const declaredId = declared !== undefined ? normalizeProjectId(declared) : undefined;
320
362
  let marker;
321
363
  try {
322
364
  marker = await resolveProjectId(fs, taskRoot);
@@ -328,10 +370,33 @@ export async function resolveSessionProject(fs, taskRoot, declared) {
328
370
  }
329
371
  if (marker !== null) {
330
372
  if (declaredId !== undefined && declaredId !== marker.projectId) {
331
- throw identityError("config.project_identity_mismatch", `TaskSpec.projectId declares ${declaredId}, but this checkout's project marker ${join(marker.markerDir, PROJECT_MARKER_PATH)} carries ${marker.projectId} — ` +
332
- `the leg is refused rather than filed under the wrong project. Declare the marker's id, or correct the marker.`);
373
+ const markerPath = join(marker.markerDir, PROJECT_MARKER_PATH);
374
+ throw identityError("config.project_identity_mismatch", `TaskSpec.projectId declares ${declaredId}, but this checkout's project marker ${markerPath} carries ${marker.projectId} — ` +
375
+ `the leg is refused rather than filed under the wrong project. Declare the marker's id, or correct the marker.`, { kind: "mismatch", declared: declaredId, marker: marker.projectId, markerPath });
333
376
  }
334
377
  return { root: taskRoot, project: { id: marker.projectId, source: "marker" } };
335
378
  }
336
- return declaredId !== undefined ? { root: taskRoot, project: { id: declaredId, source: "declared" } } : { root: taskRoot };
379
+ const fallbackId = declaredId ?? (defaultProjectId !== undefined ? normalizeProjectId(defaultProjectId) : undefined);
380
+ return fallbackId !== undefined ? { root: taskRoot, project: { id: fallbackId, source: "declared" } } : { root: taskRoot };
381
+ }
382
+ export function assertMemoryProjectVerdict(sessionProject, scopes, writeScope) {
383
+ const consumesProjectIdentity = [...scopes, ...(writeScope !== null ? [writeScope] : [])]
384
+ .map(parseScopeKey)
385
+ .some((k) => k.kind === "proj" || k.kind === "userproj");
386
+ if (sessionProject.markerFault !== undefined && consumesProjectIdentity)
387
+ throw sessionProject.markerFault;
388
+ if (writeScope === null)
389
+ return;
390
+ const w = parseScopeKey(writeScope);
391
+ if (w.kind !== "proj" && w.kind !== "userproj")
392
+ return;
393
+ const verdict = sessionProject.project;
394
+ if (verdict === undefined) {
395
+ throw identityError("config.memory_project_identity", `memory scope contract v2: writeScope ${writeScope} targets projectId ${w.projectId}, ` +
396
+ `but this leg has no project verdict (no .sema/project marker and no TaskSpec.projectId) — refusing a project-scoped write without a project identity.`, { kind: "write_without_verdict", writeScope, writeProjectId: w.projectId });
397
+ }
398
+ if (normalizeProjectId(w.projectId) !== normalizeProjectId(verdict.id)) {
399
+ throw identityError("config.memory_project_identity", `memory scope contract v2: writeScope ${writeScope} targets projectId ${w.projectId}, ` +
400
+ `but this leg's project verdict (${verdict.source === "marker" ? "marker .sema/project" : "declared TaskSpec.projectId"}) is ${verdict.id} — refusing a mis-addressed write.`, { kind: "write_project_mismatch", writeScope, writeProjectId: w.projectId, verdictProjectId: verdict.id, verdictSource: verdict.source });
401
+ }
337
402
  }
@@ -7,7 +7,7 @@
7
7
  * The run fills it on `ToolExecuteContext.mountedMcp`; the delegation tool puts the same universe through the child's lists
8
8
  * and declares the child the servers they leave.
9
9
  */
10
- import type { McpServerSpec } from "./mcp-server-spec.js";
10
+ import { type McpServerSpec } from "./mcp-server-spec.js";
11
11
  import type { ToolContentOrigin } from "./tool-spec.js";
12
12
  import type { McpHostSeat } from "./mcp-host-seat.js";
13
13
  import type { McpInstructionsEntry } from "./prompt-section-seat.js";
@@ -111,9 +111,14 @@ export interface MountedMcpServer {
111
111
  export interface MountedMcp {
112
112
  readonly servers: ReadonlyArray<MountedMcpServer>;
113
113
  readonly aggregate: ReadonlyArray<string>;
114
- /** The run's host seats by declaration name: a child that inherits a host-transport server is handed that server's seat. */
114
+ /** The seats of the host-transport servers this leg declares ({@link hostSeatsAlong}): a child that inherits one, or an agent this
115
+ * leg wakes whose own list holds one, is handed that server's seat. A seat the leg holds for a server it does not declare is not here. */
115
116
  readonly hostSeats?: ReadonlyMap<string, McpHostSeat>;
116
117
  }
118
+ /** THE seat judge: of `held`, the seats of the host-transport servers among `servers`, by declaration name — `undefined` when none. A
119
+ * seat follows a declaration; the mount (the leg's own servers), a spawn (the servers a child inherits) and a wake (the woken leg's own
120
+ * list, read against the waker's mount) all read it. */
121
+ export declare function hostSeatsAlong(held: ReadonlyMap<string, McpHostSeat> | undefined, servers: ReadonlyArray<McpServerSpec>): ReadonlyMap<string, McpHostSeat> | undefined;
117
122
  /** A roster entry as far as this reading goes. */
118
123
  interface RosterEntry {
119
124
  readonly name: string;
@@ -1,3 +1,4 @@
1
+ import { transportKindOf } from "./mcp-server-spec.js";
1
2
  import { MCP_NAMESPACE, TOOL_NAME_MAX_CHARS, mintNamespacePrefix, normalizeNameSegment } from "@sema-agent/primitives";
2
3
  export const MCP_RESOURCE_LIST_ALLOW = "list_resources";
3
4
  export const MCP_RESOURCE_READ_ALLOW = "read_resource";
@@ -125,6 +126,13 @@ export function unretractInstructions(lane, server) {
125
126
  if (slot !== undefined)
126
127
  slot.retracting = false;
127
128
  }
129
+ export function hostSeatsAlong(held, servers) {
130
+ const seats = servers.flatMap((s) => {
131
+ const seat = transportKindOf(s) === "host" ? held?.get(s.name) : undefined;
132
+ return seat !== undefined ? [[s.name, seat]] : [];
133
+ });
134
+ return seats.length > 0 ? new Map(seats) : undefined;
135
+ }
128
136
  export function toolNamesOfServer(names, serverName) {
129
137
  const prefix = mintNamespacePrefix(MCP_NAMESPACE, serverName);
130
138
  return [...names].filter((name) => name.startsWith(prefix));
@@ -147,7 +155,8 @@ export function mountedMcpOf(input) {
147
155
  return { server, tools };
148
156
  });
149
157
  const aggregate = input.roster.filter((t) => input.aggregateNames.has(t.name)).map((t) => t.name);
150
- return { servers, aggregate, ...(input.hostSeats !== undefined ? { hostSeats: input.hostSeats } : {}) };
158
+ const hostSeats = hostSeatsAlong(input.hostSeats, input.declared ?? []);
159
+ return { servers, aggregate, ...(hostSeats !== undefined ? { hostSeats } : {}) };
151
160
  }
152
161
  export function mountedMcpPoolRows(mounted) {
153
162
  return [
@@ -1,15 +1,20 @@
1
+ import type { ToolCallPathTarget } from "./tool-face.js";
1
2
  /** The longest scalar an argument rule reads, unless a policy states its own (`caps.maxScalarValueChars`): a longer value is not
2
3
  * read, and the rule's lane wins (fail-closed). */
3
4
  export declare const DEFAULT_MAX_SCALAR_VALUE_CHARS = 16384;
4
5
  /** The call an argument rule is judged on: its arguments as the loop handed them, and its face (the tool's reading). */
5
6
  export interface ParamRuleCall {
6
7
  readonly args: unknown;
7
- readonly face?: object | undefined;
8
+ readonly face?: (object & {
9
+ readonly pathTarget?: ToolCallPathTarget | undefined;
10
+ }) | undefined;
8
11
  }
9
12
  /**
10
13
  * Does the rule on argument `param` with `pattern` reach this call? Non-object arguments ⇒ no; own top-level properties only
11
14
  * (`param` is a literal key, never a dotted path); scalar values only, trimmed, matched whole by the `*` glob; a value longer than
12
15
  * `maxScalarValueChars` FAIL-CLOSES (reached: it cannot be read, so the rule's lane wins). A call without the parameter is reached
13
- * by a rule whose value the tool's reading folds away ({@link readingAbsorbs}).
16
+ * by a rule whose value the tool's reading folds away ({@link readingAbsorbs}). A list in a slot the call's face reads element by
17
+ * element (`pathTarget.each`, the slot's `param` or an alias) is that many values: a tightening rule (`direction` `"tighten"`, a
18
+ * deny or an ask) reaches the call when it reaches ANY element, an allow only when it reaches EVERY one.
14
19
  */
15
- export declare function paramRuleReaches(call: ParamRuleCall, param: string, pattern: string, maxScalarValueChars?: number): boolean;
20
+ export declare function paramRuleReaches(call: ParamRuleCall, param: string, pattern: string, maxScalarValueChars?: number, direction?: "tighten" | "allow"): boolean;
@@ -2,13 +2,21 @@ import { canonicalize, UNCANONICALIZABLE } from "./canonical-json.js";
2
2
  import { argsAsTheToolReads } from "./effective-path-target.js";
3
3
  import { wildcardMatch } from "./namespaced-rule-name.js";
4
4
  export const DEFAULT_MAX_SCALAR_VALUE_CHARS = 16_384;
5
- export function paramRuleReaches(call, param, pattern, maxScalarValueChars = DEFAULT_MAX_SCALAR_VALUE_CHARS) {
5
+ export function paramRuleReaches(call, param, pattern, maxScalarValueChars = DEFAULT_MAX_SCALAR_VALUE_CHARS, direction = "tighten") {
6
6
  const args = call.args;
7
7
  if (typeof args !== "object" || args === null || Array.isArray(args))
8
8
  return false;
9
9
  if (!Object.hasOwn(args, param))
10
10
  return readingAbsorbs(call, args, param, pattern);
11
11
  const raw = args[param];
12
+ const pt = call.face?.pathTarget;
13
+ if (Array.isArray(raw) && pt?.each === true && [pt.param, ...(pt.aliases ?? [])].includes(param)) {
14
+ const reached = (v) => scalarReached(v, pattern, maxScalarValueChars);
15
+ return raw.length > 0 && (direction === "tighten" ? raw.some(reached) : raw.every(reached));
16
+ }
17
+ return scalarReached(raw, pattern, maxScalarValueChars);
18
+ }
19
+ function scalarReached(raw, pattern, maxScalarValueChars) {
12
20
  if (raw === undefined || raw === null)
13
21
  return false;
14
22
  const t = typeof raw;
@@ -16,7 +16,7 @@ import type { ToolExecuteContext } from "./tool-spec.js";
16
16
  import type { FastModeLeg } from "./runner/fast-mode-seat.js";
17
17
  import type { TaskSpec } from "./types.js";
18
18
  /** The fields of a spec the seat carries — one `Pick`, shared by the mint's input and the apply's target. */
19
- export type ParentSpecSeatFields = Pick<TaskSpec, "principal" | "isolationScope" | "oneShot" | "clientContext" | "onQuestion" | "mods" | "additionalDirectories" | "additionalReadDirectories" | "envFacts" | "sandbox" | "memoryPersistenceCapable" | "classifyAllShell" | "memory" | "compaction" | "skillListingBudgetFraction" | "skillListingMaxDescChars" | "fileHistory" | "projectMemory" | "promptForm" | "promptBinding" | "promptLocale" | "advisorModel" | "attachments" | "language" | "instructionFamily" | "fastMode">;
19
+ export type ParentSpecSeatFields = Pick<TaskSpec, "principal" | "isolationScope" | "oneShot" | "clientContext" | "onQuestion" | "mods" | "additionalDirectories" | "additionalReadDirectories" | "envFacts" | "sandbox" | "memoryPersistenceCapable" | "classifyAllShell" | "memory" | "compaction" | "skillListingBudgetFraction" | "skillListingMaxDescChars" | "fileHistory" | "projectMemory" | "promptForm" | "promptBinding" | "promptLocale" | "advisorModel" | "attachments" | "language" | "instructionFamily" | "fastMode" | "projectId">;
20
20
  /**
21
21
  * The seat a run hands its children. Every member is the parent's own value, frozen at mint (arrays copied and
22
22
  * frozen; the facts object copied). Members present iff the parent carries them — an absent member is "nothing to
@@ -88,6 +88,11 @@ export type ParentSpecSeatFields = Pick<TaskSpec, "principal" | "isolationScope"
88
88
  * word as the stream verb (`TaskStream.setFastMode`) last set it ({@link bindParentSpecSeatFastMode}), the spec's word before a
89
89
  * leg is bound — so a toggle reaches every child started after it. Not a clamp: either word travels as written. An ORDINARY
90
90
  * member (fill law): a child's own word stands.
91
+ * · `projectId` — the parent leg's project-identity verdict id, bound once after `resolveSessionProject`
92
+ * ({@link bindParentSpecSeatProjectId}) so delegation spawners can pass it on `RunInternals.parentProjectId` as a
93
+ * low-priority default (used only when the child declares no `projectId` and its own workspace has no marker).
94
+ * Deliberately NOT copied onto `TaskSpec.projectId` by {@link applyParentSpecSeat}, because a child's own workspace
95
+ * marker must beat the inherited default rather than mismatch against it.
91
96
  */
92
97
  export interface ParentSpecSeat {
93
98
  readonly principal?: string;
@@ -118,6 +123,7 @@ export interface ParentSpecSeat {
118
123
  readonly language?: string;
119
124
  readonly instructionFamily?: TaskSpec["instructionFamily"];
120
125
  readonly fastMode?: boolean;
126
+ readonly projectId?: string;
121
127
  }
122
128
  /** Refuse (by name, `config.deps_retired_key`) a seat that still carries a retired member. Read at every door a seat enters
123
129
  * by hand: the ctx reader, the apply, and the send lane's waker clamps. */
@@ -125,6 +131,10 @@ export declare function assertParentSpecSeatCurrent(seat: object | undefined): v
125
131
  /** Bind the seat a leg minted to that leg's fast mode: from now on the seat's `fastMode` is what the leg asks for at the moment it
126
132
  * is read — a child started after a toggle is filled with the toggled word. Once per seat, by the leg that minted it. */
127
133
  export declare function bindParentSpecSeatFastMode(seat: ParentSpecSeat, leg: Pick<FastModeLeg, "requested">): void;
134
+ /** Bind the seat a leg minted to that leg's resolved project verdict id (`sessionProject.project?.id`): from now on the seat's
135
+ * `projectId` is the leg's verdict id (whether from marker or declaration, or `undefined` when absent). Bound once per seat,
136
+ * after `resolveSessionProject` runs, so mount validation still runs before the marker walk. */
137
+ export declare function bindParentSpecSeatProjectId(seat: ParentSpecSeat, projectId: string | undefined): void;
128
138
  /** Mint the seat off the parent's REBOUND spec and its frozen question face (spec over deps — the caller resolves it once,
129
139
  * the same value the parent's own question routing reads). Absent fields stay absent; `oneShot` only when `true`. `fastMode` is
130
140
  * read when it is read: the bound leg's ask ({@link bindParentSpecSeatFastMode}) — `undefined` while the leg asks for nothing and
@@ -18,15 +18,25 @@ export function assertParentSpecSeatCurrent(seat) {
18
18
  assertNoRetiredKeys(seat, RETIRED_PARENT_SPEC_SEAT_KEYS, "ParentSpecSeat");
19
19
  }
20
20
  const SEAT_FAST_MODE_LEG = new WeakMap();
21
+ const SEAT_PROJECT_ID = new WeakMap();
21
22
  export function bindParentSpecSeatFastMode(seat, leg) {
22
23
  const cell = SEAT_FAST_MODE_LEG.get(seat);
23
24
  if (cell === undefined || cell.leg !== undefined)
24
25
  throw new Error("parentSpecSeat: a seat's fast mode is bound once, by the leg that minted it");
25
26
  cell.leg = leg;
26
27
  }
28
+ export function bindParentSpecSeatProjectId(seat, projectId) {
29
+ const cell = SEAT_PROJECT_ID.get(seat);
30
+ if (cell === undefined || cell.bound)
31
+ throw new Error("parentSpecSeat: a seat's project id is bound once, by the leg that minted it");
32
+ cell.bound = true;
33
+ cell.id = projectId;
34
+ }
27
35
  export function parentSpecSeatOf(spec, frozenOnQuestion) {
28
36
  const word = spec.fastMode;
29
37
  const cell = {};
38
+ const projectWord = spec.projectId;
39
+ const projectCell = { bound: false };
30
40
  const seat = Object.freeze({
31
41
  ...(spec.principal !== undefined ? { principal: spec.principal } : {}),
32
42
  ...(spec.isolationScope !== undefined ? { isolationScope: spec.isolationScope } : {}),
@@ -56,9 +66,13 @@ export function parentSpecSeatOf(spec, frozenOnQuestion) {
56
66
  const asked = cell.leg?.requested;
57
67
  return asked === undefined || (!asked && word === undefined) ? word : asked;
58
68
  },
69
+ get projectId() {
70
+ return projectCell.bound ? projectCell.id : projectWord;
71
+ },
59
72
  ...clampFieldSeatsOf(spec),
60
73
  });
61
74
  SEAT_FAST_MODE_LEG.set(seat, cell);
75
+ SEAT_PROJECT_ID.set(seat, projectCell);
62
76
  return seat;
63
77
  }
64
78
  export function applyParentSpecSeat(child, seat) {