@sema-agent/core 7.57.0 → 7.58.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 (198) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/dist/agents/subagent-steps.js +2 -4
  3. package/dist/brain/route-adjudicator.js +2 -1
  4. package/dist/core/a2a.d.ts +2 -1
  5. package/dist/core/a2a.js +23 -10
  6. package/dist/core/allow-entry.d.ts +2 -1
  7. package/dist/core/allow-entry.js +2 -1
  8. package/dist/core/ask-origin.d.ts +21 -2
  9. package/dist/core/ask-origin.js +5 -1
  10. package/dist/core/auto-compaction.d.ts +4 -0
  11. package/dist/core/auto-compaction.js +1 -1
  12. package/dist/core/auto-mode-directive.d.ts +29 -5
  13. package/dist/core/auto-mode-directive.js +38 -8
  14. package/dist/core/checkpoint-requirements.d.ts +7 -1
  15. package/dist/core/checkpoint-requirements.js +2 -0
  16. package/dist/core/checkpoint-store.d.ts +27 -11
  17. package/dist/core/checkpoint-store.js +13 -3
  18. package/dist/core/engine-notice.d.ts +1 -1
  19. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  20. package/dist/core/fs-write-gate-policy.js +7 -3
  21. package/dist/core/gate-fold.js +6 -3
  22. package/dist/core/gate-lanes.js +11 -2
  23. package/dist/core/git-worktree-env.d.ts +53 -11
  24. package/dist/core/git-worktree-env.js +96 -12
  25. package/dist/core/hooks.d.ts +4 -1
  26. package/dist/core/hooks.js +12 -5
  27. package/dist/core/human-input-projection.d.ts +1 -0
  28. package/dist/core/human-input-projection.js +3 -0
  29. package/dist/core/locked-config.d.ts +15 -1
  30. package/dist/core/locked-config.js +38 -2
  31. package/dist/core/mcp-call-meta.d.ts +66 -0
  32. package/dist/core/mcp-call-meta.js +103 -0
  33. package/dist/core/mcp-connection-pool.d.ts +3 -1
  34. package/dist/core/mcp-connection-pool.js +3 -1
  35. package/dist/core/mcp-failure.d.ts +7 -1
  36. package/dist/core/mcp-failure.js +10 -0
  37. package/dist/core/mcp-probe.d.ts +4 -0
  38. package/dist/core/mcp-probe.js +1 -1
  39. package/dist/core/mcp-server-link.d.ts +5 -2
  40. package/dist/core/mcp-server-spec.d.ts +46 -18
  41. package/dist/core/mcp-server-spec.js +1 -18
  42. package/dist/core/mcp.d.ts +6 -14
  43. package/dist/core/mcp.js +77 -37
  44. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  45. package/dist/core/memory-engine/scope-contract.js +80 -11
  46. package/dist/core/mode-policy.d.ts +8 -5
  47. package/dist/core/mode-policy.js +5 -4
  48. package/dist/core/mods/host.js +1 -1
  49. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  50. package/dist/core/mods/kernel/dispatch.js +10 -8
  51. package/dist/core/mods/kernel/events.d.ts +5 -1
  52. package/dist/core/mods/kernel/events.js +1 -1
  53. package/dist/core/mods/kernel/registration.d.ts +5 -1
  54. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  55. package/dist/core/mods/kernel/site-rules.js +10 -0
  56. package/dist/core/mods/package.d.ts +23 -0
  57. package/dist/core/mods/package.js +118 -0
  58. package/dist/core/mods/stations.d.ts +2 -2
  59. package/dist/core/mods/stations.js +1 -1
  60. package/dist/core/mods/tool-call.d.ts +5 -1
  61. package/dist/core/mods/tool-call.js +12 -3
  62. package/dist/core/path-guard-rows.d.ts +20 -0
  63. package/dist/core/path-guard-rows.js +11 -0
  64. package/dist/core/peer-seat.d.ts +186 -0
  65. package/dist/core/peer-seat.js +307 -0
  66. package/dist/core/present-plan-tool.d.ts +10 -1
  67. package/dist/core/present-plan-tool.js +46 -2
  68. package/dist/core/protocol-http-auth.d.ts +40 -29
  69. package/dist/core/protocol-http-auth.js +30 -32
  70. package/dist/core/redaction-marks.d.ts +16 -0
  71. package/dist/core/redaction-marks.js +16 -0
  72. package/dist/core/redaction-passes.js +8 -9
  73. package/dist/core/retention.d.ts +41 -15
  74. package/dist/core/retention.js +59 -12
  75. package/dist/core/rewrite-rejudge.d.ts +37 -0
  76. package/dist/core/rewrite-rejudge.js +40 -0
  77. package/dist/core/run-origin.d.ts +40 -0
  78. package/dist/core/run-origin.js +37 -0
  79. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  80. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  81. package/dist/core/runner/compaction-restate.d.ts +15 -6
  82. package/dist/core/runner/compaction-restate.js +28 -2
  83. package/dist/core/runner/contracts.d.ts +13 -5
  84. package/dist/core/runner/gate-exit.d.ts +18 -4
  85. package/dist/core/runner/gate-exit.js +5 -1
  86. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  87. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  88. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  89. package/dist/core/runner/prepare-config-doors.js +12 -10
  90. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  91. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  92. package/dist/core/runner/prepare-gate-stations.js +1 -1
  93. package/dist/core/runner/prepare-hands-readface.d.ts +7 -3
  94. package/dist/core/runner/prepare-hands-readface.js +4 -1
  95. package/dist/core/runner/prepare-memory.d.ts +3 -0
  96. package/dist/core/runner/prepare-memory.js +19 -23
  97. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  98. package/dist/core/runner/prepare-policy-chain.js +2 -2
  99. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  100. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  101. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  102. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  103. package/dist/core/runner/prepare-task.js +25 -12
  104. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  105. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  106. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  107. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  108. package/dist/core/runner/resume-admission.js +1 -1
  109. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  110. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  111. package/dist/core/runner/run-harness-handlers.js +1 -8
  112. package/dist/core/runner/run-identity-wiring.js +1 -0
  113. package/dist/core/runner/run-leg.js +5 -1
  114. package/dist/core/runner/run-notification-lane.js +3 -0
  115. package/dist/core/runner/terminal-account.js +3 -3
  116. package/dist/core/runner/tool-end-body.js +1 -0
  117. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  118. package/dist/core/runner/tool-occurrence.js +2 -1
  119. package/dist/core/runner/write-protection-station.d.ts +8 -2
  120. package/dist/core/runner/write-protection-station.js +2 -0
  121. package/dist/core/runner-deps.d.ts +2 -2
  122. package/dist/core/sensitive-path-policy.js +6 -7
  123. package/dist/core/session-log-transfer.d.ts +24 -0
  124. package/dist/core/session-log-transfer.js +166 -0
  125. package/dist/core/session-store.d.ts +84 -19
  126. package/dist/core/session-store.js +162 -24
  127. package/dist/core/session.d.ts +92 -1
  128. package/dist/core/shell-read-silence.js +1 -0
  129. package/dist/core/steer-replay.d.ts +4 -2
  130. package/dist/core/steer-replay.js +2 -1
  131. package/dist/core/store-contracts/checkpoint-store-contract.js +17 -0
  132. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  133. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  134. package/dist/core/store-contracts/session-store-contract.js +236 -2
  135. package/dist/core/task-event.d.ts +68 -8
  136. package/dist/core/task-registry-shared.d.ts +2 -1
  137. package/dist/core/task-spec.d.ts +37 -0
  138. package/dist/core/task-stream.d.ts +2 -1
  139. package/dist/core/terminal-cause.d.ts +1 -1
  140. package/dist/core/tool-catalog-entries.js +1 -0
  141. package/dist/core/tool-result-store.d.ts +17 -10
  142. package/dist/core/tool-result-store.js +3 -1
  143. package/dist/core/types.d.ts +1 -1
  144. package/dist/core/untrusted-egress.d.ts +0 -2
  145. package/dist/core/untrusted-egress.js +10 -14
  146. package/dist/core/wiring-manifest.d.ts +12 -3
  147. package/dist/core/wiring-manifest.js +4 -3
  148. package/dist/core/workspace-snapshot.d.ts +44 -0
  149. package/dist/core/workspace-snapshot.js +34 -0
  150. package/dist/core/write-protect.d.ts +43 -3
  151. package/dist/core/write-protect.js +43 -16
  152. package/dist/engine/execution-env/node-execution-env.js +15 -11
  153. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  154. package/dist/engine/harness/agent-harness.d.ts +5 -0
  155. package/dist/engine/harness/agent-harness.js +2 -0
  156. package/dist/engine/harness/types.d.ts +48 -7
  157. package/dist/engine/harness/types.js +5 -1
  158. package/dist/engine/llm/types.d.ts +12 -3
  159. package/dist/engine/llm/types.js +1 -1
  160. package/dist/engine/session/import-validate.js +3 -0
  161. package/dist/engine/session/memory-repo.d.ts +17 -9
  162. package/dist/engine/session/memory-repo.js +44 -34
  163. package/dist/engine/session/repo-utils.d.ts +22 -4
  164. package/dist/engine/session/repo-utils.js +49 -1
  165. package/dist/engine/session/storage-base.d.ts +10 -1
  166. package/dist/engine/session/storage-base.js +7 -1
  167. package/dist/index.d.ts +13 -6
  168. package/dist/index.js +10 -4
  169. package/dist/internal/harness-types.d.ts +1 -1
  170. package/dist/internal/harness.d.ts +2 -2
  171. package/dist/internal/harness.js +2 -2
  172. package/dist/stores/file/index.d.ts +4 -1
  173. package/dist/stores/file/index.js +4 -1
  174. package/dist/stores/file/session-store.d.ts +15 -8
  175. package/dist/stores/file/session-store.js +28 -13
  176. package/dist/tools/fs/fs-write.d.ts +6 -3
  177. package/dist/tools/fs/fs-write.js +8 -7
  178. package/dist/tools/fs/index.d.ts +3 -0
  179. package/dist/tools/fs/index.js +1 -1
  180. package/dist/tools/fs/safety.js +40 -8
  181. package/dist/tools/fs/search.js +6 -24
  182. package/dist/tools/fs/shell-read-check.d.ts +8 -1
  183. package/dist/tools/fs/shell-read-check.js +59 -15
  184. package/dist/tools/fs/shell-read-establish.js +2 -1
  185. package/dist/tools/fs/shell-read-identity.js +1 -1
  186. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  187. package/dist/tools/worktree.d.ts +42 -15
  188. package/dist/tools/worktree.js +60 -32
  189. package/package.json +4 -2
  190. package/test/export-surface.snapshot.json +63 -1
  191. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  192. package/wire-changes/core@7.58.0.json +2188 -0
  193. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  194. package/wire-changes/primitives@7.58.0.json +29 -0
  195. package/dist/primitives/credential-ref.d.ts +0 -89
  196. package/dist/primitives/credential-ref.js +0 -125
  197. package/dist/primitives/index.d.ts +0 -2
  198. package/dist/primitives/index.js +0 -1
@@ -4,6 +4,8 @@ import { PROBE_CAUSE_PATH_MAX, PROBE_REASON_MAX, inlineUntrusted, sanitizeUntrus
4
4
  import { carriesBidiControls } from "./tool-policy.js";
5
5
  import { isAutoModeFallbackCause, readDenialLimitFallback } from "./auto-mode.js";
6
6
  import { isAskOrigin, isPersistedRuleMandate } from "./ask-origin.js";
7
+ import { isRunOrigin, RUN_ORIGINS } from "./run-origin.js";
8
+ import { describeRejectedValue } from "./tool-search-setting.js";
7
9
  import { readBoundBinding } from "./skill-grant-binding.js";
8
10
  import { checkpointExecutionRecorded, executionRecordDisposition, ExecutionOutcomeConflictError, } from "./checkpoint-execution-record.js";
9
11
  import { checkpointHolderMatches, checkpointOccMatches, checkpointRevOf } from "./checkpoint-generation.js";
@@ -13,6 +15,7 @@ import { renderUntrustedCommandText, stripFormatCharacters } from "./permission-
13
15
  import { egressText } from "./untrusted-egress.js";
14
16
  import { steerReplayRefusal } from "./steer-replay.js";
15
17
  import { isPermissionMode } from "./ask-origin.js";
18
+ import { readRetentionDeclaration } from "./retention.js";
16
19
  export function mintCheckpointToken() {
17
20
  return randomBytes(16).toString("hex");
18
21
  }
@@ -79,7 +82,7 @@ const BIDI_BACKFILL_MAX_NODES = 512;
79
82
  export const MAX_PENDING_STEER_CHARS = 16_000;
80
83
  export const PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES = 48_000;
81
84
  export const MAX_PENDING_STEER_ENTRIES = Math.floor(PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES / MAX_PENDING_STEER_CHARS);
82
- export const PENDING_STEER_FROZEN_FIELDS = Object.freeze(["text", "trusted", "actor", "seq", "inputId", "priority"]);
85
+ export const PENDING_STEER_FROZEN_FIELDS = Object.freeze(["text", "trusted", "actor", "seq", "inputId", "priority", "runOrigin"]);
83
86
  export function isPlainRecord(x) {
84
87
  try {
85
88
  if (x === null || typeof x !== "object" || Array.isArray(x))
@@ -316,6 +319,7 @@ export function summarizeCheckpoint(cp, disclose) {
316
319
  ...(cp.state.workspaceHandle !== undefined
317
320
  ? { restoreMode: cp.state.workspaceHandle.restoreMode === "park_only" ? "park_only" : "snapshot" }
318
321
  : {}),
322
+ ...((runOrigin) => (isRunOrigin(runOrigin) ? { runOrigin } : {}))(cp.state.runOrigin),
319
323
  ...(tool?.preview !== undefined ? { preview: tool.preview } : {}),
320
324
  ...(tool?.previewWithheld === "oversize" || tool?.previewWithheld === "unavailable" ? { previewWithheld: tool.previewWithheld } : {}),
321
325
  ...(tool?.requiresRealApproval === true ? { requiresRealApproval: true } : {}),
@@ -335,7 +339,7 @@ export function summarizeCheckpoint(cp, disclose) {
335
339
  ...(hasBidi ? { hasBidiControls: true } : {}),
336
340
  };
337
341
  }
338
- export const CHECKPOINT_CONFIG_REFUSAL_CODES = Object.freeze(["config.spec_retired_key", "config.output_style_invalid", "config.permission_mode_invalid", "config.shell_gate_value_retired", "config.approval_reach_invalid", "config.user_invoked_skill_unknown", "config.skill_deny_unreadable", "config.user_attachment_invalid", "config.tool_face_control", "config.deps_retired_key", "config.peer_presence_invalid", "config.tool_model_gate_invalid", "config.microcompact_invalid", "config.prompt_selector_invalid", "resume_at.conflicts_resume", "resume_at.mode_without_target", "config.read_face_invalid", "config.write_face_invalid", "config.invalid_argument", "config.tool_face_invalid", "config.memory_delegation_evidence", "config.memory_provenance", "config.memory_capture_policy", "config.cross_boundary_posture", "config.advisor_tool_invalid", "config.advisor_model_invalid", "config.auto_consolidation", "config.unknown_role", "config.tool_materialize_invalid", "config.memory_persistence_invalid", "config.tool_materialize_unreachable", "config.locked_registry", "config.locked_key", "config.mcp_content_class", "config.skill_listing_budget_invalid", "config.limit_unknown_key", "config.limit_invalid", "config.attachment_invalid", "config.usage_window_invalid", "config.brain_call_guardrail_invalid", "config.retention_policy", "config.retention_capability", "config.invalid_checkpoint_store", "config.skill_base_dir_invalid", "config.host_floor_invalid"]);
342
+ export const CHECKPOINT_CONFIG_REFUSAL_CODES = Object.freeze(["config.spec_retired_key", "config.output_style_invalid", "config.permission_mode_invalid", "config.shell_gate_value_retired", "config.approval_reach_invalid", "config.run_origin_invalid", "config.user_invoked_skill_unknown", "config.skill_deny_unreadable", "config.user_attachment_invalid", "config.tool_face_control", "config.deps_retired_key", "config.peer_presence_invalid", "config.tool_model_gate_invalid", "config.microcompact_invalid", "config.prompt_selector_invalid", "resume_at.conflicts_resume", "resume_at.mode_without_target", "config.read_face_invalid", "config.write_face_invalid", "config.invalid_argument", "config.tool_face_invalid", "config.memory_delegation_evidence", "config.memory_provenance", "config.memory_capture_policy", "config.cross_boundary_posture", "config.advisor_tool_invalid", "config.advisor_model_invalid", "config.auto_consolidation", "config.unknown_role", "config.tool_materialize_invalid", "config.memory_persistence_invalid", "config.tool_materialize_unreachable", "config.locked_registry", "config.locked_key", "config.mcp_content_class", "config.skill_listing_budget_invalid", "config.limit_unknown_key", "config.limit_invalid", "config.attachment_invalid", "config.usage_window_invalid", "config.brain_call_guardrail_invalid", "config.retention_policy", "config.retention_capability", "config.invalid_checkpoint_store", "config.skill_base_dir_invalid", "config.host_floor_invalid", "config.credential_in_declaration", "config.credential_ref_invalid", "config.peer_seat_missing"]);
339
343
  export const isCheckpointConfigRefusalCode = (word) => CHECKPOINT_CONFIG_REFUSAL_CODES.some((w) => w === word);
340
344
  export class CheckpointError extends Error {
341
345
  code;
@@ -450,6 +454,7 @@ export function validatePendingSteer(steer) {
450
454
  const actor = steer.actor;
451
455
  const inputId = steer.inputId;
452
456
  const priority = steer.priority;
457
+ const runOrigin = steer.runOrigin;
453
458
  if (typeof text !== "string") {
454
459
  throw new CheckpointError("steering.invalid_content", "steering text must be a string");
455
460
  }
@@ -462,6 +467,9 @@ export function validatePendingSteer(steer) {
462
467
  if (priority !== undefined && priority !== "now" && priority !== "next" && priority !== "later") {
463
468
  throw new CheckpointError("steering.invalid_content", `steering priority "${typeof priority === "string" ? priority : priority === null ? "null" : typeof priority}" is outside the injection-priority domain ("now", "next", "later")`);
464
469
  }
470
+ if (runOrigin !== undefined && !isRunOrigin(runOrigin)) {
471
+ throw new CheckpointError("steering.invalid_content", `steering runOrigin ${describeRejectedValue(runOrigin)} is not a run origin (${RUN_ORIGINS.map((w) => JSON.stringify(w)).join(" | ")}) — omit it when the deployment's scheduler did not hand this input`);
472
+ }
465
473
  const actorTwin = actor === undefined ? undefined : captureActorAssertion(actor);
466
474
  if (inputId !== undefined && (inputId === "" || inputId.length > MAX_STEER_INPUT_ID_CHARS)) {
467
475
  throw new CheckpointError("steering.invalid_content", `steering inputId must be a non-empty string of at most ${MAX_STEER_INPUT_ID_CHARS} characters`);
@@ -481,6 +489,7 @@ export function validatePendingSteer(steer) {
481
489
  ...(actorTwin !== undefined ? { actor: actorTwin } : {}),
482
490
  inputId: inputId ?? uuidv7(),
483
491
  ...(priority !== undefined ? { priority: priority } : {}),
492
+ ...(runOrigin !== undefined ? { runOrigin } : {}),
484
493
  };
485
494
  }
486
495
  export const MAX_ACTOR_FIELD_CHARS = 256;
@@ -554,7 +563,7 @@ export function checkpointRowMatches(cp, scope, status) {
554
563
  return cp !== undefined && cp.scope === scope && cp.status === status;
555
564
  }
556
565
  export class InMemoryCheckpointStore {
557
- retention = "none";
566
+ retention;
558
567
  durability = "process-local";
559
568
  fidelity = "structured-clone";
560
569
  execution = { outcome: true };
@@ -563,6 +572,7 @@ export class InMemoryCheckpointStore {
563
572
  disclose;
564
573
  holderIsCurrent;
565
574
  constructor(opts = {}) {
575
+ this.retention = readRetentionDeclaration("InMemoryCheckpointStore.retention", opts.retention);
566
576
  this.disclose = opts.disclose;
567
577
  this.holderIsCurrent = opts.holderIsCurrent;
568
578
  if (opts.holderIsCurrent !== undefined)
@@ -72,7 +72,7 @@ export interface EngineNotice {
72
72
  * - `"mods.registration_refused"` — an extension registration was not mounted: a registration admitted before it
73
73
  * answered `{ refuse }` on `plugin.register`, or failed while judging it (fail-closed). The run goes on without it.
74
74
  * Audience `user` (the seat is in `detail`). Once per refused registration per run. `detail: { name, seat, tier,
75
- * refusedBy, reason, sessionId }` (`seat` ∈ `deployment` / `task`).
75
+ * provenance?, refusedBy, reason, sessionId }` (`seat` ∈ `deployment` / `task`; `provenance` as the host gave it, absent when none).
76
76
  * - `"skills.listing_truncated"` — the `<skills>` disclosure block did not fit its byte budget, so
77
77
  * at least one skill is listed without its description (`nameOnly`) or, in the pathological case,
78
78
  * not listed at all (`dropped`); the `Skill` tool still serves every one of them. Audience
@@ -20,8 +20,10 @@ export interface FsWriteGatePolicyOptions {
20
20
  * the `acceptDirs`/`exemptDirs` entries below always resolve against THIS value. */
21
21
  rootPath?: string;
22
22
  /** Writes whose canonical target lands inside one of these dirs are ALLOWED (the accept-session
23
- * domain, e.g. the cwd subtree after "allow all edits during this session"). */
24
- acceptDirs?: readonly string[];
23
+ * domain, e.g. the cwd subtree after "allow all edits during this session"). A getter is read once per
24
+ * call — a leg's live write roots, which move with its write location — and its entries are CANONICAL
25
+ * identities, compared as keys (a fixed list is resolved per call, as before). */
26
+ acceptDirs?: readonly string[] | (() => readonly string[]);
25
27
  /** Writes whose canonical target lands inside one of these dirs are ALLOWED and never asked
26
28
  * (auto-approved working areas: the scratchpad dir, plan files). Checked before `acceptDirs`
27
29
  * (same verdict — the split is intent/observability, exemptions are structural not session-won).
@@ -42,7 +42,11 @@ function assertExemptDirsDoNotCoverRoot(exemptDirs, rootLexical) {
42
42
  }
43
43
  export function createFsWriteGatePolicy(opts) {
44
44
  const { env, rootPath, defaultWrite } = opts;
45
- const acceptDirs = opts.acceptDirs && opts.acceptDirs.length > 0 ? opts.acceptDirs : undefined;
45
+ const acceptDirsSeat = opts.acceptDirs;
46
+ const acceptDirsNow = () => {
47
+ const dirs = typeof acceptDirsSeat === "function" ? acceptDirsSeat() : acceptDirsSeat;
48
+ return dirs !== undefined && dirs.length > 0 ? dirs : undefined;
49
+ };
46
50
  const exemptDirs = opts.exemptDirs && opts.exemptDirs.length > 0 ? opts.exemptDirs : undefined;
47
51
  const rootLexical = absoluteRootOf(rootPath, env.cwd);
48
52
  assertExemptDirsDoNotCoverRoot(exemptDirs, rootLexical);
@@ -80,12 +84,12 @@ export function createFsWriteGatePolicy(opts) {
80
84
  let refusedDomain;
81
85
  for (const [dirs, structural] of [
82
86
  [exemptDirs, true],
83
- [acceptDirs, false],
87
+ [acceptDirsNow(), false],
84
88
  ]) {
85
89
  if (!dirs)
86
90
  continue;
87
91
  for (const raw of dirs) {
88
- const dir = await canonicalizeTarget(env, raw, signal, pathFamilyOf({ root: rootPath ?? env.cwd }), rootPath);
92
+ const dir = !structural && typeof acceptDirsSeat === "function" ? { ok: true, key: raw } : await canonicalizeTarget(env, raw, signal, pathFamilyOf({ root: rootPath ?? env.cwd }), rootPath);
89
93
  if (!dir.ok)
90
94
  continue;
91
95
  if (structural) {
@@ -3,9 +3,9 @@ import { markTightenMessage } from "./safety-axis-vocab.js";
3
3
  import { PROBE_REASON_MAX, normalizeProbeCause } from "./checkpoint-store.js";
4
4
  import { normalizeReadRootCandidate } from "./read-root-candidate.js";
5
5
  import { engineFailClosedExit, hookDenyExit } from "./runner/gate-exit.js";
6
- import { readRejudge, screenRewrite } from "./rewrite-rejudge.js";
6
+ import { noteRewrite, POLICY_AUTHOR, readRejudge, screenRewrite } from "./rewrite-rejudge.js";
7
7
  import { traceHookCrash } from "./gate-crash-trace.js";
8
- import { writeProtectionMandated, writeProtectionTightenDecision } from "./write-protect.js";
8
+ import { writeProtectionMandated, writeProtectionReachOf, writeProtectionTightenDecision } from "./write-protect.js";
9
9
  import { createGateDeadline, awaitWriteProtectionJudgment, gateWaitFailureOf, withGateTimeout } from "./gate-bounded-await.js";
10
10
  import { shellReadFaceWords } from "../tools/fs/shell-read-face.js";
11
11
  import { failedJudgmentDeny } from "./runner/policy-throw.js";
@@ -54,6 +54,7 @@ export async function runGateFold(pass) {
54
54
  }
55
55
  if ((pass.decision.action === "allow" || pass.decision.action === "ask") && pass.decision.updatedInput !== undefined) {
56
56
  pass.policyRewrite = argsAsTheToolReads(pass.req, pass.decision.updatedInput);
57
+ noteRewrite(pass.rewrites, pass.req, pass.currentInput, pass.policyRewrite, POLICY_AUTHOR);
57
58
  }
58
59
  else if (pass.hookAsk?.updatedInput !== undefined) {
59
60
  pass.policyRewrite = argsAsTheToolReads(pass.req, pass.hookAsk.updatedInput);
@@ -170,7 +171,7 @@ export async function runGateFold(pass) {
170
171
  traceHookCrash(input, new Error(`write-protection judge ${kind === "timeout" ? "timed out" : "threw"} for tool "${toolName}" (toolCallId ${toolCallId}) — this call's write target could not be judged: ${thrownText(err)}`), notifier);
171
172
  });
172
173
  if (verdict !== undefined && writeProtectionMandated(verdict))
173
- pass.writeProtected = true;
174
+ pass[writeProtectionReachOf(verdict) === "spelling" ? "writeProtected" : "writeProtectedOnDisk"] = true;
174
175
  const decision = verdict === undefined ? undefined : writeProtectionTightenDecision(toolName, verdict);
175
176
  if (decision !== undefined && (writeProtectionStanding === "allow" || decision.action === "deny")) {
176
177
  pass.decision = decision;
@@ -208,6 +209,8 @@ function applyShellReadVerdict(pass, answer, toolName, shellGated) {
208
209
  pass.shellWritesPlaced = true;
209
210
  if (verdict.writeProtected === true)
210
211
  pass.writeProtected = true;
212
+ if (verdict.writeProtectedOnDisk === true)
213
+ pass.writeProtectedOnDisk = true;
211
214
  if (verdict.targetUnresolved === true)
212
215
  pass.targetUnresolved = true;
213
216
  if (verdict.unplacedOptions !== undefined)
@@ -1,6 +1,6 @@
1
1
  import { argsAsTheToolReads, withArgsReading } from "./effective-path-target.js";
2
2
  import { attest, attestationOf, bindableArgsOf, decisionText, foldHookAsk, refusalOf, refuseOutOfContractDecision } from "./tool-policy.js";
3
- import { outletAsk, readRejudge, rewriteChasedSentence, screenRewrite } from "./rewrite-rejudge.js";
3
+ import { APPROVER_AUTHOR, extensionAuthors, noteRewrite, outletAsk, POLICY_AUTHOR, readRejudge, rewriteChasedSentence, screenRewrite } from "./rewrite-rejudge.js";
4
4
  import { arbitrateByMode, classifyAsk, decisionAskClassesOf, dontAskRefusalMessage, fileCommandOptionsSentence, persistedRuleMandateOf, safetyAxisOf, stampAskOrigin } from "./ask-origin.js";
5
5
  import { classifierParseFailureDenyMessage, denialLimitFallbackMessage, rungDidNotRule, unarmedWindow } from "./auto-mode.js";
6
6
  import { classifierNoRulingArm, settleNoRulingAsk } from "./classifier-unavailable-arm.js";
@@ -77,6 +77,7 @@ export async function runGateLanes(pass) {
77
77
  requiresUserInteraction: input.requiresUserInteraction,
78
78
  probeUnanswered: pass.probeUnanswered === true,
79
79
  writeProtected: pass.writeProtected === true,
80
+ writeProtectedOnDisk: pass.writeProtectedOnDisk === true,
80
81
  targetUnresolved: pass.targetUnresolved === true,
81
82
  });
82
83
  const readFaceNow = input.readFace?.();
@@ -553,6 +554,7 @@ export async function runGateLanes(pass) {
553
554
  }
554
555
  if (approvedWithArgs && pass.decision.action === "allow" && pass.decision.updatedInput !== undefined) {
555
556
  let editArgs = pass.decision.updatedInput;
557
+ let shownToApprover = { bytes: pass.policyRewrite ?? pass.currentInput };
556
558
  let editDenied;
557
559
  let editAnswer = pass.decision;
558
560
  let unanswered;
@@ -567,6 +569,9 @@ export async function runGateLanes(pass) {
567
569
  return await untakenValueExit(pass, { value: editArgs, message: taken.refusal, deniedBy: "ask_resolution" });
568
570
  }
569
571
  editArgs = argsAsTheToolReads(pass.req, taken.value);
572
+ if (shownToApprover !== undefined)
573
+ noteRewrite(pass.rewrites, pass.req, shownToApprover.bytes, editArgs, APPROVER_AUTHOR);
574
+ shownToApprover = undefined;
570
575
  if (round >= 3) {
571
576
  editDenied = {
572
577
  action: "deny",
@@ -578,7 +583,7 @@ export async function runGateLanes(pass) {
578
583
  let editHookAsk;
579
584
  let rewrittenEdit = false;
580
585
  if (screening !== undefined) {
581
- const screened = await screening.screen(editArgs, `the approved edit for "${toolName}"`);
586
+ const screened = await screening.screen(editArgs, `the approved edit for "${toolName}"`, pass.req);
582
587
  if (screened.kind === "refused") {
583
588
  editDenied = { action: "deny", message: screened.reason };
584
589
  pass.deniedBy = "hook";
@@ -599,6 +604,7 @@ export async function runGateLanes(pass) {
599
604
  }
600
605
  const hookRead = readRejudge(pass.req, editArgs, hr);
601
606
  if (hookRead.kind === "rewritten") {
607
+ noteRewrite(pass.rewrites, pass.req, editArgs, hookRead.form, extensionAuthors(screened.rewrittenBy ?? []));
602
608
  editArgs = hookRead.form;
603
609
  rewrittenEdit = true;
604
610
  }
@@ -642,6 +648,7 @@ export async function runGateLanes(pass) {
642
648
  pass.deniedBy = "policy";
643
649
  break;
644
650
  }
651
+ noteRewrite(pass.rewrites, pass.req, editArgs, policyRead.form, POLICY_AUTHOR);
645
652
  editArgs = policyRead.form;
646
653
  rewrittenEdit = true;
647
654
  const second = screening !== undefined ? await screenRewrite(screening, pass.req, editArgs, `the rewritten edit for "${toolName}"`) : undefined;
@@ -720,6 +727,7 @@ export async function runGateLanes(pass) {
720
727
  }
721
728
  if (editRead?.kind === "approved") {
722
729
  carriedOwnAsk = editRead.outstanding ?? (editDecision.action === "ask" ? editDecision : undefined);
730
+ shownToApprover = { bytes: editArgs };
723
731
  editArgs = editRead.allow.updatedInput;
724
732
  editAnswer = editRead.allow;
725
733
  continue;
@@ -766,6 +774,7 @@ export async function runGateLanes(pass) {
766
774
  if (rr.updatedInput === undefined) {
767
775
  break;
768
776
  }
777
+ shownToApprover = { bytes: editArgs };
769
778
  editArgs = rr.updatedInput;
770
779
  editAnswer = rr;
771
780
  if (editAskDecision.action === "ask")
@@ -1,12 +1,28 @@
1
1
  import type { ExecutionEnv } from "../internal/harness-types.js";
2
- /** Private parent dir (under the repo root) that holds all managed worktrees, so {@link pruneWorktrees} and a
3
- * userland reaper can find orphans by a single known location. */
4
- export declare const WORKTREE_PARENT = ".sema-worktrees";
2
+ /** The managed parent (under the repository root) that holds every managed worktree — the reference implementation's
3
+ * `.claude/worktrees/` under this project's brand — so {@link pruneWorktrees} and a userland reaper find orphans by one known
4
+ * location. Every tree the engine mints lives at `<repoRoot>/.sema/worktrees/<slug>` (see {@link managedWorktreeDir}). */
5
+ export declare const WORKTREE_PARENT = ".sema/worktrees";
6
+ /** Why `name` is not a managed worktree name, or `undefined` when it is one. */
7
+ export declare function worktreeNameProblem(name: string): string | undefined;
8
+ /** THE managed location of the tree named `name` under `repoRoot`. */
9
+ export declare function managedWorktreeDir(repoRoot: string, name: string): string;
10
+ /** The checkout a managed worktree directory was minted under — `dir` minus its `/.sema/worktrees/<slug>` tail — or `undefined`
11
+ * when `dir` is not shaped as a managed tree. Literal, byte-exact segments (no case fold): this answer EXEMPTS, and a fold
12
+ * would widen an exemption. */
13
+ export declare function managedWorktreeBaseOf(dir: string): string | undefined;
14
+ /** The branch the path law gives the managed tree at `dir` (`sema/<slug>`), or `undefined` when `dir` is not a managed tree —
15
+ * what a recorded branch must equal before anything deletes it (a record cannot name some other branch for removal). */
16
+ export declare function managedWorktreeBranchOf(dir: string): string | undefined;
5
17
  export interface AddWorktreeOptions {
6
18
  /** The base repository root — where `git worktree add` runs (the base env's cwd is typically this). */
7
19
  repoRoot: string;
8
- /** Stable per-task identity, sanitized into the worktree dir name (for human-readable orphan diagnosis). */
20
+ /** Stable per-task identity: with no {@link name}, the tree's name is this (sanitized) plus a random suffix — a fresh name
21
+ * per mint, for the lanes that mint one tree per child. */
9
22
  sessionId: string;
23
+ /** The managed name ({@link worktreeNameProblem} grammar), used as given: the tree lands at `.sema/worktrees/<slug>` on the
24
+ * new branch `sema/<slug>`. A name whose directory or branch already exists is refused, never reused or reset. */
25
+ name?: string;
10
26
  /**
11
27
  * How to build a worktree-ROOTED {@link ExecutionEnv} for THIS env type — the only env-specific bit. Local:
12
28
  * `(dir) => new NodeExecutionEnv({ cwd: dir })`. A single-E2B deployment: an E2B env whose cwd is `dir`. The
@@ -17,16 +33,39 @@ export interface AddWorktreeOptions {
17
33
  commit?: string;
18
34
  }
19
35
  /**
20
- * design/97 CORE-6 — the env-agnostic git-WORKTREE isolation primitive. Creates a detached worktree under
21
- * {@link WORKTREE_PARENT} in `repoRoot` (via the BASE env's shell) and returns a worktree-ROOTED ExecutionEnv
22
- * (built by `rootEnvAt`) whose `destroy()` removes the worktree. A control-plane `executionEnvFactory` calls this
23
- * when its `ctx.isolation === "worktree"` and returns the result (with `destroy`); for a non-isolated task it
24
- * returns the SHARED base env (no `destroy`) so the Runner never tears the base down.
36
+ * Remove a managed worktree and — by the ONE branch rule — its branch: the branch is deleted only when its tip is still the
37
+ * commit the tree was minted at (it carries nothing the tree made); otherwise it is kept, so commits made in the tree stay
38
+ * reachable after the directory is gone. The branch half is best-effort (a branch left behind is a name, not an orphaned
39
+ * directory) and reported as `branchKept`.
40
+ *
41
+ * server [1796]②: the worktree removal itself used to be fire-and-forget — a transient failure (spawn EAGAIN/EMFILE under
42
+ * load) then left the directory AND its registration behind, which `git worktree prune` can never reclaim (prune only
43
+ * deregisters worktrees whose directory is gone). Check the result, retry once (the observed failures are transient),
44
+ * and report the outcome.
45
+ */
46
+ export declare function removeManagedWorktree(baseEnv: ExecutionEnv, repoRoot: string, worktreeDir: string, branch?: {
47
+ readonly name: string;
48
+ readonly baseSha: string;
49
+ }): Promise<{
50
+ ok: true;
51
+ branchDeleted?: string;
52
+ branchKept?: string;
53
+ } | {
54
+ ok: false;
55
+ detail: string;
56
+ }>;
57
+ /**
58
+ * design/97 CORE-6 — the env-agnostic git-WORKTREE isolation primitive, and the engine's ONE worktree mint. Creates a managed
59
+ * worktree at `<repoRoot>/.sema/worktrees/<slug>` on the new branch `sema/<slug>` (via the BASE env's shell, refusing when
60
+ * any level of that path is a symlink) and returns a worktree-ROOTED ExecutionEnv (built by `rootEnvAt`) whose `destroy()`
61
+ * removes the worktree (and its branch, by the branch rule of {@link removeManagedWorktree}). A control-plane
62
+ * `executionEnvFactory` calls this when its `ctx.isolation === "worktree"` and returns the result (with `destroy`); for a
63
+ * non-isolated task it returns the SHARED base env (no `destroy`) so the Runner never tears the base down.
25
64
  *
26
65
  * ISOLATE-ONLY: the runtime never merges — the orchestrator script reads each worktree's result and
27
66
  * decides verify/merge in userland. Caveats: `git worktree` isolates the git WORKING COPY, not
28
67
  * arbitrary shell access (bash can still reach the host — sandbox separately); UNCOMMITTED changes in the base
29
- * repo are absent in the child (detached HEAD); a worktree orphaned by a process crash is reaped by
68
+ * repo are absent in the child (the tree starts at the base commit); a worktree orphaned by a process crash is reaped by
30
69
  * {@link pruneWorktrees} (userland — there is no Runner hook for post-kill cleanup).
31
70
  */
32
71
  export declare function addWorktree(baseEnv: ExecutionEnv, opts: AddWorktreeOptions): Promise<{
@@ -34,13 +73,16 @@ export declare function addWorktree(baseEnv: ExecutionEnv, opts: AddWorktreeOpti
34
73
  destroy(): Promise<void>;
35
74
  };
36
75
  worktreeDir: string;
76
+ name: string;
77
+ branch: string;
78
+ baseSha?: string;
37
79
  }>;
38
80
  /** Reap orphaned worktrees (after a crash removed their dirs) — `git worktree prune` deregisters them. A userland
39
81
  * reaper calls this periodically against the base repo; core ships no post-kill Runner hook.
40
82
  *
41
83
  * HRD-PTL-11: the exec Result used to be discarded, so every caller had to ASSUME the prune landed — and
42
84
  * ExitWorktree's "already gone externally" leg told the model "stale git worktree metadata was pruned"
43
- * on a claim it could not have checked. Same fail-loud treatment {@link removeWorktree} already got
85
+ * on a claim it could not have checked. Same fail-loud treatment {@link removeManagedWorktree} already got
44
86
  * Report the outcome, let the caller decide what to say. Never throws (a throwing env
45
87
  * lands on the same `{ok:false}`), so a caller that ignores the value behaves exactly as before. */
46
88
  export declare function pruneWorktrees(baseEnv: ExecutionEnv, repoRoot: string): Promise<{
@@ -1,28 +1,107 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { thrownLabel, thrownText } from "./thrown-value.js";
3
- export const WORKTREE_PARENT = ".sema-worktrees";
3
+ export const WORKTREE_PARENT = ".sema/worktrees";
4
+ const WORKTREE_BRANCH_PREFIX = "sema";
5
+ const NAME_SEGMENT = /^[a-zA-Z0-9._-]+$/;
6
+ const NAME_MAX = 64;
7
+ export function worktreeNameProblem(name) {
8
+ if (name.length > NAME_MAX)
9
+ return `Invalid worktree name: must be ${NAME_MAX} characters or fewer (got ${name.length})`;
10
+ for (const segment of name.split("/")) {
11
+ if (segment === "." || segment === "..")
12
+ return `Invalid worktree name "${name}": must not contain "." or ".." path segments`;
13
+ if (segment.toLowerCase().replace(/\.+$/, "") === ".git")
14
+ return `Invalid worktree name "${name}": "${segment}" is a reserved git directory name`;
15
+ if (!NAME_SEGMENT.test(segment))
16
+ return `Invalid worktree name "${name}": each "/"-separated segment must be non-empty and contain only letters, digits, dots, underscores, and dashes`;
17
+ }
18
+ return undefined;
19
+ }
20
+ function slugOf(name) {
21
+ return name.replaceAll("/", "+");
22
+ }
23
+ export function managedWorktreeDir(repoRoot, name) {
24
+ return `${repoRoot}/${WORKTREE_PARENT}/${slugOf(name)}`;
25
+ }
26
+ export function managedWorktreeBaseOf(dir) {
27
+ const parts = dir.split("/");
28
+ if (parts.length < 4)
29
+ return undefined;
30
+ const [dot, parent, slug] = parts.slice(-3);
31
+ if (dot !== ".sema" || parent !== "worktrees" || slug === undefined || slug === "" || slug === "." || slug === "..")
32
+ return undefined;
33
+ const base = parts.slice(0, -3).join("/");
34
+ return base === "" ? "/" : base;
35
+ }
36
+ export function managedWorktreeBranchOf(dir) {
37
+ if (managedWorktreeBaseOf(dir) === undefined)
38
+ return undefined;
39
+ return `${WORKTREE_BRANCH_PREFIX}/${dir.slice(dir.lastIndexOf("/") + 1)}`;
40
+ }
4
41
  function shq(s) {
5
42
  return `'${s.replace(/'/g, "'\\''")}'`;
6
43
  }
7
- async function removeWorktree(baseEnv, repoRoot, worktreeDir) {
44
+ async function symlinkedLevel(env, repoRoot, worktreeDir) {
45
+ for (const level of [`${repoRoot}/.sema`, `${repoRoot}/${WORKTREE_PARENT}`, worktreeDir]) {
46
+ const info = await env.fileInfo(level);
47
+ if (!info.ok) {
48
+ if (info.error.code === "not_found")
49
+ continue;
50
+ return `Cannot create worktree: failed to read ${level} (${thrownText(info.error)}); a level of the managed path whose kind is unknown could be a symlink. Nothing was created.`;
51
+ }
52
+ if (info.value.kind === "symlink") {
53
+ return `Cannot create worktree: ${level} is a symlink. A symlink at .sema, .sema/worktrees or .sema/worktrees/<name> could redirect worktree creation outside the repository. Remove the symlink and retry.`;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
58
+ export async function removeManagedWorktree(baseEnv, repoRoot, worktreeDir, branch) {
8
59
  let detail = "";
9
- for (let attempt = 0; attempt < 2; attempt++) {
60
+ let removed = false;
61
+ for (let attempt = 0; attempt < 2 && !removed; attempt++) {
10
62
  try {
11
63
  const r = await baseEnv.exec(`git worktree remove --force ${shq(worktreeDir)}`, { cwd: repoRoot });
12
64
  if (r.ok && r.value.exitCode === 0)
13
- return { ok: true };
14
- detail = r.ok ? r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}` : thrownText(r.error);
65
+ removed = true;
66
+ else
67
+ detail = r.ok ? r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}` : thrownText(r.error);
15
68
  }
16
69
  catch (err) {
17
70
  detail = thrownLabel(err);
18
71
  }
19
72
  }
20
- return { ok: false, detail };
73
+ if (!removed)
74
+ return { ok: false, detail };
75
+ if (branch === undefined || branch.name !== managedWorktreeBranchOf(worktreeDir))
76
+ return { ok: true };
77
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(branch.baseSha) || /^0+$/.test(branch.baseSha))
78
+ return { ok: true, branchKept: `${branch.name} (its base commit is not a usable witness)` };
79
+ try {
80
+ const del = await baseEnv.exec(`git update-ref --no-deref -d ${shq(`refs/heads/${branch.name}`)} ${shq(branch.baseSha)}`, { cwd: repoRoot });
81
+ if (del.ok && del.value.exitCode === 0)
82
+ return { ok: true, branchDeleted: branch.name };
83
+ const tip = await baseEnv.exec(`git rev-parse --verify --quiet ${shq(`refs/heads/${branch.name}`)}`, { cwd: repoRoot });
84
+ if (tip.ok && tip.value.exitCode !== 0)
85
+ return { ok: true };
86
+ if (tip.ok && tip.value.stdout.trim() !== branch.baseSha)
87
+ return { ok: true, branchKept: `${branch.name} (it carries commits made in the worktree)` };
88
+ return { ok: true, branchKept: `${branch.name} (it could not be deleted: ${del.ok ? (del.value.stderr || del.value.stdout).trim() : thrownText(del.error)})` };
89
+ }
90
+ catch (err) {
91
+ return { ok: true, branchKept: `${branch.name} (it could not be deleted: ${thrownLabel(err)})` };
92
+ }
21
93
  }
22
94
  export async function addWorktree(baseEnv, opts) {
23
- const safe = (opts.sessionId || "task").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
24
- const worktreeDir = `${opts.repoRoot}/${WORKTREE_PARENT}/${safe}-${randomUUID().slice(0, 8)}`;
25
- const add = await baseEnv.exec(`git worktree add --detach ${shq(worktreeDir)} ${shq(opts.commit ?? "HEAD")}`, {
95
+ const name = opts.name ?? `${(opts.sessionId || "task").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 50)}-${randomUUID().slice(0, 8)}`;
96
+ const nameProblem = worktreeNameProblem(name);
97
+ if (nameProblem !== undefined)
98
+ throw new Error(nameProblem);
99
+ const worktreeDir = managedWorktreeDir(opts.repoRoot, name);
100
+ const branch = `${WORKTREE_BRANCH_PREFIX}/${slugOf(name)}`;
101
+ const symlinked = await symlinkedLevel(baseEnv, opts.repoRoot, worktreeDir);
102
+ if (symlinked !== undefined)
103
+ throw new Error(symlinked);
104
+ const add = await baseEnv.exec(`git worktree add --no-track -b ${shq(branch)} ${shq(worktreeDir)} ${shq(opts.commit ?? "HEAD")}`, {
26
105
  cwd: opts.repoRoot,
27
106
  });
28
107
  if (!add.ok || add.value.exitCode !== 0) {
@@ -34,12 +113,17 @@ export async function addWorktree(baseEnv, opts) {
34
113
  .exec(`ex="$(git rev-parse --git-path info/exclude)" && mkdir -p "$(dirname "$ex")" && ` +
35
114
  `{ grep -qxF ${excludeLine} "$ex" 2>/dev/null || printf '%s\\n' ${excludeLine} >> "$ex"; }`, { cwd: opts.repoRoot })
36
115
  .catch(() => undefined);
116
+ const baseSha = await baseEnv
117
+ .exec("git rev-parse HEAD", { cwd: worktreeDir })
118
+ .then((r) => (r.ok && r.value.exitCode === 0 && r.value.stdout.trim() !== "" ? r.value.stdout.trim() : undefined))
119
+ .catch(() => undefined);
120
+ const branchRule = baseSha !== undefined ? { name: branch, baseSha } : undefined;
37
121
  let inner;
38
122
  try {
39
123
  inner = await opts.rootEnvAt(worktreeDir);
40
124
  }
41
125
  catch (err) {
42
- await removeWorktree(baseEnv, opts.repoRoot, worktreeDir);
126
+ await removeManagedWorktree(baseEnv, opts.repoRoot, worktreeDir, branchRule);
43
127
  throw err;
44
128
  }
45
129
  const innerDestroy = inner.destroy;
@@ -50,14 +134,14 @@ export async function addWorktree(baseEnv, opts) {
50
134
  await innerDestroy.call(inner);
51
135
  }
52
136
  finally {
53
- const removed = await removeWorktree(baseEnv, opts.repoRoot, worktreeDir);
137
+ const removed = await removeManagedWorktree(baseEnv, opts.repoRoot, worktreeDir, branchRule);
54
138
  if (!removed.ok) {
55
139
  throw new Error(`git worktree remove failed twice — ${worktreeDir} is now an orphan (dir + registration remain; ` +
56
140
  `\`git worktree prune\` cannot reclaim it while the dir exists — remove it manually): ${removed.detail}`);
57
141
  }
58
142
  }
59
143
  };
60
- return { env, worktreeDir };
144
+ return { env, worktreeDir, name, branch, ...(baseSha !== undefined ? { baseSha } : {}) };
61
145
  }
62
146
  export async function pruneWorktrees(baseEnv, repoRoot) {
63
147
  try {
@@ -553,13 +553,16 @@ export interface ToolGateResult {
553
553
  gate?: GateOutcome;
554
554
  /** The args to execute with — the pass's own immutable copy, the value every judge of the call read (the model's args
555
555
  * as taken at the gate's entry, or what a hook, a policy or a person rewrote them to); re-validated by the loop. Present
556
- * on every allow exit, whether or not anything rewrote (compare values to tell); absent on a block and a suspend. */
556
+ * on every allow exit, whether or not anything rewrote ({@link rewrite} says whether, and who); absent on a block and a suspend. */
557
557
  updatedInput?: unknown;
558
558
  /** The input this pass decided on (what a refusal refused, what an allowed call runs with) as a deep, FROZEN plain-data projection
559
559
  * taken at the exit — never the live args: on a refusal every member that is not data (a bigint, a Map, a Date, a class instance, a
560
560
  * function, an accessor, a symbol-keyed member) is a `[not recorded: …]` marker; an allow exit meets only the gate's own copy, so there
561
561
  * just a bigint, a cycle's closing member and containers past 256 levels are. Beside {@link gate} on both terminal exits; absent on the suspend exit. */
562
562
  finalInput?: unknown;
563
+ /** The allow exit's record of a rewrite: `finalInput` and who replaced the args, when they are not the ones the entry took
564
+ * (`tool_end.rewrite`, the one home of its contract). Absent on every other exit and on an allow that runs the entry's bytes. */
565
+ rewrite?: import("./task-event.js").ToolInputRewrite;
563
566
  /** A blocking refusal's structured details, when the refusing station minted any (the shell read station's
564
567
  * `read_path_denied` / `readonly_out_of_root` cards): the loop attaches them to the error result it mints
565
568
  * from `reason`, so the refusal reaches `tool_end.structured` / `errorCode` exactly as the tool's own
@@ -1,4 +1,5 @@
1
1
  import { argsAsTheToolReads, stampArgsReading } from "./effective-path-target.js";
2
+ import { extensionAuthors, noteRewrite, screeningAuthorship } from "./rewrite-rejudge.js";
2
3
  import { abortedSeatDeny, decisionText, describeThrown, isEngineRefusal, ownArgs, ownedReading, refuseOutOfContractDecision, unaskedSeatAnswer } from "./tool-policy.js";
3
4
  import { createSettlementLedger, engineFailClosedExit, hookDenyExit, unownedArgsExit } from "./runner/gate-exit.js";
4
5
  import { classicEventBase, dispatchClassic, ENGINE_CORE_ANSWER, engineCore, failedHandlerClause, judgedInputOf, observePermissionDenied, recordScreeningChain } from "./mods/stations.js";
@@ -128,10 +129,11 @@ export function createPreToolUseScreening(input) {
128
129
  };
129
130
  };
130
131
  return {
131
- screen: async (args, subject) => {
132
+ screen: async (args, subject, readAs) => {
132
133
  let outcome;
134
+ const authorship = screeningAuthorship(readAs ?? {});
133
135
  try {
134
- outcome = await dispatchClassic(bus, "classic.PreToolUse", eventOf(args), { ...(input.abortSignal !== undefined ? { signal: input.abortSignal } : {}), checkAnswer: preToolUseAnswerViolation, ranks: PRE_TOOL_USE_RANKS });
136
+ outcome = await dispatchClassic(bus, "classic.PreToolUse", eventOf(args), { ...(input.abortSignal !== undefined ? { signal: input.abortSignal } : {}), checkAnswer: (a, e, by, below) => preToolUseAnswerViolation(a) ?? authorship.record(a, e, by, below), ranks: PRE_TOOL_USE_RANKS });
135
137
  }
136
138
  catch (err) {
137
139
  return { kind: "refused", reason: preToolUseRefusedReason(subject, { kind: "failed", registration: "engine", cause: "threw", reason: `could not raise the screening: ${describeThrown(err)}`, skipped: [] }) };
@@ -141,7 +143,9 @@ export function createPreToolUseScreening(input) {
141
143
  if (outcome.kind === "failed")
142
144
  return { kind: "refused", reason: preToolUseRefusedReason(subject, outcome) };
143
145
  const r = screenPreToolUseResult(outcome.answer);
144
- return { kind: "answered", answer: r === null || r === false ? undefined : r, ...(outcome.answeredBy !== undefined ? { answeredBy: outcome.answeredBy } : {}) };
146
+ const answer = r === null || r === false ? undefined : r;
147
+ const rewrittenBy = authorship.of(outcome.answer);
148
+ return { kind: "answered", answer, ...(outcome.answeredBy !== undefined ? { answeredBy: outcome.answeredBy } : {}), ...(answer?.updatedInput !== undefined ? { rewrittenBy: rewrittenBy.length > 0 || outcome.answeredBy === undefined ? rewrittenBy : [outcome.answeredBy] } : {}) };
145
149
  },
146
150
  deniedReason: (answer) => decisionText(answer) ?? `tool "${toolName}" blocked by a PreToolUse hook`,
147
151
  };
@@ -237,6 +241,7 @@ export async function runToolGate(input) {
237
241
  screening,
238
242
  afterFold: runGateLanes,
239
243
  currentInput: args,
244
+ rewrites: { entry: args, by: [] },
240
245
  req: Object.freeze({ toolName, args, toolCallId, ...(() => { const f = input.toolFaceOf?.(toolName); const read = event.readArguments; if (f !== undefined && read !== undefined)
241
246
  stampArgsReading(f, ownedReading(read)); return f !== undefined ? { face: f } : {}; })() }),
242
247
  preToolContext: [],
@@ -251,7 +256,7 @@ export async function runToolGate(input) {
251
256
  if (!owned.ok)
252
257
  return await unownedArgsExit(pass, owned.reason);
253
258
  if (screening !== undefined) {
254
- const screened = await screening.screen(pass.currentInput, `this call to "${toolName}"`);
259
+ const screened = await screening.screen(pass.currentInput, `this call to "${toolName}"`, pass.req);
255
260
  if (screened.kind === "refused") {
256
261
  return await engineFailClosedExit(pass, screened.reason);
257
262
  }
@@ -264,7 +269,9 @@ export async function runToolGate(input) {
264
269
  return hookDenyExit(pass, screening.deniedReason(r));
265
270
  }
266
271
  if (r.updatedInput !== undefined) {
267
- pass.currentInput = argsAsTheToolReads(pass.req, r.updatedInput);
272
+ const rewritten = argsAsTheToolReads(pass.req, r.updatedInput);
273
+ noteRewrite(pass.rewrites, pass.req, pass.currentInput, rewritten, extensionAuthors(screened.rewrittenBy ?? []));
274
+ pass.currentInput = rewritten;
268
275
  }
269
276
  if (r.action === "ask") {
270
277
  pass.hookAsk = r;
@@ -76,4 +76,5 @@ export declare function buildAppliedHumanInputEvent(input: {
76
76
  inputId: string;
77
77
  actor?: ActorAssertion | undefined;
78
78
  principal?: string | undefined;
79
+ runOrigin?: HumanInputEvent["runOrigin"];
79
80
  }): HumanInputEvent;
@@ -32,6 +32,7 @@ const HANDLED_HUMAN_INPUT_KEYS = {
32
32
  principal: "forwarded",
33
33
  entryId: "forwarded",
34
34
  attachments: "forwarded",
35
+ runOrigin: "forwarded",
35
36
  };
36
37
  export function buildHumanInputEvent(input) {
37
38
  void HANDLED_HUMAN_INPUT_KEYS;
@@ -47,6 +48,7 @@ export function buildHumanInputEvent(input) {
47
48
  ...(input.principal !== undefined ? { principal: input.principal } : {}),
48
49
  ...(input.entryId !== undefined ? { entryId: input.entryId } : {}),
49
50
  ...(input.attachments !== undefined && input.attachments.length > 0 ? { attachments: input.attachments.map((a) => ({ ...a })) } : {}),
51
+ ...(input.runOrigin !== undefined ? { runOrigin: input.runOrigin } : {}),
50
52
  };
51
53
  }
52
54
  export function buildAppliedHumanInputEvent(input) {
@@ -59,5 +61,6 @@ export function buildAppliedHumanInputEvent(input) {
59
61
  ...(input.actor !== undefined ? { actor: input.actor } : {}),
60
62
  ...(input.actor?.issuer !== undefined ? { issuer: input.actor.issuer } : {}),
61
63
  ...(input.principal !== undefined ? { principal: input.principal } : {}),
64
+ ...(input.runOrigin !== undefined ? { runOrigin: input.runOrigin } : {}),
62
65
  });
63
66
  }