@sema-agent/core 7.61.0 → 7.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +840 -0
- package/dist/agents/cascade.d.ts +11 -3
- package/dist/agents/cascade.js +1 -1
- package/dist/agents/peer-held-queue.d.ts +27 -4
- package/dist/agents/peer-held-queue.js +81 -36
- package/dist/agents/peer-session-drain.js +13 -3
- package/dist/agents/subagent-transcript-placement.d.ts +23 -0
- package/dist/agents/subagent-transcript-placement.js +14 -0
- package/dist/agents/subagent.d.ts +6 -1
- package/dist/agents/subagent.js +143 -58
- package/dist/agents/suspend-guard.d.ts +38 -16
- package/dist/agents/suspend-guard.js +9 -4
- package/dist/agents/verify.js +4 -3
- package/dist/brain/route-adjudicator.js +9 -4
- package/dist/core/approval-object.js +1 -1
- package/dist/core/arg-summary.js +1 -1
- package/dist/core/ask-question.d.ts +2 -2
- package/dist/core/canonical-json.d.ts +23 -13
- package/dist/core/canonical-json.js +4 -4
- package/dist/core/checkpoint-features.d.ts +722 -0
- package/dist/core/checkpoint-features.js +98 -0
- package/dist/core/checkpoint-queries.d.ts +47 -4
- package/dist/core/checkpoint-queries.js +36 -16
- package/dist/core/checkpoint-requirements.d.ts +12 -5
- package/dist/core/checkpoint-requirements.js +11 -5
- package/dist/core/checkpoint-row-verdict.d.ts +110 -0
- package/dist/core/checkpoint-row-verdict.js +245 -0
- package/dist/core/checkpoint-store.d.ts +76 -753
- package/dist/core/checkpoint-store.js +83 -144
- package/dist/core/compliance.d.ts +6 -2
- package/dist/core/compliance.js +3 -3
- package/dist/core/engine-attestation.d.ts +1 -1
- package/dist/core/engine-notice.d.ts +38 -7
- package/dist/core/engine-notice.js +9 -2
- package/dist/core/gate-fold.js +2 -2
- package/dist/core/git-worktree-env.d.ts +62 -3
- package/dist/core/git-worktree-env.js +91 -30
- package/dist/core/governance-codes.d.ts +9 -3
- package/dist/core/governance-codes.js +16 -3
- package/dist/core/hooks.d.ts +13 -0
- package/dist/core/human-input-projection.d.ts +1 -0
- package/dist/core/human-input-projection.js +3 -0
- package/dist/core/image-admission.d.ts +1 -1
- package/dist/core/locked-config.d.ts +2 -2
- package/dist/core/mcp-host-seat.js +6 -1
- package/dist/core/memory-engine/consolidation-driver.d.ts +33 -18
- package/dist/core/memory-engine/consolidation-driver.js +99 -98
- package/dist/core/memory-engine/consolidation.d.ts +73 -10
- package/dist/core/memory-engine/consolidation.js +167 -11
- package/dist/core/memory-engine/data-plane.d.ts +8 -4
- package/dist/core/memory-engine/data-plane.js +11 -6
- package/dist/core/memory-engine/delegation-settlement.d.ts +37 -35
- package/dist/core/memory-engine/delegation-settlement.js +53 -59
- package/dist/core/memory-engine/dual-root.d.ts +12 -6
- package/dist/core/memory-engine/dual-root.js +9 -5
- package/dist/core/memory-engine/engine.d.ts +98 -35
- package/dist/core/memory-engine/engine.js +477 -380
- package/dist/core/memory-engine/entry-scan.d.ts +8 -0
- package/dist/core/memory-engine/entry-scan.js +3 -0
- package/dist/core/memory-engine/file-backend.d.ts +29 -3
- package/dist/core/memory-engine/file-backend.js +66 -35
- package/dist/core/memory-engine/index.d.ts +7 -7
- package/dist/core/memory-engine/index.js +6 -6
- package/dist/core/memory-engine/landing-admission.d.ts +5 -3
- package/dist/core/memory-engine/landing-admission.js +3 -3
- package/dist/core/memory-engine/layout.d.ts +121 -45
- package/dist/core/memory-engine/layout.js +252 -102
- package/dist/core/memory-engine/memory-backend-contract.d.ts +19 -1
- package/dist/core/memory-engine/memory-backend-contract.js +320 -0
- package/dist/core/memory-engine/memory-deployment.d.ts +31 -8
- package/dist/core/memory-engine/memory-deployment.js +26 -12
- package/dist/core/memory-engine/scope-contract.d.ts +52 -11
- package/dist/core/memory-engine/scope-contract.js +68 -19
- package/dist/core/memory-engine/session-write-home.d.ts +3 -1
- package/dist/core/memory-engine/session-write-home.js +1 -1
- package/dist/core/memory-engine/sync-client.d.ts +3 -1
- package/dist/core/memory-engine/sync-client.js +7 -0
- package/dist/core/memory-engine/sync-report.d.ts +3 -2
- package/dist/core/memory-engine/sync-report.js +6 -2
- package/dist/core/memory-engine/tools.d.ts +2 -2
- package/dist/core/memory-engine/tools.js +10 -10
- package/dist/core/memory-engine/types.d.ts +118 -19
- package/dist/core/memory-engine/types.js +1 -0
- package/dist/core/memory-vector.d.ts +1 -1
- package/dist/core/memory.d.ts +10 -10
- package/dist/core/memory.js +15 -6
- package/dist/core/mode-policy.js +1 -1
- package/dist/core/mods/classic-events.d.ts +9 -1
- package/dist/core/mods/dollar.d.ts +32 -1
- package/dist/core/mods/dollar.js +13 -1
- package/dist/core/mods/kernel/events.d.ts +11 -3
- package/dist/core/mods/kernel/events.js +13 -10
- package/dist/core/mods/lifecycle-stations.d.ts +36 -4
- package/dist/core/mods/lifecycle-stations.js +44 -9
- package/dist/core/mods/session-append.d.ts +4 -1
- package/dist/core/mods/session-append.js +7 -0
- package/dist/core/mods/session-receive.js +12 -15
- package/dist/core/mods/stations.d.ts +70 -6
- package/dist/core/mods/stations.js +144 -1
- package/dist/core/own-property-receipt.d.ts +7 -0
- package/dist/core/own-property-receipt.js +3 -0
- package/dist/core/park-selfcheck.js +2 -2
- package/dist/core/pause-registry.d.ts +2 -0
- package/dist/core/pause-registry.js +3 -0
- package/dist/core/permission-rule-consent.d.ts +10 -3
- package/dist/core/permission-rule-consent.js +37 -24
- package/dist/core/permission-rule-store.d.ts +35 -1
- package/dist/core/permission-rule-store.js +27 -8
- package/dist/core/read-only-shell.js +3 -2
- package/dist/core/read-root-candidate.js +1 -1
- package/dist/core/redaction-marks.d.ts +8 -0
- package/dist/core/redaction-marks.js +6 -0
- package/dist/core/remote-env.d.ts +12 -1
- package/dist/core/remote-env.js +3 -0
- package/dist/core/resume-startup-cause.d.ts +5 -4
- package/dist/core/runner/child-tree.d.ts +29 -3
- package/dist/core/runner/child-tree.js +39 -16
- package/dist/core/runner/compact-session.js +5 -2
- package/dist/core/runner/contracts.d.ts +36 -17
- package/dist/core/runner/delegation-owner.d.ts +43 -0
- package/dist/core/runner/delegation-owner.js +59 -0
- package/dist/core/runner/gate-exit.js +2 -2
- package/dist/core/runner/inherited-ask-grants.js +1 -1
- package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
- package/dist/core/runner/lineage-reroot-view.js +108 -0
- package/dist/core/runner/memory-consolidation-driver.d.ts +6 -3
- package/dist/core/runner/memory-consolidation-driver.js +4 -4
- package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
- package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
- package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
- package/dist/core/runner/permission-rule-lanes.js +2 -2
- package/dist/core/runner/person-path-rows.d.ts +23 -3
- package/dist/core/runner/person-path-rows.js +31 -4
- package/dist/core/runner/placement-fence.d.ts +12 -0
- package/dist/core/runner/placement-fence.js +20 -6
- package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
- package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
- package/dist/core/runner/prepare-ask-lane.js +2 -2
- package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -1
- package/dist/core/runner/prepare-caps-and-workflow.js +6 -3
- package/dist/core/runner/prepare-config-doors.d.ts +6 -6
- package/dist/core/runner/prepare-config-doors.js +3 -4
- package/dist/core/runner/prepare-execution-env.js +17 -6
- package/dist/core/runner/prepare-hands-readface.d.ts +3 -2
- package/dist/core/runner/prepare-hands-readface.js +32 -10
- package/dist/core/runner/prepare-inherited-gate.d.ts +12 -8
- package/dist/core/runner/prepare-inherited-gate.js +14 -6
- package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
- package/dist/core/runner/prepare-memory-engine-session.js +4 -4
- package/dist/core/runner/prepare-memory.d.ts +3 -2
- package/dist/core/runner/prepare-memory.js +28 -20
- package/dist/core/runner/prepare-park-ask.js +4 -3
- package/dist/core/runner/prepare-task.js +22 -16
- package/dist/core/runner/prepare-workspace-restore.js +3 -6
- package/dist/core/runner/resume-admission.d.ts +3 -3
- package/dist/core/runner/resume-admission.js +6 -3
- package/dist/core/runner/resume-apply.d.ts +4 -0
- package/dist/core/runner/resume-apply.js +11 -4
- package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
- package/dist/core/runner/resume-checkpoint-screen.js +4 -84
- package/dist/core/runner/run-git-lane.d.ts +2 -0
- package/dist/core/runner/run-git-lane.js +4 -1
- package/dist/core/runner/run-harness-handlers.d.ts +2 -0
- package/dist/core/runner/run-harness-handlers.js +3 -2
- package/dist/core/runner/run-leg.js +25 -8
- package/dist/core/runner/run-settle-and-teardown.js +6 -4
- package/dist/core/runner/run-stop-and-final-verify.js +2 -1
- package/dist/core/runner/run-turn-boundary.js +7 -4
- package/dist/core/runner/runtask.js +6 -6
- package/dist/core/runner/steering-preview.d.ts +9 -0
- package/dist/core/runner/steering-preview.js +5 -0
- package/dist/core/runner/stream-steer-verb.js +8 -0
- package/dist/core/runner/terminal-account.js +1 -1
- package/dist/core/runner/tool-face-overlay.js +2 -0
- package/dist/core/runner/turn-attachments.d.ts +5 -0
- package/dist/core/runner/turn-attachments.js +1 -1
- package/dist/core/runner-deps.d.ts +8 -4
- package/dist/core/secret-env.d.ts +9 -6
- package/dist/core/secret-env.js +41 -22
- package/dist/core/session-checkout.d.ts +108 -0
- package/dist/core/session-checkout.js +485 -0
- package/dist/core/session-store.d.ts +13 -5
- package/dist/core/session-store.js +28 -4
- package/dist/core/session.d.ts +29 -5
- package/dist/core/session.js +3 -0
- package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -12
- package/dist/core/store-contracts/checkpoint-store-contract.js +73 -6
- package/dist/core/store-contracts/session-store-contract.js +61 -8
- package/dist/core/task-event.d.ts +28 -1
- package/dist/core/task-notification.d.ts +9 -1
- package/dist/core/task-notification.js +8 -1
- package/dist/core/task-registry-agent.d.ts +40 -8
- package/dist/core/task-registry-agent.js +57 -24
- package/dist/core/task-registry-shared.d.ts +33 -11
- package/dist/core/task-registry-workflow.js +4 -3
- package/dist/core/task-registry.d.ts +27 -10
- package/dist/core/task-registry.js +19 -13
- package/dist/core/task-result.d.ts +5 -5
- package/dist/core/task-spec-members.js +1 -1
- package/dist/core/task-spec.d.ts +21 -1
- package/dist/core/terminal-cause.d.ts +6 -6
- package/dist/core/tool-face.d.ts +6 -2
- package/dist/core/tool-face.js +1 -1
- package/dist/core/tool-policy.d.ts +16 -13
- package/dist/core/tool-policy.js +11 -10
- package/dist/core/tool-roster.d.ts +4 -4
- package/dist/core/tool-spec.d.ts +42 -19
- package/dist/core/types.d.ts +2 -2
- package/dist/core/types.js +1 -1
- package/dist/core/untrusted-egress.d.ts +15 -4
- package/dist/core/untrusted-egress.js +23 -22
- package/dist/core/workspace-snapshot.d.ts +3 -1
- package/dist/core/workspace-snapshot.js +1 -0
- package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
- package/dist/engine/execution-env/node-execution-env.js +12 -5
- package/dist/engine/harness/types.d.ts +77 -1
- package/dist/engine/harness/types.js +108 -0
- package/dist/engine/session/import-validate.js +6 -1
- package/dist/engine/session/parent-chain-guard.d.ts +3 -3
- package/dist/engine/session/parent-chain-guard.js +1 -1
- package/dist/engine/session/path-to-root.d.ts +18 -3
- package/dist/engine/session/path-to-root.js +15 -1
- package/dist/engine/session/repo-utils.d.ts +12 -1
- package/dist/engine/session/repo-utils.js +41 -0
- package/dist/engine/session/session.d.ts +24 -1
- package/dist/engine/session/session.js +46 -2
- package/dist/engine/session/storage-base.d.ts +20 -0
- package/dist/engine/session/storage-base.js +28 -9
- package/dist/index.d.ts +16 -12
- package/dist/index.js +11 -8
- package/dist/internal/harness-types.d.ts +1 -1
- package/dist/internal/harness.d.ts +4 -3
- package/dist/internal/harness.js +3 -2
- package/dist/orchestration/run-workflow-tool.d.ts +7 -1
- package/dist/orchestration/run-workflow-tool.js +28 -11
- package/dist/orchestration/workflow-governance.d.ts +1 -1
- package/dist/orchestration/workflow.d.ts +6 -0
- package/dist/orchestration/workflow.js +5 -8
- package/dist/stores/file/checkpoint-store.d.ts +2 -0
- package/dist/stores/file/checkpoint-store.js +7 -6
- package/dist/stores/file/fs-atomic.d.ts +0 -22
- package/dist/stores/file/fs-atomic.js +0 -17
- package/dist/stores/file/index.d.ts +2 -9
- package/dist/stores/file/index.js +2 -4
- package/dist/stores/file/session-store.d.ts +13 -7
- package/dist/stores/file/session-store.js +42 -18
- package/dist/tools/fs/bash-program-position.d.ts +3 -2
- package/dist/tools/fs/bash-program-position.js +10 -10
- package/dist/tools/fs/program-read-model.d.ts +34 -10
- package/dist/tools/fs/program-read-model.js +37 -7
- package/dist/tools/fs/program-read-model.rows.js +13 -2
- package/dist/tools/fs/read-deny.d.ts +13 -1
- package/dist/tools/fs/read-deny.js +10 -2
- package/dist/tools/fs/removal-targets.js +5 -5
- package/dist/tools/fs/safety.d.ts +2 -0
- package/dist/tools/fs/safety.js +1 -1
- package/dist/tools/fs/shell-read-argv.d.ts +11 -2
- package/dist/tools/fs/shell-read-argv.js +45 -29
- package/dist/tools/fs/shell-read-bindings.d.ts +20 -2
- package/dist/tools/fs/shell-read-bindings.js +153 -69
- package/dist/tools/fs/shell-read-brace.d.ts +18 -0
- package/dist/tools/fs/shell-read-brace.js +79 -0
- package/dist/tools/fs/shell-read-check.js +29 -11
- package/dist/tools/fs/shell-read-establish.js +43 -22
- package/dist/tools/fs/shell-read-functions.js +2 -2
- package/dist/tools/fs/shell-read-judge.d.ts +11 -0
- package/dist/tools/fs/shell-read-judge.js +3 -3
- package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
- package/dist/tools/fs/shell-read-object-path.js +119 -0
- package/dist/tools/fs/shell-read-plan.d.ts +18 -0
- package/dist/tools/fs/shell-read-plan.js +217 -104
- package/dist/tools/fs/shell-read-start.d.ts +76 -13
- package/dist/tools/fs/shell-read-start.js +97 -17
- package/dist/tools/fs/shell-read-word.d.ts +10 -0
- package/dist/tools/fs/shell-read-word.js +9 -5
- package/dist/tools/fs/shell-read-workdir.d.ts +54 -14
- package/dist/tools/fs/shell-read-workdir.js +103 -19
- package/dist/tools/fs/shell-read-write-targets.js +13 -8
- package/dist/tools/worktree.d.ts +3 -2
- package/dist/tools/worktree.js +7 -35
- package/package.json +3 -2
- package/test/export-surface.snapshot.json +93 -43
- package/wire-changes/core-stores-sql@7.62.0.json +30 -0
- package/wire-changes/core-stores-sql@7.63.0.json +30 -0
- package/wire-changes/core@7.62.0.json +2181 -0
- package/wire-changes/core@7.63.0.json +3523 -0
- package/wire-changes/mods-kernel@7.62.0.json +42 -0
- package/wire-changes/mods-kernel@7.63.0.json +30 -0
- package/wire-changes/primitives@7.62.0.json +30 -0
- package/wire-changes/primitives@7.63.0.json +445 -0
- package/dist/core/consolidate-scope.d.ts +0 -93
- package/dist/core/consolidate-scope.js +0 -98
- package/dist/core/credential-vocabulary.d.ts +0 -176
- package/dist/core/credential-vocabulary.js +0 -190
- package/dist/core/redaction-passes.d.ts +0 -82
- package/dist/core/redaction-passes.js +0 -377
- package/dist/core/runner/memory-consolidation.d.ts +0 -109
- package/dist/core/runner/memory-consolidation.js +0 -251
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { appendSessionCheckout, readSessionCheckout } from "../engine/session/session.js";
|
|
3
|
+
import { isSensitiveRecordKey } from "@sema-agent/primitives";
|
|
4
|
+
import { managedAnchorOf, managedWorktreeBranchOf, managedWorktreeDir, mintManagedWorktree, removeManagedWorktree, repositoryRootOf, resolveBaseCommit, shq, symlinkedLevel, WORKTREE_PARENT, worktreeNameProblem, } from "./git-worktree-env.js";
|
|
5
|
+
import { strayMembersOf } from "./own-property-receipt.js";
|
|
6
|
+
import { thrownText } from "./thrown-value.js";
|
|
7
|
+
export const WORKTREE_INCAPABLE_REASONS = Object.freeze([
|
|
8
|
+
"git_unavailable",
|
|
9
|
+
"not_a_repository",
|
|
10
|
+
"bare_repository",
|
|
11
|
+
"no_commit",
|
|
12
|
+
"managed_parent_symlinked",
|
|
13
|
+
"parent_not_writable",
|
|
14
|
+
"name_in_use",
|
|
15
|
+
]);
|
|
16
|
+
const refusal = (code, message) => Object.assign(new Error(message), { code });
|
|
17
|
+
const invalid = (problem) => refusal("config.session_workspace_invalid", `TaskSpec.workspace ${problem}`);
|
|
18
|
+
const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
|
|
19
|
+
const SOURCE_MAX = 64;
|
|
20
|
+
const DECLARATION_MEMBERS = Object.freeze(["isolation", "baseRef", "name", "sources"]);
|
|
21
|
+
const SOURCE_MEMBERS = Object.freeze(["root", "remote", "sha", "ref"]);
|
|
22
|
+
function normalizeRemote(remote, at) {
|
|
23
|
+
if (typeof remote !== "string" || remote.length === 0 || remote.length > 2048)
|
|
24
|
+
throw invalid(`${at}.remote must be an https repository URL`);
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
url = new URL(remote);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw invalid(`${at}.remote is not a URL`);
|
|
31
|
+
}
|
|
32
|
+
if (url.protocol !== "https:")
|
|
33
|
+
throw invalid(`${at}.remote must be an https URL (got a ${url.protocol.replace(/:$/, "")} URL)`);
|
|
34
|
+
if (url.username !== "" || url.password !== "")
|
|
35
|
+
throw invalid(`${at}.remote carries a user name or password (${url.origin}); credentials never ride the declaration`);
|
|
36
|
+
const fragment = new URLSearchParams(url.hash.replace(/^#/, ""));
|
|
37
|
+
for (const params of [url.searchParams, fragment]) {
|
|
38
|
+
for (const name of params.keys()) {
|
|
39
|
+
if (isSensitiveRecordKey(name))
|
|
40
|
+
throw invalid(`${at}.remote carries a credential parameter (${url.origin}); credentials never ride the declaration`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const path = url.pathname.replace(/\/+$/, "").replace(/\.git$/, "");
|
|
44
|
+
if (path === "" || path === "/")
|
|
45
|
+
throw invalid(`${at}.remote names no repository (${url.origin})`);
|
|
46
|
+
return `https://${url.host.toLowerCase()}${path}`;
|
|
47
|
+
}
|
|
48
|
+
function screenRoot(root, at) {
|
|
49
|
+
if (root === "taskRoot")
|
|
50
|
+
return "taskRoot";
|
|
51
|
+
if (root !== null && typeof root === "object" && !Array.isArray(root)) {
|
|
52
|
+
const keys = Object.keys(root);
|
|
53
|
+
const directory = root.directory;
|
|
54
|
+
if (keys.length === 1 && keys[0] === "directory" && typeof directory === "string" && directory.startsWith("/"))
|
|
55
|
+
return { directory };
|
|
56
|
+
}
|
|
57
|
+
throw invalid(`${at}.root must be "taskRoot" or { directory } naming an absolute additionalDirectories entry`);
|
|
58
|
+
}
|
|
59
|
+
const rootKey = (root) => (root === "taskRoot" ? "taskRoot" : `dir:${root.directory}`);
|
|
60
|
+
export function screenWorkspaceDeclaration(value) {
|
|
61
|
+
if (value === undefined)
|
|
62
|
+
return undefined;
|
|
63
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
64
|
+
throw invalid("must be an object");
|
|
65
|
+
const v = value;
|
|
66
|
+
const stray = strayMembersOf(v, { subject: "TaskSpec.workspace", unit: "member", moment: "when the leg starts" }, DECLARATION_MEMBERS);
|
|
67
|
+
if (stray !== undefined)
|
|
68
|
+
throw refusal("config.session_workspace_invalid", stray.sentence);
|
|
69
|
+
if (v.isolation !== undefined && v.isolation !== "worktree")
|
|
70
|
+
throw invalid('.isolation must be "worktree"');
|
|
71
|
+
if (v.baseRef !== undefined && v.baseRef !== "fresh" && v.baseRef !== "head")
|
|
72
|
+
throw invalid('.baseRef must be "fresh" or "head"');
|
|
73
|
+
if ((v.baseRef !== undefined || v.name !== undefined) && v.isolation === undefined)
|
|
74
|
+
throw invalid('.baseRef and .name only apply with isolation: "worktree"');
|
|
75
|
+
if (v.name !== undefined) {
|
|
76
|
+
if (typeof v.name !== "string")
|
|
77
|
+
throw invalid(".name must be a string");
|
|
78
|
+
const problem = worktreeNameProblem(v.name);
|
|
79
|
+
if (problem !== undefined)
|
|
80
|
+
throw invalid(`.name: ${problem}`);
|
|
81
|
+
}
|
|
82
|
+
let sources;
|
|
83
|
+
if (v.sources !== undefined) {
|
|
84
|
+
if (!Array.isArray(v.sources) || v.sources.length === 0 || v.sources.length > SOURCE_MAX)
|
|
85
|
+
throw invalid(`.sources must be a non-empty list of at most ${SOURCE_MAX} entries`);
|
|
86
|
+
sources = [];
|
|
87
|
+
const seen = new Set();
|
|
88
|
+
v.sources.forEach((s, i) => {
|
|
89
|
+
const at = `.sources[${i}]`;
|
|
90
|
+
if (s === null || typeof s !== "object" || Array.isArray(s))
|
|
91
|
+
throw invalid(`${at} must be an object`);
|
|
92
|
+
const entry = s;
|
|
93
|
+
const straySource = strayMembersOf(entry, { subject: `TaskSpec.workspace${at}`, unit: "member", moment: "when the leg starts" }, SOURCE_MEMBERS);
|
|
94
|
+
if (straySource !== undefined)
|
|
95
|
+
throw refusal("config.session_workspace_invalid", straySource.sentence);
|
|
96
|
+
const root = screenRoot(entry.root, at);
|
|
97
|
+
if (seen.has(rootKey(root)))
|
|
98
|
+
throw invalid(`${at}.root names a root another source already names`);
|
|
99
|
+
seen.add(rootKey(root));
|
|
100
|
+
const remote = normalizeRemote(entry.remote, at);
|
|
101
|
+
if (typeof entry.sha !== "string" || !FULL_SHA.test(entry.sha))
|
|
102
|
+
throw invalid(`${at}.sha must be a full commit id (40 or 64 lowercase hex characters)`);
|
|
103
|
+
if (entry.ref !== undefined && (typeof entry.ref !== "string" || entry.ref.length === 0 || entry.ref.length > 256))
|
|
104
|
+
throw invalid(`${at}.ref must be a non-empty label of at most 256 characters`);
|
|
105
|
+
if (root === "taskRoot" && v.isolation !== undefined && v.baseRef !== undefined)
|
|
106
|
+
throw invalid(`${at}: a source for the isolated task root sets the tree's start; drop .baseRef`);
|
|
107
|
+
sources.push({ root, remote, sha: entry.sha, ...(entry.ref !== undefined ? { ref: entry.ref } : {}) });
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
if (v.isolation === undefined && sources === undefined)
|
|
111
|
+
throw invalid('declares nothing (give isolation: "worktree", sources, or both)');
|
|
112
|
+
return {
|
|
113
|
+
...(v.isolation !== undefined ? { isolation: "worktree" } : {}),
|
|
114
|
+
...(v.baseRef !== undefined ? { baseRef: v.baseRef } : {}),
|
|
115
|
+
...(v.name !== undefined ? { name: v.name } : {}),
|
|
116
|
+
...(sources !== undefined ? { sources } : {}),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
const declaredDigest = (d) => JSON.stringify(d === undefined ? null : [d.isolation ?? null, d.baseRef ?? null, d.name ?? null, (d.sources ?? []).map((s) => [rootKey(s.root), s.remote, s.sha, s.ref ?? null])]);
|
|
120
|
+
async function run(env, command, cwd) {
|
|
121
|
+
try {
|
|
122
|
+
const r = await env.exec(command, { cwd });
|
|
123
|
+
return r.ok ? r.value : undefined;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function sessionTreeName(sessionId) {
|
|
130
|
+
const slug = sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
|
|
131
|
+
return slug === "" ? "session" : slug;
|
|
132
|
+
}
|
|
133
|
+
export async function probeWorktreeCapability(env, cwd, opts) {
|
|
134
|
+
const no = (reason, detail, gitRoot) => ({ worktreeCapable: false, reason, detail, ...(gitRoot !== undefined ? { gitRoot } : {}) });
|
|
135
|
+
const version = await run(env, "git --version", cwd);
|
|
136
|
+
if (version === undefined || version.exitCode !== 0)
|
|
137
|
+
return no("git_unavailable", "git cannot be run in this environment");
|
|
138
|
+
const bare = await run(env, "git rev-parse --is-bare-repository", cwd);
|
|
139
|
+
if (bare === undefined || bare.exitCode !== 0)
|
|
140
|
+
return no("not_a_repository", `${cwd} is not inside a git repository`);
|
|
141
|
+
if (bare.stdout.trim() === "true")
|
|
142
|
+
return no("bare_repository", `${cwd} is a bare repository (it has no working tree to branch from)`);
|
|
143
|
+
const inside = await run(env, "git rev-parse --is-inside-work-tree", cwd);
|
|
144
|
+
if (inside === undefined || inside.exitCode !== 0 || inside.stdout.trim() !== "true")
|
|
145
|
+
return no("not_a_repository", `${cwd} is not inside a git work tree`);
|
|
146
|
+
const head = await run(env, "git rev-parse --verify --quiet 'HEAD^{commit}'", cwd);
|
|
147
|
+
if (head === undefined || head.exitCode !== 0)
|
|
148
|
+
return no("no_commit", `the repository at ${cwd} has no commit yet`);
|
|
149
|
+
const gitRoot = await managedAnchorOf(env, cwd);
|
|
150
|
+
const leaf = opts?.name !== undefined ? managedWorktreeDir(gitRoot, opts.name) : `${gitRoot}/${WORKTREE_PARENT}`;
|
|
151
|
+
const symlinked = await symlinkedLevel(env, gitRoot, leaf);
|
|
152
|
+
if (symlinked !== undefined)
|
|
153
|
+
return no("managed_parent_symlinked", symlinked, gitRoot);
|
|
154
|
+
let writable = gitRoot;
|
|
155
|
+
for (const level of [`${gitRoot}/${WORKTREE_PARENT}`, `${gitRoot}/.sema`]) {
|
|
156
|
+
const info = await env.fileInfo(level);
|
|
157
|
+
if (info.ok) {
|
|
158
|
+
writable = level;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const canWrite = await run(env, `test -w ${shq(writable)}`, cwd);
|
|
163
|
+
if (canWrite === undefined || canWrite.exitCode !== 0)
|
|
164
|
+
return no("parent_not_writable", `${writable} cannot be written`, gitRoot);
|
|
165
|
+
if (opts?.name !== undefined) {
|
|
166
|
+
const dir = managedWorktreeDir(gitRoot, opts.name);
|
|
167
|
+
const at = await env.fileInfo(dir);
|
|
168
|
+
if (at.ok || at.error.code !== "not_found")
|
|
169
|
+
return no("name_in_use", `a tree named "${opts.name}" already exists at ${dir}`, gitRoot);
|
|
170
|
+
const branch = managedWorktreeBranchOf(dir);
|
|
171
|
+
const ref = branch === undefined ? undefined : await run(env, `git rev-parse --verify --quiet ${shq(`refs/heads/${branch}`)}`, gitRoot);
|
|
172
|
+
if (ref !== undefined && ref.exitCode === 0)
|
|
173
|
+
return no("name_in_use", `the branch ${branch} already exists`, gitRoot);
|
|
174
|
+
}
|
|
175
|
+
return { worktreeCapable: true, gitRoot };
|
|
176
|
+
}
|
|
177
|
+
async function birthRecordPath(env, dir) {
|
|
178
|
+
const gitDir = await run(env, "git rev-parse --absolute-git-dir", dir);
|
|
179
|
+
return gitDir !== undefined && gitDir.exitCode === 0 && gitDir.stdout.trim().startsWith("/") ? `${gitDir.stdout.trim()}/sema-allocation` : undefined;
|
|
180
|
+
}
|
|
181
|
+
async function readBirthRecord(env, dir) {
|
|
182
|
+
const at = await birthRecordPath(env, dir);
|
|
183
|
+
if (at === undefined)
|
|
184
|
+
return undefined;
|
|
185
|
+
const text = await env.readTextFile(at);
|
|
186
|
+
if (!text.ok)
|
|
187
|
+
return undefined;
|
|
188
|
+
try {
|
|
189
|
+
const v = JSON.parse(text.value);
|
|
190
|
+
return typeof v.allocationId === "string" && typeof v.sessionId === "string" && typeof v.baseSha === "string" && FULL_SHA.test(v.baseSha) && typeof v.declared === "string"
|
|
191
|
+
? { allocationId: v.allocationId, sessionId: v.sessionId, baseSha: v.baseSha, declared: v.declared }
|
|
192
|
+
: undefined;
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const overlaps = (path, top) => path === top || path.startsWith(`${top}/`) || top.startsWith(`${path === "/" ? "" : path}/`);
|
|
199
|
+
async function refuseOverlap(env, base, additional) {
|
|
200
|
+
const top = await canonicalOf(env, base);
|
|
201
|
+
for (const directory of additional) {
|
|
202
|
+
if (overlaps(await canonicalOf(env, directory), top)) {
|
|
203
|
+
throw invalid(`isolates the task root's checkout ${top}, but additionalDirectories entry ${directory} reaches into it — writes there would land in the base checkout. Drop that directory, or work without isolation.`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const canonicalOf = async (env, path) => {
|
|
208
|
+
const r = await env.canonicalPath(path);
|
|
209
|
+
return r.ok ? r.value : path;
|
|
210
|
+
};
|
|
211
|
+
async function checkoutTopOf(env, dir) {
|
|
212
|
+
const top = await run(env, "git rev-parse --show-toplevel", dir);
|
|
213
|
+
return top !== undefined && top.exitCode === 0 && top.stdout.trim().startsWith("/") ? canonicalOf(env, top.stdout.trim()) : undefined;
|
|
214
|
+
}
|
|
215
|
+
async function placeInTree(env, root, dir) {
|
|
216
|
+
const canonical = await canonicalOf(env, root);
|
|
217
|
+
const top = await checkoutTopOf(env, canonical);
|
|
218
|
+
if (top === undefined || !(canonical === top || canonical.startsWith(`${top}/`)))
|
|
219
|
+
return undefined;
|
|
220
|
+
return `${dir}${canonical.slice(top.length)}`;
|
|
221
|
+
}
|
|
222
|
+
export async function openSessionCheckout(input) {
|
|
223
|
+
const { session, sessionId } = input;
|
|
224
|
+
const declared = screenWorkspaceDeclaration(input.declaration);
|
|
225
|
+
const observedLeaf = declared !== undefined ? await session.getStorage().getLeafId() : null;
|
|
226
|
+
const read = await readSessionCheckout(session, sessionId);
|
|
227
|
+
if (read.kind === "unreadable") {
|
|
228
|
+
throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}); the leg was not started rather than run outside the session's checkout.`);
|
|
229
|
+
}
|
|
230
|
+
if (read.kind === "record")
|
|
231
|
+
return reopen(input, declared, read.record);
|
|
232
|
+
if (declared === undefined)
|
|
233
|
+
return { taskRoot: input.baseRoot };
|
|
234
|
+
const forked = (await session.getMetadata()).forkedFrom !== undefined;
|
|
235
|
+
if (!forked && (await session.getStorage().findEntries("message")).length > 0) {
|
|
236
|
+
throw refusal("config.session_workspace_changed", "TaskSpec.workspace is declared on a session that already ran without it; a session's workspace is fixed by its first leg. Start a new session to work in a declared workspace.");
|
|
237
|
+
}
|
|
238
|
+
return allocate(input, declared, observedLeaf);
|
|
239
|
+
}
|
|
240
|
+
async function reopen(input, declared, record) {
|
|
241
|
+
const env = input.env;
|
|
242
|
+
if (record.released === true) {
|
|
243
|
+
throw refusal("config.session_workspace_changed", "This session's checkout was released; a released session runs no further leg. Start a new session.");
|
|
244
|
+
}
|
|
245
|
+
if (declaredDigest(declared) !== declaredDigest(record.declared)) {
|
|
246
|
+
throw refusal("config.session_workspace_changed", `TaskSpec.workspace differs from the declaration this session's checkout was opened under (allocation ${record.allocationId}); a session's workspace is fixed by its first leg. Send the same declaration on every leg, or start a new session.`);
|
|
247
|
+
}
|
|
248
|
+
for (const cell of record.checkouts)
|
|
249
|
+
if (cell.dir !== undefined)
|
|
250
|
+
await refuseOverlap(env, cell.repository, input.additionalDirectories ?? []);
|
|
251
|
+
let taskRoot = input.baseRoot;
|
|
252
|
+
for (const cell of record.checkouts) {
|
|
253
|
+
if (cell.dir === undefined)
|
|
254
|
+
continue;
|
|
255
|
+
const info = await env.fileInfo(cell.dir);
|
|
256
|
+
if (!info.ok) {
|
|
257
|
+
if (info.error.code === "not_found") {
|
|
258
|
+
throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} no longer exists; the leg was not started (it is never run in the base checkout instead). Release the session's checkout (releaseSessionCheckout) and start a new session.`);
|
|
259
|
+
}
|
|
260
|
+
throw refusal("workspace.checkout_unavailable", `This session's tree ${cell.dir} cannot be read (${thrownText(info.error)}); the leg was not started.`);
|
|
261
|
+
}
|
|
262
|
+
if (info.value.kind !== "directory")
|
|
263
|
+
throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer a directory; the leg was not started.`);
|
|
264
|
+
const birth = await readBirthRecord(env, cell.dir);
|
|
265
|
+
if (birth === undefined || birth.allocationId !== record.allocationId) {
|
|
266
|
+
throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer the tree this session minted (its allocation mark is missing or names another allocation); the leg was not started. Release the session's checkout and start a new session.`);
|
|
267
|
+
}
|
|
268
|
+
if (cell.root === "taskRoot") {
|
|
269
|
+
const placed = await placeInTree(env, input.baseRoot, cell.dir);
|
|
270
|
+
const repository = await repositoryRootOf(env, input.baseRoot);
|
|
271
|
+
if (placed === undefined || (repository !== undefined && (await canonicalOf(env, repository)) !== (await canonicalOf(env, cell.repository)))) {
|
|
272
|
+
throw refusal("config.session_workspace_changed", `This leg's task root ${input.baseRoot} is not in the repository this session's tree was minted from (${cell.repository}).`);
|
|
273
|
+
}
|
|
274
|
+
taskRoot = placed;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return { taskRoot, record };
|
|
278
|
+
}
|
|
279
|
+
async function allocate(input, declared, observedLeaf) {
|
|
280
|
+
const { env, sessionId, baseRoot } = input;
|
|
281
|
+
const additional = input.additionalDirectories ?? [];
|
|
282
|
+
const sources = declared.sources ?? [];
|
|
283
|
+
let isolatedRepository;
|
|
284
|
+
if (declared.isolation === "worktree")
|
|
285
|
+
await refuseOverlap(env, await managedAnchorOf(env, baseRoot), additional);
|
|
286
|
+
const sourceCells = [];
|
|
287
|
+
let taskRootSource;
|
|
288
|
+
const seenRepositories = new Set();
|
|
289
|
+
for (const source of sources) {
|
|
290
|
+
if (source.root !== "taskRoot" && !additional.includes(source.root.directory)) {
|
|
291
|
+
throw invalid(`source root ${source.root.directory} is not an additionalDirectories entry (the same spelling is required)`);
|
|
292
|
+
}
|
|
293
|
+
const location = source.root === "taskRoot" ? baseRoot : source.root.directory;
|
|
294
|
+
const repository = await repositoryRootOf(env, location);
|
|
295
|
+
const top = await checkoutTopOf(env, await canonicalOf(env, location));
|
|
296
|
+
if (repository === undefined || top === undefined)
|
|
297
|
+
throw refusal("workspace.source_mismatch", `The declared source for ${location} names a repository, but ${location} is not in a git checkout.`);
|
|
298
|
+
const key = await canonicalOf(env, repository);
|
|
299
|
+
if (seenRepositories.has(key))
|
|
300
|
+
throw invalid(`declares two sources for the repository at ${repository} (one source per repository)`);
|
|
301
|
+
seenRepositories.add(key);
|
|
302
|
+
if (source.root === "taskRoot" && declared.isolation === "worktree") {
|
|
303
|
+
taskRootSource = source;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const head = await run(env, "git rev-parse --verify --quiet 'HEAD^{commit}'", top);
|
|
307
|
+
if (head === undefined || head.exitCode !== 0 || head.stdout.trim() !== source.sha) {
|
|
308
|
+
throw refusal("workspace.source_mismatch", `The checkout at ${top} is not at the declared commit ${source.sha} (it is at ${head?.exitCode === 0 ? head.stdout.trim() : "an unreadable HEAD"}); the leg was not started.`);
|
|
309
|
+
}
|
|
310
|
+
sourceCells.push({ repository, root: source.root, baseSha: source.sha, source: { remote: source.remote, sha: source.sha, ...(source.ref !== undefined ? { ref: source.ref } : {}) } });
|
|
311
|
+
}
|
|
312
|
+
const allocationId = randomUUID();
|
|
313
|
+
const checkouts = [];
|
|
314
|
+
let taskRoot = baseRoot;
|
|
315
|
+
if (declared.isolation === "worktree") {
|
|
316
|
+
const name = declared.name ?? sessionTreeName(sessionId);
|
|
317
|
+
const probe = await probeWorktreeCapability(env, baseRoot);
|
|
318
|
+
if (!probe.worktreeCapable || probe.gitRoot === undefined) {
|
|
319
|
+
throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${baseRoot}: ${probe.detail ?? "the checkout cannot hold a managed tree"} (${probe.reason ?? "unknown"}). The leg was not started in the base checkout instead.`);
|
|
320
|
+
}
|
|
321
|
+
isolatedRepository = probe.gitRoot;
|
|
322
|
+
const dir = managedWorktreeDir(isolatedRepository, name);
|
|
323
|
+
let tree;
|
|
324
|
+
const existing = await env.fileInfo(dir);
|
|
325
|
+
if (existing.ok || existing.error.code !== "not_found") {
|
|
326
|
+
const birth = await readBirthRecord(env, dir);
|
|
327
|
+
if (birth === undefined || birth.sessionId !== sessionId) {
|
|
328
|
+
throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: a tree named "${name}" already exists at ${dir} and was not minted by this session (name_in_use). Declare another name.`);
|
|
329
|
+
}
|
|
330
|
+
if (birth.declared !== declaredDigest(declared)) {
|
|
331
|
+
const atOtherCommit = taskRootSource !== undefined && birth.baseSha !== taskRootSource.sha;
|
|
332
|
+
throw refusal(atOtherCommit ? "workspace.source_mismatch" : "workspace.isolation_unavailable", `The session's tree cannot be made: the tree this session minted earlier at ${dir} was minted under another declaration${atOtherCommit ? ` (it starts at ${birth.baseSha}, not at the declared commit ${taskRootSource.sha})` : ""} (name_in_use). Declare what it was minted under, or another name.`);
|
|
333
|
+
}
|
|
334
|
+
tree = { dir, branch: managedWorktreeBranchOf(dir) ?? `sema/${name}`, baseSha: birth.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId: birth.allocationId };
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
const named = await probeWorktreeCapability(env, baseRoot, { name });
|
|
338
|
+
if (!named.worktreeCapable) {
|
|
339
|
+
throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: ${named.detail ?? "the name is taken"} (${named.reason ?? "unknown"}). Declare another name.`);
|
|
340
|
+
}
|
|
341
|
+
let commit;
|
|
342
|
+
if (taskRootSource !== undefined)
|
|
343
|
+
commit = taskRootSource.sha;
|
|
344
|
+
else {
|
|
345
|
+
const base = await resolveBaseCommit(env, baseRoot, declared.baseRef ?? "fresh", undefined);
|
|
346
|
+
if ("error" in base)
|
|
347
|
+
throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: ${base.error}.`);
|
|
348
|
+
commit = base.sha;
|
|
349
|
+
}
|
|
350
|
+
let minted;
|
|
351
|
+
try {
|
|
352
|
+
minted = await mintManagedWorktree(env, { repoRoot: baseRoot, sessionId, name, commit });
|
|
353
|
+
}
|
|
354
|
+
catch (err) {
|
|
355
|
+
const why = thrownText(err);
|
|
356
|
+
throw refusal(taskRootSource !== undefined ? "workspace.source_mismatch" : "workspace.isolation_unavailable", `The session's tree cannot be made${taskRootSource !== undefined ? ` at the declared commit ${taskRootSource.sha}` : ""}: ${why.slice(0, 600)}`);
|
|
357
|
+
}
|
|
358
|
+
const undo = async (why, code) => {
|
|
359
|
+
const removed = await removeManagedWorktree(env, minted.anchor, minted.worktreeDir, minted.baseSha !== undefined ? { name: minted.branch, baseSha: minted.baseSha } : undefined, undefined, "clean");
|
|
360
|
+
throw refusal(code, `${why}${removed.ok ? "" : ` The tree minted for it was left at ${minted.worktreeDir} (${removed.detail.trim().slice(0, 200)}).`}`);
|
|
361
|
+
};
|
|
362
|
+
if (minted.baseSha === undefined || (taskRootSource !== undefined && minted.baseSha !== taskRootSource.sha)) {
|
|
363
|
+
return undo(`The session's tree is not at the declared commit${taskRootSource !== undefined ? ` ${taskRootSource.sha}` : ""}; the leg was not started.`, taskRootSource !== undefined ? "workspace.source_mismatch" : "workspace.isolation_unavailable");
|
|
364
|
+
}
|
|
365
|
+
const birthAt = await birthRecordPath(env, minted.worktreeDir);
|
|
366
|
+
const wrote = birthAt === undefined ? undefined : await env.writeFile(birthAt, JSON.stringify({ allocationId, sessionId, baseSha: minted.baseSha, declared: declaredDigest(declared) }));
|
|
367
|
+
if (wrote === undefined || !wrote.ok)
|
|
368
|
+
return undo("The session's tree could not be marked as this session's; the leg was not started.", "workspace.isolation_unavailable");
|
|
369
|
+
tree = { dir: minted.worktreeDir, branch: minted.branch, baseSha: minted.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId, undo };
|
|
370
|
+
}
|
|
371
|
+
checkouts.push({
|
|
372
|
+
repository: isolatedRepository,
|
|
373
|
+
root: "taskRoot",
|
|
374
|
+
baseSha: tree.baseSha,
|
|
375
|
+
dir: tree.dir,
|
|
376
|
+
name,
|
|
377
|
+
branch: tree.branch,
|
|
378
|
+
baseRef: tree.baseRef,
|
|
379
|
+
...(taskRootSource !== undefined ? { source: { remote: taskRootSource.remote, sha: taskRootSource.sha, ...(taskRootSource.ref !== undefined ? { ref: taskRootSource.ref } : {}) } } : {}),
|
|
380
|
+
});
|
|
381
|
+
const placed = await placeInTree(env, baseRoot, tree.dir);
|
|
382
|
+
if (placed === undefined) {
|
|
383
|
+
const why = `The task root ${baseRoot} has no place in the session's tree ${tree.dir}.`;
|
|
384
|
+
if (tree.undo !== undefined)
|
|
385
|
+
return tree.undo(why, "workspace.isolation_unavailable");
|
|
386
|
+
throw refusal("workspace.isolation_unavailable", why);
|
|
387
|
+
}
|
|
388
|
+
taskRoot = placed;
|
|
389
|
+
const record = { allocationId: tree.allocationId, sessionId, declared, checkouts: [...checkouts, ...sourceCells] };
|
|
390
|
+
return { taskRoot, record: await recordNow(input.session, record, observedLeaf, tree.undo) };
|
|
391
|
+
}
|
|
392
|
+
const record = { allocationId, sessionId, declared, checkouts: sourceCells };
|
|
393
|
+
return { taskRoot, record: await recordNow(input.session, record, observedLeaf) };
|
|
394
|
+
}
|
|
395
|
+
async function recordNow(session, record, observedLeaf, undo) {
|
|
396
|
+
try {
|
|
397
|
+
await appendSessionCheckout(session, record, observedLeaf);
|
|
398
|
+
}
|
|
399
|
+
catch (err) {
|
|
400
|
+
const why = `This session's checkout could not be recorded (${thrownText(err).slice(0, 300)}); the leg was not started.`;
|
|
401
|
+
const back = await readSessionCheckout(session, record.sessionId).catch((e) => ({ kind: "unreadable", detail: thrownText(e) }));
|
|
402
|
+
const dirs = record.checkouts.flatMap((cell) => (cell.dir === undefined ? [] : [cell.dir]));
|
|
403
|
+
const named = back.kind === "record" ? back.record : undefined;
|
|
404
|
+
const holds = named !== undefined && (named.allocationId === record.allocationId || named.checkouts.some((cell) => cell.dir !== undefined && dirs.includes(cell.dir)));
|
|
405
|
+
if (undo !== undefined && back.kind !== "unreadable" && !holds)
|
|
406
|
+
return undo(why, "workspace.checkout_unavailable");
|
|
407
|
+
const note = back.kind === "unreadable"
|
|
408
|
+
? ` The allocation record could not be read back${dirs.length > 0 ? `; the tree is kept at ${dirs.join(", ")}` : ""} (${back.detail.slice(0, 200)}).`
|
|
409
|
+
: named !== undefined && holds && named.allocationId !== record.allocationId
|
|
410
|
+
? ` Another record names this tree; the tree is kept at ${dirs.join(", ")}.`
|
|
411
|
+
: "";
|
|
412
|
+
throw refusal("workspace.checkout_unavailable", `${why}${note}`);
|
|
413
|
+
}
|
|
414
|
+
return record;
|
|
415
|
+
}
|
|
416
|
+
export async function releaseSessionCheckout(env, session, opts) {
|
|
417
|
+
const onExit = opts?.onExit ?? "keep-if-dirty";
|
|
418
|
+
if (onExit !== "keep-if-dirty" && onExit !== "keep") {
|
|
419
|
+
throw refusal("config.invalid_argument", `releaseSessionCheckout: onExit must be "keep-if-dirty" or "keep" (a removal that discards changes is not offered)`);
|
|
420
|
+
}
|
|
421
|
+
const sessionId = (await session.getMetadata()).id;
|
|
422
|
+
const read = await readSessionCheckout(session, sessionId);
|
|
423
|
+
if (read.kind === "unreadable")
|
|
424
|
+
throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}); nothing was removed.`);
|
|
425
|
+
if (read.kind === "none")
|
|
426
|
+
return { trees: [] };
|
|
427
|
+
const record = read.record;
|
|
428
|
+
const trees = [];
|
|
429
|
+
for (const cell of record.checkouts) {
|
|
430
|
+
if (cell.dir === undefined || cell.branch === undefined)
|
|
431
|
+
continue;
|
|
432
|
+
trees.push(await releaseTree(env, record, cell, onExit));
|
|
433
|
+
}
|
|
434
|
+
if (record.released !== true)
|
|
435
|
+
await appendSessionCheckout(session, { ...record, released: true });
|
|
436
|
+
return { trees };
|
|
437
|
+
}
|
|
438
|
+
const IGNORED_NAMED = 5;
|
|
439
|
+
function ignoredDetail(paths) {
|
|
440
|
+
const named = paths.slice(0, IGNORED_NAMED).map((p) => p.slice(0, 120)).join(", ");
|
|
441
|
+
const more = paths.length > IGNORED_NAMED ? ` and ${paths.length - IGNORED_NAMED} more` : "";
|
|
442
|
+
return `the tree holds files git ignores (${named}${more}), which removing it would delete — delete or move them, then release again`;
|
|
443
|
+
}
|
|
444
|
+
async function releaseTree(env, record, cell, onExit) {
|
|
445
|
+
const path = cell.dir;
|
|
446
|
+
const branchLeft = async () => {
|
|
447
|
+
const ref = await run(env, `git rev-parse --verify --quiet ${shq(`refs/heads/${cell.branch}`)}`, cell.repository);
|
|
448
|
+
return ref !== undefined && ref.exitCode === 0 ? { branch: cell.branch } : {};
|
|
449
|
+
};
|
|
450
|
+
const at = await env.fileInfo(path);
|
|
451
|
+
if (!at.ok) {
|
|
452
|
+
if (at.error.code !== "not_found")
|
|
453
|
+
return { path, removed: false, kept: "unverifiable", branch: cell.branch, detail: thrownText(at.error).slice(0, 300) };
|
|
454
|
+
await run(env, "git worktree prune", cell.repository);
|
|
455
|
+
return { path, removed: true, ...(await branchLeft()) };
|
|
456
|
+
}
|
|
457
|
+
const birth = await readBirthRecord(env, path);
|
|
458
|
+
if (birth === undefined || birth.allocationId !== record.allocationId)
|
|
459
|
+
return { path, removed: false, kept: "not_owned", ...(await branchLeft()) };
|
|
460
|
+
if (onExit === "keep")
|
|
461
|
+
return { path, removed: false, kept: "requested", branch: cell.branch };
|
|
462
|
+
const status = await run(env, "git status --porcelain --ignored --untracked-files=normal", path);
|
|
463
|
+
if (status === undefined || status.exitCode !== 0)
|
|
464
|
+
return { path, removed: false, kept: "unverifiable", branch: cell.branch };
|
|
465
|
+
const entries = status.stdout.split("\n").filter((line) => line !== "");
|
|
466
|
+
if (entries.some((line) => !line.startsWith("!! ")))
|
|
467
|
+
return { path, removed: false, kept: "dirty", branch: cell.branch };
|
|
468
|
+
if (entries.length > 0)
|
|
469
|
+
return { path, removed: false, kept: "ignored", branch: cell.branch, detail: ignoredDetail(entries.map((line) => line.slice(3))) };
|
|
470
|
+
const ahead = await run(env, `git rev-list --count ${shq(`${cell.baseSha}..HEAD`)}`, path);
|
|
471
|
+
const commits = ahead !== undefined && ahead.exitCode === 0 ? Number.parseInt(ahead.stdout.trim(), 10) : Number.NaN;
|
|
472
|
+
if (!Number.isFinite(commits))
|
|
473
|
+
return { path, removed: false, kept: "unverifiable", branch: cell.branch };
|
|
474
|
+
if (commits > 0)
|
|
475
|
+
return { path, removed: false, kept: "commits", branch: cell.branch };
|
|
476
|
+
const removed = await removeManagedWorktree(env, cell.repository, path, { name: cell.branch, baseSha: cell.baseSha }, undefined, "clean");
|
|
477
|
+
if (!removed.ok)
|
|
478
|
+
return { path, removed: false, kept: "unverifiable", branch: cell.branch, detail: removed.detail.trim().slice(0, 300) };
|
|
479
|
+
return { path, removed: true, ...(await branchLeft()) };
|
|
480
|
+
}
|
|
481
|
+
export function sessionFrameOf(record) {
|
|
482
|
+
if (record === undefined || record.checkouts.length === 0)
|
|
483
|
+
return undefined;
|
|
484
|
+
return record.checkouts.map((cell) => ({ ...cell, root: cell.root === "taskRoot" ? "taskRoot" : { directory: cell.root.directory }, ...(cell.source !== undefined ? { source: { ...cell.source } } : {}) }));
|
|
485
|
+
}
|
|
@@ -81,10 +81,11 @@ export interface TtlSessionStoreOptions {
|
|
|
81
81
|
* session — host-listable, never really-deleted, the declared full tier falsified in silence. On
|
|
82
82
|
* a store that DECLARES the partition (`capability.subagentPlacement`; an ignoring store legally drops
|
|
83
83
|
* placements), an acquire carrying a placement must therefore come back with a PERSISTED tuple whose
|
|
84
|
-
* join identity matches the declaration — a missing or foreign tuple refuses loudly.
|
|
84
|
+
* join identity matches the declaration — a missing or foreign tuple refuses loudly. A placed `fork` is judged by the
|
|
85
|
+
* same direction on the row it created (no squat can win a fork's fresh id, but a repo that drops the tuple can).
|
|
85
86
|
*
|
|
86
87
|
* @param persisted the tuple the backend holds for `sessionId` as resolved (`undefined`: an unplaced session).
|
|
87
|
-
* @param request the `acquire` options the caller passed.
|
|
88
|
+
* @param request the `acquire` options the caller passed (a placed `fork`: its placement).
|
|
88
89
|
* @param capability whether the store declares the subagent placement partition. `subagentPlacement` is read once,
|
|
89
90
|
* and only when the mirror direction is judged (a placement request that is not the read form, after `request`'s
|
|
90
91
|
* members are read), so a store may pass a getter over its live declaration.
|
|
@@ -92,7 +93,7 @@ export interface TtlSessionStoreOptions {
|
|
|
92
93
|
*/
|
|
93
94
|
export declare function admitSessionPlacement(sessionId: string, persisted: SessionPlacementRecord | undefined, request: {
|
|
94
95
|
requireExisting?: boolean;
|
|
95
|
-
placement?: SessionPlacement
|
|
96
|
+
placement?: Omit<SessionPlacement, "owner">;
|
|
96
97
|
}, capability: {
|
|
97
98
|
subagentPlacement: boolean;
|
|
98
99
|
}): void;
|
|
@@ -237,8 +238,15 @@ export declare class TtlSessionStore implements SessionStore {
|
|
|
237
238
|
*
|
|
238
239
|
* Adding this method is what makes {@link hasSessionFork} true for a `TtlSessionStore` wrapping ANY repo, so the
|
|
239
240
|
* fork capability mounts (it was INERT before — the durable repo had `fork` but the store never exposed it).
|
|
241
|
+
*
|
|
242
|
+
* `opts.placement` forks INTO the placement partition ({@link SessionStore.fork}): the tuple rides the repo's fork verbatim, as a
|
|
243
|
+
* placed create's does, and the cache entry carries the persisted tuple so the obligations arm at cache speed. On a store that
|
|
244
|
+
* declares the partition the created row is judged by the placement admission's mirror direction; a refusal removes the row
|
|
245
|
+
* first (nobody else holds the fresh id), so a dropped tuple leaves no ordinary copy of the source's history behind.
|
|
240
246
|
*/
|
|
241
|
-
fork(sourceId: string, owner?: string | null
|
|
247
|
+
fork(sourceId: string, owner?: string | null, opts?: {
|
|
248
|
+
placement?: Omit<SessionPlacement, "owner">;
|
|
249
|
+
}): Promise<string | null>;
|
|
242
250
|
/** Drop a session from the live set. With a durable repo (`evict: "forget"`) the history is kept. A release that rejects leaves the
|
|
243
251
|
* session where it was: the store keeps no view of it and retries nothing on its own, and a placed row is found again by the
|
|
244
252
|
* partition-GC leg's `listPlaced` — except one whose header is damaged, which `listPlaced` skips and every release of it rejects
|
|
@@ -340,6 +348,6 @@ export declare class TtlSessionStore implements SessionStore {
|
|
|
340
348
|
* Exported at the package root: the bundled store's `fork` and any other store's `fork` are the same question and must give the same
|
|
341
349
|
* answer — a backend reads the source session (`SessionRepo.open`), asks this, and hands the answer to `SessionRepo.fork` with the id
|
|
342
350
|
* and owner it mints. Forking the whole log instead copies the in-flight turn. The walk is one of the parent-chain walks, so it takes the
|
|
343
|
-
* shared guard: a leaf on a loop of tool-result messages is refused `
|
|
351
|
+
* shared guard: a leaf on a loop of tool-result messages is refused `corrupt_session` (the sentence of `getPathToRoot`) instead of followed.
|
|
344
352
|
*/
|
|
345
353
|
export declare function settledForkOptions(source: Session): Promise<ForkPoint>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { InMemorySessionRepo, ParentChainGuard, SessionError, findUnansweredToolBatch, compareOccupants, ownerCell, sessionLogMarkOf, uuidv7, } from "../internal/harness.js";
|
|
2
2
|
import { isSessionConflict, readSessionListQuery } from "./session.js";
|
|
3
3
|
import { readRetentionDeclaration } from "./retention.js";
|
|
4
|
-
import { readMember } from "./thrown-value.js";
|
|
4
|
+
import { readMember, thrownText } from "./thrown-value.js";
|
|
5
5
|
import { principalNameFault, principalNameOf } from "./principal-name.js";
|
|
6
6
|
import { DECLARATION_RECEIPT_MODE, optionKeys, receiptRefusal, receiveMembers, receiveOptions } from "./own-property-receipt.js";
|
|
7
7
|
import { describeFault, receive } from "./mods/kernel/receive.js";
|
|
@@ -25,6 +25,10 @@ export function admitSessionPlacement(sessionId, persisted, request, capability)
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
+
function placedRowCells(placement) {
|
|
29
|
+
const { owner, ...tuple } = placement;
|
|
30
|
+
return { placement: tuple, owner };
|
|
31
|
+
}
|
|
28
32
|
const TTL_SESSION_STORE_OPTION_KEYS = optionKeys()({ defaultTtlDays: 0, sweepIntervalMs: 0, repo: 0, evict: 0, durability: 0, placements: 0, retention: 0, hooks: 0 });
|
|
29
33
|
export const STORE_HOOK_KEYS = optionKeys()({ beforeSessionDelete: 0 });
|
|
30
34
|
export class TtlSessionStore {
|
|
@@ -197,7 +201,7 @@ export class TtlSessionStore {
|
|
|
197
201
|
async createAndStore(id, placement) {
|
|
198
202
|
let session;
|
|
199
203
|
try {
|
|
200
|
-
session = await this.repo.create({ ...(id !== undefined ? { id } : {}), ...(placement !== undefined ?
|
|
204
|
+
session = await this.repo.create({ ...(id !== undefined ? { id } : {}), ...(placement !== undefined ? placedRowCells(placement) : {}) });
|
|
201
205
|
}
|
|
202
206
|
catch (err) {
|
|
203
207
|
if (id === undefined || !isSessionConflict(err))
|
|
@@ -257,7 +261,8 @@ export class TtlSessionStore {
|
|
|
257
261
|
...(forkedFrom !== undefined ? { forkedFrom } : {}),
|
|
258
262
|
};
|
|
259
263
|
}
|
|
260
|
-
async fork(sourceId, owner) {
|
|
264
|
+
async fork(sourceId, owner, opts) {
|
|
265
|
+
const placement = opts?.placement;
|
|
261
266
|
let source;
|
|
262
267
|
try {
|
|
263
268
|
source = await this.repo.open({ id: sourceId, createdAt: "" });
|
|
@@ -269,13 +274,32 @@ export class TtlSessionStore {
|
|
|
269
274
|
throw err;
|
|
270
275
|
}
|
|
271
276
|
const forkOptions = await settledForkOptions(source);
|
|
272
|
-
const forked = await this.repo.fork(await source.getMetadata(), { ...forkOptions, id: uuidv7(), ...(owner !== undefined ? { owner } : {}) });
|
|
277
|
+
const forked = await this.repo.fork(await source.getMetadata(), { ...forkOptions, id: uuidv7(), ...(owner !== undefined ? { owner } : {}), ...(placement !== undefined ? { placement } : {}) });
|
|
273
278
|
const meta = await forked.getMetadata();
|
|
279
|
+
if (placement !== undefined) {
|
|
280
|
+
try {
|
|
281
|
+
this.assertPlacementAdmission(meta.id, meta.placement, { placement });
|
|
282
|
+
}
|
|
283
|
+
catch (refusal) {
|
|
284
|
+
let left;
|
|
285
|
+
try {
|
|
286
|
+
const created = { row: { owner: meta.owner ?? null, incarnation: meta.incarnation } };
|
|
287
|
+
await this.deleteRow(meta, this.repoHead !== undefined ? async () => created : undefined);
|
|
288
|
+
}
|
|
289
|
+
catch (err) {
|
|
290
|
+
left = err;
|
|
291
|
+
}
|
|
292
|
+
if (left === undefined)
|
|
293
|
+
throw refusal;
|
|
294
|
+
throw new SessionError("placement_refused", `${refusal.message} — and the copy ${meta.id} this fork created could not be removed (${thrownText(left)}); delete it by id`, refusal);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
274
297
|
this.entries.set(meta.id, {
|
|
275
298
|
session: forked,
|
|
276
299
|
lastActiveAt: Date.now(),
|
|
277
300
|
createdAt: meta.createdAt,
|
|
278
301
|
forkedFrom: meta.forkedFrom ?? sourceId,
|
|
302
|
+
...(meta.placement !== undefined ? { placement: meta.placement } : {}),
|
|
279
303
|
});
|
|
280
304
|
return meta.id;
|
|
281
305
|
}
|