@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.
- package/CHANGELOG.md +385 -0
- package/dist/agents/subagent-steps.js +2 -4
- package/dist/brain/route-adjudicator.js +2 -1
- package/dist/core/a2a.d.ts +2 -1
- package/dist/core/a2a.js +23 -10
- package/dist/core/allow-entry.d.ts +2 -1
- package/dist/core/allow-entry.js +2 -1
- package/dist/core/ask-origin.d.ts +21 -2
- package/dist/core/ask-origin.js +5 -1
- package/dist/core/auto-compaction.d.ts +4 -0
- package/dist/core/auto-compaction.js +1 -1
- package/dist/core/auto-mode-directive.d.ts +29 -5
- package/dist/core/auto-mode-directive.js +38 -8
- package/dist/core/checkpoint-requirements.d.ts +7 -1
- package/dist/core/checkpoint-requirements.js +2 -0
- package/dist/core/checkpoint-store.d.ts +27 -11
- package/dist/core/checkpoint-store.js +13 -3
- package/dist/core/engine-notice.d.ts +1 -1
- package/dist/core/fs-write-gate-policy.d.ts +4 -2
- package/dist/core/fs-write-gate-policy.js +7 -3
- package/dist/core/gate-fold.js +6 -3
- package/dist/core/gate-lanes.js +11 -2
- package/dist/core/git-worktree-env.d.ts +53 -11
- package/dist/core/git-worktree-env.js +96 -12
- package/dist/core/hooks.d.ts +4 -1
- package/dist/core/hooks.js +12 -5
- package/dist/core/human-input-projection.d.ts +1 -0
- package/dist/core/human-input-projection.js +3 -0
- package/dist/core/locked-config.d.ts +15 -1
- package/dist/core/locked-config.js +38 -2
- package/dist/core/mcp-call-meta.d.ts +66 -0
- package/dist/core/mcp-call-meta.js +103 -0
- package/dist/core/mcp-connection-pool.d.ts +3 -1
- package/dist/core/mcp-connection-pool.js +3 -1
- package/dist/core/mcp-failure.d.ts +7 -1
- package/dist/core/mcp-failure.js +10 -0
- package/dist/core/mcp-probe.d.ts +4 -0
- package/dist/core/mcp-probe.js +1 -1
- package/dist/core/mcp-server-link.d.ts +5 -2
- package/dist/core/mcp-server-spec.d.ts +46 -18
- package/dist/core/mcp-server-spec.js +1 -18
- package/dist/core/mcp.d.ts +6 -14
- package/dist/core/mcp.js +77 -37
- package/dist/core/memory-engine/scope-contract.d.ts +45 -4
- package/dist/core/memory-engine/scope-contract.js +80 -11
- package/dist/core/mode-policy.d.ts +8 -5
- package/dist/core/mode-policy.js +5 -4
- package/dist/core/mods/host.js +1 -1
- package/dist/core/mods/kernel/dispatch.d.ts +3 -0
- package/dist/core/mods/kernel/dispatch.js +10 -8
- package/dist/core/mods/kernel/events.d.ts +5 -1
- package/dist/core/mods/kernel/events.js +1 -1
- package/dist/core/mods/kernel/registration.d.ts +5 -1
- package/dist/core/mods/kernel/site-rules.d.ts +3 -0
- package/dist/core/mods/kernel/site-rules.js +10 -0
- package/dist/core/mods/package.d.ts +23 -0
- package/dist/core/mods/package.js +118 -0
- package/dist/core/mods/stations.d.ts +2 -2
- package/dist/core/mods/stations.js +1 -1
- package/dist/core/mods/tool-call.d.ts +5 -1
- package/dist/core/mods/tool-call.js +12 -3
- package/dist/core/path-guard-rows.d.ts +20 -0
- package/dist/core/path-guard-rows.js +11 -0
- package/dist/core/peer-seat.d.ts +186 -0
- package/dist/core/peer-seat.js +307 -0
- package/dist/core/present-plan-tool.d.ts +10 -1
- package/dist/core/present-plan-tool.js +46 -2
- package/dist/core/protocol-http-auth.d.ts +40 -29
- package/dist/core/protocol-http-auth.js +30 -32
- package/dist/core/redaction-marks.d.ts +16 -0
- package/dist/core/redaction-marks.js +16 -0
- package/dist/core/redaction-passes.js +8 -9
- package/dist/core/retention.d.ts +41 -15
- package/dist/core/retention.js +59 -12
- package/dist/core/rewrite-rejudge.d.ts +37 -0
- package/dist/core/rewrite-rejudge.js +40 -0
- package/dist/core/run-origin.d.ts +40 -0
- package/dist/core/run-origin.js +37 -0
- package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
- package/dist/core/runner/advertised-writable-dirs.js +126 -0
- package/dist/core/runner/compaction-restate.d.ts +15 -6
- package/dist/core/runner/compaction-restate.js +28 -2
- package/dist/core/runner/contracts.d.ts +13 -5
- package/dist/core/runner/gate-exit.d.ts +18 -4
- package/dist/core/runner/gate-exit.js +5 -1
- package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
- package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
- package/dist/core/runner/prepare-config-doors.d.ts +8 -5
- package/dist/core/runner/prepare-config-doors.js +12 -10
- package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
- package/dist/core/runner/prepare-delegation-surface.js +15 -18
- package/dist/core/runner/prepare-gate-stations.js +1 -1
- package/dist/core/runner/prepare-hands-readface.d.ts +7 -3
- package/dist/core/runner/prepare-hands-readface.js +4 -1
- package/dist/core/runner/prepare-memory.d.ts +3 -0
- package/dist/core/runner/prepare-memory.js +19 -23
- package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
- package/dist/core/runner/prepare-policy-chain.js +2 -2
- package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
- package/dist/core/runner/prepare-protocol-tools.js +3 -3
- package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
- package/dist/core/runner/prepare-suspend-saga.js +2 -1
- package/dist/core/runner/prepare-task.js +25 -12
- package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
- package/dist/core/runner/prepare-wiring-manifest.js +2 -2
- package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
- package/dist/core/runner/prepare-workspace-restore.js +4 -4
- package/dist/core/runner/resume-admission.js +1 -1
- package/dist/core/runner/resume-checkpoint-screen.js +2 -0
- package/dist/core/runner/run-harness-handlers.d.ts +3 -4
- package/dist/core/runner/run-harness-handlers.js +1 -8
- package/dist/core/runner/run-identity-wiring.js +1 -0
- package/dist/core/runner/run-leg.js +5 -1
- package/dist/core/runner/run-notification-lane.js +3 -0
- package/dist/core/runner/terminal-account.js +3 -3
- package/dist/core/runner/tool-end-body.js +1 -0
- package/dist/core/runner/tool-occurrence.d.ts +4 -1
- package/dist/core/runner/tool-occurrence.js +2 -1
- package/dist/core/runner/write-protection-station.d.ts +8 -2
- package/dist/core/runner/write-protection-station.js +2 -0
- package/dist/core/runner-deps.d.ts +2 -2
- package/dist/core/sensitive-path-policy.js +6 -7
- package/dist/core/session-log-transfer.d.ts +24 -0
- package/dist/core/session-log-transfer.js +166 -0
- package/dist/core/session-store.d.ts +84 -19
- package/dist/core/session-store.js +162 -24
- package/dist/core/session.d.ts +92 -1
- package/dist/core/shell-read-silence.js +1 -0
- package/dist/core/steer-replay.d.ts +4 -2
- package/dist/core/steer-replay.js +2 -1
- package/dist/core/store-contracts/checkpoint-store-contract.js +17 -0
- package/dist/core/store-contracts/session-repo-contract.js +112 -5
- package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
- package/dist/core/store-contracts/session-store-contract.js +236 -2
- package/dist/core/task-event.d.ts +68 -8
- package/dist/core/task-registry-shared.d.ts +2 -1
- package/dist/core/task-spec.d.ts +37 -0
- package/dist/core/task-stream.d.ts +2 -1
- package/dist/core/terminal-cause.d.ts +1 -1
- package/dist/core/tool-catalog-entries.js +1 -0
- package/dist/core/tool-result-store.d.ts +17 -10
- package/dist/core/tool-result-store.js +3 -1
- package/dist/core/types.d.ts +1 -1
- package/dist/core/untrusted-egress.d.ts +0 -2
- package/dist/core/untrusted-egress.js +10 -14
- package/dist/core/wiring-manifest.d.ts +12 -3
- package/dist/core/wiring-manifest.js +4 -3
- package/dist/core/workspace-snapshot.d.ts +44 -0
- package/dist/core/workspace-snapshot.js +34 -0
- package/dist/core/write-protect.d.ts +43 -3
- package/dist/core/write-protect.js +43 -16
- package/dist/engine/execution-env/node-execution-env.js +15 -11
- package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
- package/dist/engine/harness/agent-harness.d.ts +5 -0
- package/dist/engine/harness/agent-harness.js +2 -0
- package/dist/engine/harness/types.d.ts +48 -7
- package/dist/engine/harness/types.js +5 -1
- package/dist/engine/llm/types.d.ts +12 -3
- package/dist/engine/llm/types.js +1 -1
- package/dist/engine/session/import-validate.js +3 -0
- package/dist/engine/session/memory-repo.d.ts +17 -9
- package/dist/engine/session/memory-repo.js +44 -34
- package/dist/engine/session/repo-utils.d.ts +22 -4
- package/dist/engine/session/repo-utils.js +49 -1
- package/dist/engine/session/storage-base.d.ts +10 -1
- package/dist/engine/session/storage-base.js +7 -1
- package/dist/index.d.ts +13 -6
- package/dist/index.js +10 -4
- package/dist/internal/harness-types.d.ts +1 -1
- package/dist/internal/harness.d.ts +2 -2
- package/dist/internal/harness.js +2 -2
- package/dist/stores/file/index.d.ts +4 -1
- package/dist/stores/file/index.js +4 -1
- package/dist/stores/file/session-store.d.ts +15 -8
- package/dist/stores/file/session-store.js +28 -13
- package/dist/tools/fs/fs-write.d.ts +6 -3
- package/dist/tools/fs/fs-write.js +8 -7
- package/dist/tools/fs/index.d.ts +3 -0
- package/dist/tools/fs/index.js +1 -1
- package/dist/tools/fs/safety.js +40 -8
- package/dist/tools/fs/search.js +6 -24
- package/dist/tools/fs/shell-read-check.d.ts +8 -1
- package/dist/tools/fs/shell-read-check.js +59 -15
- package/dist/tools/fs/shell-read-establish.js +2 -1
- package/dist/tools/fs/shell-read-identity.js +1 -1
- package/dist/tools/fs/shell-read-judge.d.ts +10 -1
- package/dist/tools/worktree.d.ts +42 -15
- package/dist/tools/worktree.js +60 -32
- package/package.json +4 -2
- package/test/export-surface.snapshot.json +63 -1
- package/wire-changes/core-stores-sql@7.58.0.json +29 -0
- package/wire-changes/core@7.58.0.json +2188 -0
- package/wire-changes/mods-kernel@7.58.0.json +81 -0
- package/wire-changes/primitives@7.58.0.json +29 -0
- package/dist/primitives/credential-ref.d.ts +0 -89
- package/dist/primitives/credential-ref.js +0 -125
- package/dist/primitives/index.d.ts +0 -2
- package/dist/primitives/index.js +0 -1
package/dist/tools/fs/safety.js
CHANGED
|
@@ -444,7 +444,7 @@ function within(rootCanonical, p) {
|
|
|
444
444
|
}
|
|
445
445
|
export async function resolveKey(env, rootCanonical, path, signal, baseCwd, additionalRoots, exactFileReadExemption, readDeny, containmentFace) {
|
|
446
446
|
const views = await readPath(env, path, baseCwd ?? rootCanonical, { root: rootCanonical, ...(baseCwd !== undefined ? { cwd: baseCwd } : {}) }, { intent: "resolve", views: readDeny !== undefined ? "chain" : "canonical" }, signal);
|
|
447
|
-
const canon = views.canonical ??
|
|
447
|
+
const canon = views.canonical ?? { ok: false, message: `cannot resolve path "${clipSpelling(path)}": ${views.lexical?.kind === "unreadable" ? views.lexical.reason : "the environment was not asked where it lands"}; refused.` };
|
|
448
448
|
if (!canon.ok)
|
|
449
449
|
return { ok: false, violation: { code: "invalid", message: canon.message } };
|
|
450
450
|
const key = canon.key;
|
|
@@ -545,6 +545,10 @@ async function probeRealTarget(env, path, target, family, signal) {
|
|
|
545
545
|
if (!newPath.ok) {
|
|
546
546
|
return { ok: false, message: newPath.message, unresolvedSymlink: true };
|
|
547
547
|
}
|
|
548
|
+
if ("reprobe" in newPath) {
|
|
549
|
+
abs = newPath.reprobe;
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
548
552
|
return { ok: true, key: newPath.key };
|
|
549
553
|
}
|
|
550
554
|
const canon = await env.canonicalPath(abs, signal);
|
|
@@ -559,6 +563,10 @@ async function probeRealTarget(env, path, target, family, signal) {
|
|
|
559
563
|
if (!viaAncestors.ok) {
|
|
560
564
|
return { ok: false, message: viaAncestors.message, unresolvedSymlink: true };
|
|
561
565
|
}
|
|
566
|
+
if ("reprobe" in viaAncestors) {
|
|
567
|
+
abs = viaAncestors.reprobe;
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
562
570
|
return { ok: true, key: viaAncestors.key };
|
|
563
571
|
}
|
|
564
572
|
if (!env.readLink) {
|
|
@@ -584,7 +592,7 @@ async function probeRealTarget(env, path, target, family, signal) {
|
|
|
584
592
|
}
|
|
585
593
|
abs = reabs.value;
|
|
586
594
|
}
|
|
587
|
-
return { ok: false, message: `
|
|
595
|
+
return { ok: false, message: `resolving "${path}" exceeded the hop cap (links followed, or a \`..\` back into an existing directory re-probed); target unresolved`, unresolvedSymlink: true };
|
|
588
596
|
}
|
|
589
597
|
function parentDir(abs) {
|
|
590
598
|
const i = lastSepIndex(abs);
|
|
@@ -623,15 +631,39 @@ async function canonicalizeNewPath(env, abs, family, signal, opts) {
|
|
|
623
631
|
if (!canon.ok) {
|
|
624
632
|
return { ok: false, message: `cannot canonicalize existing ancestor "${candidate}": ${canon.error.message}` };
|
|
625
633
|
}
|
|
626
|
-
|
|
627
|
-
const canonSep = nativeSepOf(canon.value);
|
|
628
|
-
if (tailSegments.length === 0)
|
|
629
|
-
return { ok: true, key: canon.value };
|
|
630
|
-
return { ok: true, key: [canon.value.replace(family === "win" ? /[\\/]+$/ : /\/+$/, ""), ...tailSegments].join(canonSep) };
|
|
634
|
+
return { ok: true, ...rejoinMissingTail(canon.value, tail.reverse(), family) };
|
|
631
635
|
}
|
|
632
636
|
tail.push(parts.pop());
|
|
633
637
|
}
|
|
634
|
-
|
|
638
|
+
const share = family === "win" && isUncSpelling(abs) ? tail.pop() : undefined;
|
|
639
|
+
return { ok: true, ...rejoinMissingTail(`${[...parts, ...(share !== undefined ? [share] : [])].join(sep)}${sep}`, tail.reverse(), family) };
|
|
640
|
+
}
|
|
641
|
+
function rejoinMissingTail(canonical, tail, family) {
|
|
642
|
+
const trimmed = (at) => at.replace(family === "win" ? /[\\/]+$/ : /\/+$/, "");
|
|
643
|
+
let at = canonical;
|
|
644
|
+
const names = [];
|
|
645
|
+
for (let i = 0; i < tail.length; i++) {
|
|
646
|
+
const seg = tail[i];
|
|
647
|
+
if (seg === "" || seg === ".")
|
|
648
|
+
continue;
|
|
649
|
+
if (seg !== "..")
|
|
650
|
+
names.push(seg);
|
|
651
|
+
else if (names.length > 1)
|
|
652
|
+
names.pop();
|
|
653
|
+
else {
|
|
654
|
+
if (names.length === 1)
|
|
655
|
+
names.pop();
|
|
656
|
+
else {
|
|
657
|
+
const up = normalizeAbsPathLexically(`${at}/..`);
|
|
658
|
+
if (up !== normalizeAbsPathLexically(at))
|
|
659
|
+
at = up;
|
|
660
|
+
}
|
|
661
|
+
const rest = tail.slice(i + 1);
|
|
662
|
+
if (rest.some((s) => s !== "" && s !== "."))
|
|
663
|
+
return { reprobe: [trimmed(at), ...rest].join(nativeSepOf(at)) };
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return { key: names.length === 0 ? at : [trimmed(at), ...names].join(nativeSepOf(at)) };
|
|
635
667
|
}
|
|
636
668
|
export function violationText(toolName, v) {
|
|
637
669
|
return `Error (${toolName}): ${v.message}`;
|
package/dist/tools/fs/search.js
CHANGED
|
@@ -40,25 +40,6 @@ const TYPE_GLOBS = {
|
|
|
40
40
|
css: "*.{css,scss,less}",
|
|
41
41
|
};
|
|
42
42
|
const basename = (p) => p.slice(Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\")) + 1);
|
|
43
|
-
function collapseDotSegments(p) {
|
|
44
|
-
const win = isWinFormPath(p);
|
|
45
|
-
const lead = (win ? /^[\\/]*/ : /^\/*/).exec(p)?.[0] ?? "";
|
|
46
|
-
const sep = win ? "\\" : "/";
|
|
47
|
-
const parts = p.slice(lead.length).split(win ? /[\\/]+/ : /\/+/);
|
|
48
|
-
const floor = !win ? 0 : lead.length >= 2 ? 2 : /^[A-Za-z]:$/.test(parts[0] ?? "") ? 1 : 0;
|
|
49
|
-
const kept = [];
|
|
50
|
-
for (const part of parts) {
|
|
51
|
-
if (part === "" || part === ".")
|
|
52
|
-
continue;
|
|
53
|
-
if (part === "..") {
|
|
54
|
-
if (kept.length > floor)
|
|
55
|
-
kept.pop();
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
kept.push(part);
|
|
59
|
-
}
|
|
60
|
-
return kept.length === 0 ? "" : lead + kept.join(sep);
|
|
61
|
-
}
|
|
62
43
|
const NO_MATCHES = "No matches.";
|
|
63
44
|
const GREP_LINE_CLIP = 500;
|
|
64
45
|
function clipLine(line) {
|
|
@@ -813,18 +794,19 @@ export async function jsGrepDetailed(env, root, p, signal, guards, deny, denyOut
|
|
|
813
794
|
const mode = p.output_mode ?? "files_with_matches";
|
|
814
795
|
const rel = (abs) => (abs.startsWith(rootPrefix) ? abs.slice(rootPrefix.length) : abs);
|
|
815
796
|
const startWin = isWinFormPath(start);
|
|
816
|
-
const
|
|
817
|
-
const
|
|
797
|
+
const trailingSeparators = startWin ? /[\\/]+$/ : /\/+$/;
|
|
798
|
+
const anchor = start.replace(trailingSeparators, "");
|
|
799
|
+
const targetSpell = p.path ? p.path.replace(trailingSeparators, "") : "";
|
|
818
800
|
const isBoundary = (c) => c === "/" || (startWin && c === "\\");
|
|
819
801
|
const relOut = (abs) => {
|
|
820
802
|
if (!p.path) {
|
|
821
803
|
const r = rel(abs);
|
|
822
804
|
return r === abs ? r : `./${r}`;
|
|
823
805
|
}
|
|
824
|
-
if (abs ===
|
|
806
|
+
if (abs === start || abs === anchor)
|
|
825
807
|
return targetSpell;
|
|
826
|
-
if (abs.startsWith(
|
|
827
|
-
return targetSpell + abs.slice(
|
|
808
|
+
if (abs.startsWith(anchor) && isBoundary(abs[anchor.length]))
|
|
809
|
+
return targetSpell + abs.slice(anchor.length);
|
|
828
810
|
return rel(abs);
|
|
829
811
|
};
|
|
830
812
|
if (p.glob) {
|
|
@@ -105,8 +105,15 @@ export interface ShellReadVerdictFacts {
|
|
|
105
105
|
readonly writesPlaced?: true;
|
|
106
106
|
/** A FACT beside the disposition: a write target this command names lands on the write-protection table — judged by
|
|
107
107
|
* the table's own judge, as a write tool's target is — so the command's ask carries that table's class, whichever
|
|
108
|
-
* mode reads it. Absent ⇒ no target the station established is covered (or no judge is mounted).
|
|
108
|
+
* mode reads it. Absent ⇒ no target the station established is covered (or no judge is mounted). Said of a target whose
|
|
109
|
+
* TEXT names the row (the table's spelling view of one of its spellings); a covered target whose text names none is the
|
|
110
|
+
* member below — one target, one of the two. */
|
|
109
111
|
readonly writeProtected?: true;
|
|
112
|
+
/** A FACT beside the disposition: a write target this command names meets the write-protection table only where it resolves
|
|
113
|
+
* on disk (its real target, a link on the way) — none of the target's spellings names a row — so the command's ask carries
|
|
114
|
+
* that reading's class, which the auto-mode classifier does not answer. Beside `writeProtected` when another target's text
|
|
115
|
+
* names a row. Absent ⇒ no such target (or no judge is mounted). */
|
|
116
|
+
readonly writeProtectedOnDisk?: true;
|
|
110
117
|
/** A FACT beside the disposition: a target this command's program WRITES was placed and the environment could not say
|
|
111
118
|
* where it leads ({@link EstablishedRead.unresolved}) — the reading's `target_unresolved` fact, the same one a write
|
|
112
119
|
* tool's unresolved target states, so the command's ask carries that class (no automatic lane answers it; the shell face
|
|
@@ -104,12 +104,13 @@ function unplacedOptionsOf(judged) {
|
|
|
104
104
|
async function writeGuardsOf(judged, boundary, env, signal) {
|
|
105
105
|
const judge = boundary.writeTargetJudge;
|
|
106
106
|
if (judge === undefined)
|
|
107
|
-
return { unplaced: false, writeProtected: false };
|
|
107
|
+
return { unplaced: false, writeProtected: false, writeProtectedOnDisk: false };
|
|
108
108
|
const { runs, concurrent } = runOrderOf(judged);
|
|
109
109
|
const asKey = new Map();
|
|
110
110
|
const asSpelling = new Map();
|
|
111
111
|
const landingKeys = new Set();
|
|
112
112
|
const writtenBy = runs.map(() => []);
|
|
113
|
+
const targets = [];
|
|
113
114
|
const add = (into, view, child, at) => {
|
|
114
115
|
if (!isAbsoluteForFamily(pathFamilyOf({ root: view }), view))
|
|
115
116
|
return;
|
|
@@ -126,10 +127,16 @@ async function writeGuardsOf(judged, boundary, env, signal) {
|
|
|
126
127
|
add(key ? asKey : asSpelling, f.read.target, child, at);
|
|
127
128
|
if (key && written.seat === "landing")
|
|
128
129
|
landingKeys.add(f.read.target);
|
|
129
|
-
|
|
130
|
-
|
|
130
|
+
const views = [[f.read.target, key]];
|
|
131
|
+
if (written.seat === "landing") {
|
|
132
|
+
for (const spelling of f.read.spellings) {
|
|
131
133
|
add(asSpelling, spelling, child, at);
|
|
134
|
+
views.push([spelling, false]);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
132
137
|
writtenBy[at].push(f.read.target, ...f.read.spellings);
|
|
138
|
+
const derived = f.read.derivedSpellings ?? [];
|
|
139
|
+
targets.push({ views, text: f.read.established === "expansion" ? (f.read.origin !== undefined ? [f.read.origin] : []) : f.read.spellings.filter((s) => !derived.includes(s)) });
|
|
133
140
|
}
|
|
134
141
|
});
|
|
135
142
|
const probes = new Map();
|
|
@@ -160,20 +167,52 @@ async function writeGuardsOf(judged, boundary, env, signal) {
|
|
|
160
167
|
};
|
|
161
168
|
const answer = async (view, key) => (await judge(view, { fs: env, ...(signal !== undefined ? { signal } : {}), ...(key ? { canonical: true } : {}) })) ?? "clear";
|
|
162
169
|
const asked = [...[...asKey].map(([view, v]) => [view, v, true]), ...[...asSpelling].filter(([view]) => !landingKeys.has(view)).map(([view, v]) => [view, v, false])];
|
|
170
|
+
const slotOf = (view, key) => `${key || landingKeys.has(view) ? "key" : "spelling"}\u0000${view}`;
|
|
171
|
+
const askable = new Map(asked.map(([view, v, key]) => [slotOf(view, key), { view, v, key }]));
|
|
172
|
+
const answers = new Map();
|
|
173
|
+
const answerAt = async (view, key) => {
|
|
174
|
+
const slot = slotOf(view, key);
|
|
175
|
+
const known = answers.get(slot);
|
|
176
|
+
if (known !== undefined)
|
|
177
|
+
return known;
|
|
178
|
+
const a = askable.get(slot);
|
|
179
|
+
const found = a === undefined || (!(await writable(a.view, a.v)) && !changedBefore(a.view, a.v.at)) ? "clear" : await answer(a.view, a.key);
|
|
180
|
+
answers.set(slot, found);
|
|
181
|
+
return found;
|
|
182
|
+
};
|
|
183
|
+
const textNamesRow = async (text) => {
|
|
184
|
+
for (const spelling of text) {
|
|
185
|
+
if (!isAbsoluteForFamily(pathFamilyOf({ root: spelling }), spelling))
|
|
186
|
+
continue;
|
|
187
|
+
if ((await judge(spelling, { fs: env, spellingOnly: true })) === "protected")
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
191
|
+
};
|
|
163
192
|
let unplaced = false;
|
|
164
193
|
let writeProtected = false;
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
194
|
+
let writeProtectedOnDisk = false;
|
|
195
|
+
for (const target of targets) {
|
|
196
|
+
let covered = false;
|
|
197
|
+
for (const [view, key] of target.views) {
|
|
198
|
+
const found = await answerAt(view, key);
|
|
199
|
+
if (found !== "clear")
|
|
200
|
+
unplaced = true;
|
|
201
|
+
if (found === "protected") {
|
|
202
|
+
covered = true;
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (covered) {
|
|
207
|
+
if (await textNamesRow(target.text))
|
|
208
|
+
writeProtected = true;
|
|
209
|
+
else
|
|
210
|
+
writeProtectedOnDisk = true;
|
|
211
|
+
}
|
|
212
|
+
if (writeProtected && writeProtectedOnDisk)
|
|
174
213
|
break;
|
|
175
214
|
}
|
|
176
|
-
return { unplaced, writeProtected };
|
|
215
|
+
return { unplaced, writeProtected, writeProtectedOnDisk };
|
|
177
216
|
}
|
|
178
217
|
export function readStationMemberOf(call, members) {
|
|
179
218
|
return seatOf("fold.readStation", members, call);
|
|
@@ -352,13 +391,18 @@ async function runShellReadStation(tool, command, declared, seat, readers, estab
|
|
|
352
391
|
};
|
|
353
392
|
let judged = judgedNow();
|
|
354
393
|
let judgedVerdict = verdictOf(tool, seat, foldShellReadFindings(judged), judged, boundary);
|
|
355
|
-
const guarded = judgedVerdict.disposition === "refuse" ? { unplaced: false, writeProtected: false } : await writeGuardsOf(judged, boundary, door.fs, signal);
|
|
394
|
+
const guarded = judgedVerdict.disposition === "refuse" ? { unplaced: false, writeProtected: false, writeProtectedOnDisk: false } : await writeGuardsOf(judged, boundary, door.fs, signal);
|
|
356
395
|
judged = judgedNow();
|
|
357
396
|
judgedVerdict = verdictOf(tool, seat, foldShellReadFindings(judged), judged, boundary);
|
|
358
397
|
const unplaced = unplacedOptionsOf(judged);
|
|
359
398
|
const placed = judgedVerdict.finding !== "unanswered" && writesPlacedOf(judged, boundary);
|
|
360
399
|
const unresolved = judgedVerdict.disposition !== "refuse" && runOrderOf(judged).runs.some((s) => s.findings.some((f) => f.read.written !== undefined && f.read.unresolved === true));
|
|
361
|
-
const facts = {
|
|
400
|
+
const facts = {
|
|
401
|
+
...judgedVerdict,
|
|
402
|
+
...(guarded.writeProtected ? { writeProtected: true } : {}),
|
|
403
|
+
...(guarded.writeProtectedOnDisk ? { writeProtectedOnDisk: true } : {}),
|
|
404
|
+
...(unresolved ? { targetUnresolved: true } : {}),
|
|
405
|
+
};
|
|
362
406
|
const verdict = placed && !guarded.unplaced ? { ...facts, writesPlaced: true } : unplaced !== undefined ? { ...facts, unplacedOptions: unplaced } : facts;
|
|
363
407
|
return { plan, established, judged, boundary, verdict };
|
|
364
408
|
}
|
|
@@ -444,8 +444,9 @@ function establishLegOver(seen, readRoots) {
|
|
|
444
444
|
continue;
|
|
445
445
|
}
|
|
446
446
|
const spellings = at.spelled !== undefined ? [at.folded, at.spelled] : [at.folded];
|
|
447
|
+
const derived = name !== operand.spelled ? { derivedSpellings: spellings } : {};
|
|
447
448
|
for (const seat of j.seats ?? ["landing"])
|
|
448
|
-
out.push(writtenAt(await canonicalReadOf(j.candidate, at.spelled ?? at.folded, spellings, "canonical", undefined, undefined, signal, seat), j, seat));
|
|
449
|
+
out.push(writtenAt({ ...(await canonicalReadOf(j.candidate, at.spelled ?? at.folded, spellings, "canonical", undefined, undefined, signal, seat)), ...derived }, j, seat));
|
|
449
450
|
}
|
|
450
451
|
}
|
|
451
452
|
return out;
|
|
@@ -55,7 +55,7 @@ export async function withHomeViews(door, placed, established, signal) {
|
|
|
55
55
|
const home = landed ? await views.of(r.target, r.node === "file" ? { leaf: "file" } : undefined) : {};
|
|
56
56
|
if (home.unread !== undefined && !unread.includes(home.unread))
|
|
57
57
|
unread.push(home.unread);
|
|
58
|
-
out.push(home.view === undefined || r.spellings.includes(home.view) ? r : { ...r, spellings: [...r.spellings, home.view] });
|
|
58
|
+
out.push(home.view === undefined || r.spellings.includes(home.view) ? r : { ...r, spellings: [...r.spellings, home.view], derivedSpellings: [...(r.derivedSpellings ?? []), home.view] });
|
|
59
59
|
}
|
|
60
60
|
reads.set(segment, out);
|
|
61
61
|
}
|
|
@@ -218,11 +218,15 @@ export interface ShellReadBoundary extends BashReadonlyRootBoundary {
|
|
|
218
218
|
* `"guarded"`: a deployment row covers it — the target is not placed; `undefined`: nothing covers it. Read by the
|
|
219
219
|
* station's write facts only. A judgment that throws fails the station's answer (the caller's fail-closed arm). Every lookup
|
|
220
220
|
* it makes goes through `fs` — the command's door — and through no environment of its own: the station's one decision about
|
|
221
|
-
* what a silence means reads the answers the judgment got as well as the ones it did not.
|
|
221
|
+
* what a silence means reads the answers the judgment got as well as the ones it did not. `spellingOnly` ⇔ judge the path as
|
|
222
|
+
* written and nothing else — the table's spelling view, no lookup, no deployment row: `"protected"` when the text itself names
|
|
223
|
+
* a row of the table (what the station tells a written target's two readings apart by,
|
|
224
|
+
* {@link import("./shell-read-check.js").ShellReadVerdict.writeProtectedOnDisk}). */
|
|
222
225
|
readonly writeTargetJudge?: (target: string, opts: {
|
|
223
226
|
readonly fs: ObservedFilesystem;
|
|
224
227
|
readonly signal?: AbortSignal;
|
|
225
228
|
readonly canonical?: true;
|
|
229
|
+
readonly spellingOnly?: true;
|
|
226
230
|
}) => Promise<"protected" | "guarded" | undefined>;
|
|
227
231
|
}
|
|
228
232
|
/** How far one candidate got before it was judged. `lexical` = the folded spelling is the judged target
|
|
@@ -239,6 +243,11 @@ export interface EstablishedRead {
|
|
|
239
243
|
/** Every spelling the deny judge sees BESIDE the target: the folded spelling, the kernel spelling of a
|
|
240
244
|
* `..` operand, the pattern an expansion came from, the placeholder-carrying fold of a substitution. */
|
|
241
245
|
readonly spellings: readonly string[];
|
|
246
|
+
/** The members of {@link spellings} a reading of the FILESYSTEM produced rather than the command's text — the home's view of
|
|
247
|
+
* a landed target (read-deny-home.ts), added so the deny judge places a home-anchored row wherever the target really is; the
|
|
248
|
+
* name of a GNU sed `--follow-symlinks` backup when the operand's links supplied it. Every other spelling is the command's
|
|
249
|
+
* own text (folded, or as the kernel walks it). Absent ⇒ none. */
|
|
250
|
+
readonly derivedSpellings?: readonly string[];
|
|
242
251
|
/** The pattern or traversal root an `expansion` came from, as folded. */
|
|
243
252
|
readonly origin?: string;
|
|
244
253
|
/** What the environment said the target IS, where a read asked — only a traversal root asks (it lists the root
|
package/dist/tools/worktree.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 审计深挖 G4 — the `EnterWorktree` / `ExitWorktree` tool pair: SESSION-level git-worktree
|
|
3
|
-
* isolation. EnterWorktree creates a managed worktree under `.sema
|
|
4
|
-
* (the same {@link WORKTREE_PARENT} the subagent `isolation:"worktree"` lane uses) and
|
|
5
|
-
* the task's working directory into it; ExitWorktree returns to the original directory and
|
|
3
|
+
* isolation. EnterWorktree creates a managed worktree under `.sema/worktrees/`
|
|
4
|
+
* (the same {@link WORKTREE_PARENT} the subagent `isolation:"worktree"` lane uses, through the one mint `addWorktree`) and
|
|
5
|
+
* REALLY switches the task's working directory and write access into it; ExitWorktree returns to the original directory and
|
|
6
|
+
* cleans up.
|
|
6
7
|
*
|
|
7
8
|
* Semantics:
|
|
8
9
|
* ① worktrees live in a managed parent dir inside the repo (CC: `.claude/worktrees/`; sema:
|
|
9
|
-
* `.sema
|
|
10
|
+
* `.sema/worktrees/<name>`, on the new branch `sema/<name>`) — never scattered;
|
|
10
11
|
* ② baseRef is two-state: `"head"` = the current local HEAD (unpushed commits present), `"fresh"` =
|
|
11
12
|
* the default branch tip (CC: `origin/<default-branch>` for a clean tree);
|
|
12
13
|
* ③ a second CREATING EnterWorktree (`name`) while one is active is REFUSED ("Already in a worktree
|
|
@@ -23,18 +24,16 @@
|
|
|
23
24
|
* hands band shares one {@link CwdRef} (`handsCwdRef` in prepare-task): Bash runs every command in
|
|
24
25
|
* `cwdRef.current` (and `cd` moves it), Read/Edit/Write resolve relative paths against it, Monitor
|
|
25
26
|
* spawns there. EnterWorktree therefore performs a REAL switch by assigning `cwdRef.current`; the
|
|
26
|
-
* Runner's per-tool cwd read reports it as `workspace_changed`, same as an observed `cd`.
|
|
27
|
-
* containment is untouched: the worktree lives UNDER the task root, so resolveKey's canonical-within
|
|
28
|
-
* check still holds for every subsequent fs op.
|
|
27
|
+
* Runner's per-tool cwd read reports it as `workspace_changed`, same as an observed `cd`.
|
|
29
28
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
29
|
+
* WRITE ROOT = WRITE LOCATION (the reference implementation's permission-root relocation: entering a worktree "moves the
|
|
30
|
+
* session's working directory and write access there", and after a further switch the previously visited tree is no longer
|
|
31
|
+
* writable). The leg's write root is read live through {@link currentCheckoutOf} — the active worktree while one is tracked,
|
|
32
|
+
* the task root otherwise — by every write-root reader (the structured write tools, the shell's write targets, the
|
|
33
|
+
* accept-edits mode gate), so the base checkout and every other managed worktree are outside the write roots while a tree is
|
|
34
|
+
* active and judged by the existing out-of-root semantics. The READ roots do not move (the worktree lives under the task
|
|
35
|
+
* root). It is still not a sandbox: an arbitrary program run in the shell writes wherever the process can; the tool
|
|
36
|
+
* description and the replies say both halves.
|
|
38
37
|
*
|
|
39
38
|
* Security posture: both tools only ever run `git` against the task root / managed worktree (no
|
|
40
39
|
* arbitrary command surface), but they create/delete on-disk state ⇒ effect:"write" (plan mode gates
|
|
@@ -47,6 +46,7 @@
|
|
|
47
46
|
* Enter→suspend→resume→Exit behaves exactly like an unsuspended session.
|
|
48
47
|
*/
|
|
49
48
|
import type { ActiveWorktreeSession, AgentTool, ExecutionEnv } from "../internal/harness-types.js";
|
|
49
|
+
import type { ManagedCheckoutView } from "../core/write-protect.js";
|
|
50
50
|
import type { CwdRef } from "./fs/index.js";
|
|
51
51
|
/** the ACTIVE worktree session, ALL-SERIALIZABLE (plain strings, no closures):
|
|
52
52
|
* prepare-task owns the ref, stamps `current` into `CheckpointState.activeWorktree` at a durable
|
|
@@ -73,6 +73,33 @@ export interface WorktreeSessionRef {
|
|
|
73
73
|
* for the CAS-reject-vs-serialize trade-off). */
|
|
74
74
|
entering?: boolean;
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* THE write location of a leg — its one reader: the active worktree while one is tracked, the task root otherwise. Every
|
|
78
|
+
* write-root reader reads this (the structured write tools, the shell's write targets, the accept-edits mode gate), so
|
|
79
|
+
* "where may this leg write" has one answer that moves with EnterWorktree / ExitWorktree.
|
|
80
|
+
*
|
|
81
|
+
* The answer is a CANONICAL directory (the write roots compare canonical keys). A tree this engine minted is spelled under
|
|
82
|
+
* the task root's own spelling (`<root>/.sema/worktrees/<slug>`), and its three managed levels are refused at mint when any
|
|
83
|
+
* is a symlink — so its canonical form IS the task root's canonical form plus the same tail; a tree entered by `path` is
|
|
84
|
+
* already spelled as git reports it (the physical path). A recorded spelling under neither stands as recorded: a write root
|
|
85
|
+
* that matches no key refuses, never admits.
|
|
86
|
+
*/
|
|
87
|
+
export declare function currentCheckoutOf(session: WorktreeSessionRef | undefined, taskRoot: {
|
|
88
|
+
readonly spelled: string;
|
|
89
|
+
readonly canonical: string;
|
|
90
|
+
}): string;
|
|
91
|
+
/** A leg's write-location seat (the EnterWorktree session; empty until the worktree mount seeds it) and its readers, minted
|
|
92
|
+
* before any write-root reader: `writeLocation` ({@link currentCheckoutOf} over the seat) and `checkout` — the write location
|
|
93
|
+
* when it is a managed tree (a switch, or a task root that IS one): its canonical identity and the spelling the leg's paths
|
|
94
|
+
* carry it under, for the write-protection judge's current-tree reading (`WriteProtectionCompileOptions.checkoutOf`). */
|
|
95
|
+
export declare function writeLocationOf(taskRoot: {
|
|
96
|
+
readonly spelled: string;
|
|
97
|
+
readonly canonical: string;
|
|
98
|
+
}): {
|
|
99
|
+
readonly seat: WorktreeSessionRef;
|
|
100
|
+
readonly writeLocation: () => string;
|
|
101
|
+
readonly checkout: () => ReadonlyArray<ManagedCheckoutView> | undefined;
|
|
102
|
+
};
|
|
76
103
|
export interface WorktreeToolsOptions {
|
|
77
104
|
/** The task root (the repo root the managed worktrees nest under; `git` runs `-C` here). */
|
|
78
105
|
repoRoot: string;
|
package/dist/tools/worktree.js
CHANGED
|
@@ -1,9 +1,32 @@
|
|
|
1
1
|
import { resolve } from "node:path";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { defineTool, errorResult } from "../core/tools.js";
|
|
4
|
-
import { addWorktree, pruneWorktrees, WORKTREE_PARENT } from "../core/git-worktree-env.js";
|
|
4
|
+
import { addWorktree, managedWorktreeBaseOf, pruneWorktrees, removeManagedWorktree, worktreeNameProblem, WORKTREE_PARENT } from "../core/git-worktree-env.js";
|
|
5
5
|
import { mountRuleFace, toolFace } from "../core/tool-catalog-entries.js";
|
|
6
6
|
import { thrownText } from "../core/thrown-value.js";
|
|
7
|
+
export function currentCheckoutOf(session, taskRoot) {
|
|
8
|
+
const dir = session?.current?.worktreeDir;
|
|
9
|
+
if (dir === undefined)
|
|
10
|
+
return taskRoot.canonical;
|
|
11
|
+
const spelled = taskRoot.spelled.endsWith("/") ? taskRoot.spelled.slice(0, -1) : taskRoot.spelled;
|
|
12
|
+
if (spelled !== taskRoot.canonical && (dir === spelled || dir.startsWith(`${spelled}/`)))
|
|
13
|
+
return taskRoot.canonical + dir.slice(spelled.length);
|
|
14
|
+
return dir;
|
|
15
|
+
}
|
|
16
|
+
export function writeLocationOf(taskRoot) {
|
|
17
|
+
const seat = {};
|
|
18
|
+
const writeLocation = () => currentCheckoutOf(seat, taskRoot);
|
|
19
|
+
const checkout = () => {
|
|
20
|
+
const views = [];
|
|
21
|
+
for (const [root, kind] of [[writeLocation(), "canonical"], [seat.current?.worktreeDir ?? taskRoot.spelled, "spelled"]]) {
|
|
22
|
+
const base = managedWorktreeBaseOf(root);
|
|
23
|
+
if (base !== undefined)
|
|
24
|
+
views.push({ root, base, kind });
|
|
25
|
+
}
|
|
26
|
+
return views.length > 0 ? views : undefined;
|
|
27
|
+
};
|
|
28
|
+
return { seat, writeLocation, checkout };
|
|
29
|
+
}
|
|
7
30
|
const ENTER_DESCRIPTION = "Use this tool ONLY when explicitly instructed to work in a worktree — either by the user directly, or by " +
|
|
8
31
|
"project instructions. This tool creates an isolated git worktree and switches the current session into it.\n" +
|
|
9
32
|
"\n" +
|
|
@@ -21,9 +44,9 @@ const ENTER_DESCRIPTION = "Use this tool ONLY when explicitly instructed to work
|
|
|
21
44
|
"\n" +
|
|
22
45
|
"## Behavior\n" +
|
|
23
46
|
"\n" +
|
|
24
|
-
`- Creates a
|
|
25
|
-
"session's working directory to it: subsequent Bash commands run there,
|
|
26
|
-
"Read/Edit/Write resolve against it.\n" +
|
|
47
|
+
`- Creates a new worktree under \`${WORKTREE_PARENT}/<name>/\` in the repository root on a new branch \`sema/<name>\` and ` +
|
|
48
|
+
"switches the session's working directory and write access to it: subsequent Bash commands run there, relative paths in " +
|
|
49
|
+
"Read/Edit/Write resolve against it, and file writes must land inside it (or in an additional working directory).\n" +
|
|
27
50
|
'- `baseRef` picks the starting point: `"fresh"` (default) starts from the default branch tip ' +
|
|
28
51
|
"(origin's default branch when a remote exists, else local main/master, else the current HEAD with " +
|
|
29
52
|
'an honest note); `"head"` starts from the current local HEAD (unpushed commits and current branch ' +
|
|
@@ -34,10 +57,13 @@ const ENTER_DESCRIPTION = "Use this tool ONLY when explicitly instructed to work
|
|
|
34
57
|
"- Pass `path` instead of `name` to switch the session into a worktree of this repository that already " +
|
|
35
58
|
"exists (it must appear in `git worktree list` and live under the task root). Switching with `path` also " +
|
|
36
59
|
"works while already in a worktree session — the previous worktree is left on disk, untouched, and only " +
|
|
37
|
-
"the new one is tracked for exit-time cleanup. ExitWorktree will not remove a worktree entered via `path
|
|
38
|
-
"-
|
|
39
|
-
"
|
|
40
|
-
"
|
|
60
|
+
"the new one is tracked for exit-time cleanup. ExitWorktree will not remove a worktree entered via `path`. After a further " +
|
|
61
|
+
"switch, previously-visited worktrees are no longer writable — re-issue EnterWorktree with `path` to return to one.\n" +
|
|
62
|
+
"- While a worktree is active, the base checkout and every other worktree are outside the write roots: where writes are " +
|
|
63
|
+
"confined to the write roots, Edit/Write refuse them and a shell command writing there asks first. Reads still reach the " +
|
|
64
|
+
"whole task root. Use ExitWorktree to " +
|
|
65
|
+
"write the base checkout again. This is not a sandbox: a program run in the shell can still write anywhere the process " +
|
|
66
|
+
"can — do not rely on the worktree as an isolation boundary.\n" +
|
|
41
67
|
"- Requires a git repository — there is no VCS-agnostic fallback in this deployment.";
|
|
42
68
|
const EXIT_DESCRIPTION = "Exit a worktree session created by EnterWorktree and return the session to the original working directory.\n" +
|
|
43
69
|
"\n" +
|
|
@@ -117,7 +143,7 @@ export function createWorktreeTools(env, opts) {
|
|
|
117
143
|
description: ENTER_DESCRIPTION,
|
|
118
144
|
parameters: Type.Object({
|
|
119
145
|
name: Type.Optional(Type.String({
|
|
120
|
-
description:
|
|
146
|
+
description: 'Optional name for a new worktree. Each "/"-separated segment may contain only letters, digits, dots, underscores, and dashes; max 64 chars total. A random name is generated if not provided. Mutually exclusive with `path`.',
|
|
121
147
|
})),
|
|
122
148
|
path: Type.Optional(Type.String({
|
|
123
149
|
description: "Path to an existing worktree of the current repository to switch into instead of creating a new one. Must appear in `git worktree list` for the current repo (and live under the task root). Mutually exclusive with `name`.",
|
|
@@ -182,7 +208,7 @@ export function createWorktreeTools(env, opts) {
|
|
|
182
208
|
const fence = rootCanon.ok ? rootCanon.value : repoRoot;
|
|
183
209
|
if (target !== fence && !target.startsWith(fence.endsWith("/") ? fence : `${fence}/`)) {
|
|
184
210
|
return errorResult(`Error (EnterWorktree): the worktree ${target} lives outside the task root ${repoRoot}; ` +
|
|
185
|
-
"
|
|
211
|
+
"read containment stays anchored at the task root, so it cannot be entered from this session.");
|
|
186
212
|
}
|
|
187
213
|
const head = await env.exec("git rev-parse HEAD", { cwd: target });
|
|
188
214
|
if (!head.ok || head.value.exitCode !== 0) {
|
|
@@ -193,44 +219,50 @@ export function createWorktreeTools(env, opts) {
|
|
|
193
219
|
session.current = { worktreeDir: target, originalCwd, baseSha: head.value.stdout.trim(), entered: true };
|
|
194
220
|
cwdRef.current = target;
|
|
195
221
|
return {
|
|
196
|
-
content: `Switched into the existing worktree at ${target}${previous ? ` (the previous worktree at ${previous.worktreeDir} was left on disk, untouched)` : ""}. ` +
|
|
197
|
-
"The session's working directory
|
|
198
|
-
"operate there
|
|
199
|
-
"task root. ExitWorktree will restore the original directory but will NOT remove a
|
|
200
|
-
"entered via `path`.",
|
|
222
|
+
content: `Switched into the existing worktree at ${target}${previous ? ` (the previous worktree at ${previous.worktreeDir} was left on disk, untouched, and is no longer writable)` : ""}. ` +
|
|
223
|
+
"The session's working directory and write access are now this worktree — subsequent commands and relative paths " +
|
|
224
|
+
"operate there, and writes outside it (the base checkout included) are outside the write roots. Reads still reach " +
|
|
225
|
+
"the whole task root; this is not a sandbox. ExitWorktree will restore the original directory but will NOT remove a " +
|
|
226
|
+
"worktree entered via `path`.",
|
|
201
227
|
details: { type: "worktree", action: "enter", worktreeDir: target },
|
|
202
228
|
};
|
|
203
229
|
}
|
|
230
|
+
const nameProblem = name === undefined ? undefined : worktreeNameProblem(name);
|
|
231
|
+
if (nameProblem !== undefined)
|
|
232
|
+
return errorResult(`Error (EnterWorktree): ${nameProblem.slice(0, 300)}.`);
|
|
204
233
|
const base = await resolveBaseCommit(env, repoRoot, baseRef ?? "fresh");
|
|
205
234
|
if ("error" in base)
|
|
206
235
|
return errorResult(`Error (EnterWorktree): ${base.error}.`);
|
|
207
|
-
let
|
|
236
|
+
let created;
|
|
208
237
|
try {
|
|
209
|
-
|
|
238
|
+
created = await addWorktree(env, {
|
|
210
239
|
repoRoot,
|
|
211
|
-
sessionId:
|
|
240
|
+
sessionId: "worktree",
|
|
241
|
+
...(name !== undefined ? { name } : {}),
|
|
212
242
|
commit: base.sha,
|
|
213
243
|
rootEnvAt: (dir) => Object.create(env, {
|
|
214
244
|
cwd: { value: dir, configurable: true },
|
|
215
245
|
destroy: { value: undefined, writable: true, configurable: true },
|
|
216
246
|
}),
|
|
217
247
|
});
|
|
218
|
-
createdDir = worktreeDir;
|
|
219
248
|
}
|
|
220
249
|
catch (e) {
|
|
221
250
|
return errorResult(`Error (EnterWorktree): ${thrownText(e)}`);
|
|
222
251
|
}
|
|
252
|
+
const createdDir = created.worktreeDir;
|
|
223
253
|
session.current = {
|
|
224
254
|
worktreeDir: createdDir,
|
|
225
255
|
originalCwd: cwdRef.current,
|
|
226
256
|
baseSha: base.sha,
|
|
257
|
+
name: created.name,
|
|
258
|
+
branch: created.branch,
|
|
227
259
|
};
|
|
228
260
|
cwdRef.current = createdDir;
|
|
229
261
|
return {
|
|
230
|
-
content: `Created worktree at ${createdDir} (base: ${base.label}${base.note ?? ""}). ` +
|
|
231
|
-
"The session's working directory
|
|
232
|
-
"operate there
|
|
233
|
-
"
|
|
262
|
+
content: `Created worktree at ${createdDir} (base: ${base.label}${base.note ?? ""}) on branch ${created.branch}. ` +
|
|
263
|
+
"The session's working directory and write access are now the worktree — subsequent commands and relative paths " +
|
|
264
|
+
"operate there, and writes outside it (the base checkout included) are outside the write roots. Reads still reach " +
|
|
265
|
+
"the rest of the task root; this is not a sandbox. " +
|
|
234
266
|
"Use ExitWorktree to leave (an unchanged worktree is removed; a changed one is kept).",
|
|
235
267
|
details: { type: "worktree", action: "create", worktreeDir: createdDir, base: base.label },
|
|
236
268
|
};
|
|
@@ -253,7 +285,7 @@ export function createWorktreeTools(env, opts) {
|
|
|
253
285
|
description: "true = remove the worktree even when it has uncommitted files or new commits, permanently discarding them. Default false: a changed worktree is kept and its changes listed. Cannot be combined with `keep: true`.",
|
|
254
286
|
})),
|
|
255
287
|
action: Type.Optional(Type.Union([Type.Literal("keep"), Type.Literal("remove")], {
|
|
256
|
-
description: '"keep" leaves the worktree on disk. "remove" takes the default removal path: an unchanged worktree is removed, a changed one is still KEPT unless `discard_changes: true`.
|
|
288
|
+
description: '"keep" leaves the worktree and its branch on disk. "remove" takes the default removal path: an unchanged worktree is removed, a changed one is still KEPT unless `discard_changes: true`. A removed worktree\'s branch is deleted with it only when it carries no commits beyond the base; a branch with commits is kept and named in the reply.',
|
|
257
289
|
})),
|
|
258
290
|
discard_changes: Type.Optional(Type.Boolean({
|
|
259
291
|
description: 'Set true to remove the worktree even when it has uncommitted files or unmerged commits — they are permanently discarded. Without it a changed worktree is KEPT (the exit still completes and the reply lists the changes plus this escape), never refused.',
|
|
@@ -377,13 +409,9 @@ export function createWorktreeTools(env, opts) {
|
|
|
377
409
|
details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: true },
|
|
378
410
|
};
|
|
379
411
|
}
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
? undefined
|
|
384
|
-
: r.ok
|
|
385
|
-
? (r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}`).trim()
|
|
386
|
-
: reasonOf(r.error), (e) => reasonOf(e));
|
|
412
|
+
const removal = await removeManagedWorktree(env, repoRoot, active.worktreeDir, active.branch !== undefined ? { name: active.branch, baseSha: active.baseSha } : undefined);
|
|
413
|
+
const removeFailure = removal.ok ? undefined : removal.detail.trim();
|
|
414
|
+
const branchNote = !removal.ok ? "" : removal.branchKept !== undefined ? ` Its branch was kept: ${removal.branchKept}.` : removal.branchDeleted !== undefined ? ` Its branch ${removal.branchDeleted} was deleted.` : "";
|
|
387
415
|
const pruned = await pruneWorktrees(env, repoRoot);
|
|
388
416
|
const stillThere = await env.exists(active.worktreeDir);
|
|
389
417
|
const removalNote = removeFailure !== undefined ? ` (the removal command reported: ${removeFailure})` : "";
|
|
@@ -412,7 +440,7 @@ export function createWorktreeTools(env, opts) {
|
|
|
412
440
|
}
|
|
413
441
|
return {
|
|
414
442
|
content: `Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
|
|
415
|
-
`The worktree at ${active.worktreeDir} ${stateClause} and was removed.${removalNote}${pruneNote}`,
|
|
443
|
+
`The worktree at ${active.worktreeDir} ${stateClause} and was removed.${removalNote}${pruneNote}${branchNote}`,
|
|
416
444
|
details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: false, ...pruneDetail },
|
|
417
445
|
};
|
|
418
446
|
}
|