authoravatarclover caruso<git@paperclover.net>2026-10-13 16:14:38-07:00
committeravatarclover caruso<git@paperclover.net>2026-11-13 16:28:31-08:00
log19223a8e9d01da0e197884183f53c290fde7ab37
treec33d4e6d4475e569d82fd958d24cdc799c4ca8fe
parent0a3a0718013495927cf596de79e0763634a660c9
signature Signed by SSH key SHA256:cOKiuRFOeSRxne6EWgHtdQQSlBxjOXm2hOCFnCdLQbQ

feat(workspaces): verify settlement captures before abandoned-work cleanup

Clover chose the working JJ change at settlement as the abandonment identity. Capture it immediately for each chat settlement, retain the same capture on repeated events, clear it on resume, and report abandonment only for that exact settlement. Thread IDs live in the per-thread record path; change, commit, and repository operation identities have one home in that capture. A known captured commit with no visible version is eligible only when the current working change is empty and its ancestry has no nonempty commits introduced since the historical visible repository view. This preserves rebases and later work hidden beneath an empty tip. Unknown source/history fails closed. Collection removes capture records with the directory. Atomic settle/unsettle/completion commands bypass the preparation lock so T3 settlement reactions and GC probes cannot deadlock. Verified real JJ rebase, abandonment, new nonempty work, new-work then empty-tip abandonment, idempotence, timestamp mismatch, resume, unknown source, and capture cleanup in the isolated V2/JJ/APFS lifecycle; lock tests and Nix syntax pass. Assisted-by: gpt-6.1-sol

4 files changed, 151 insertions(+), 4 deletions(-)

users/clover/packages/workspaces/README.md+9-1
......@@ -51,7 +51,15 @@ Settling a chat keeps its workspace directory. Cleanup begins only after every
5151chat using the directory is archived or deleted and no work is running. Archival
5252releases the directory for cleanup; settling does not. Automatic archival uses
5353T3 Code's guarded merge check and retains chats with open, closed, or missing PRs.
54An unavailable merge check pauses cleanup. `ws gc --dry-run` never archives chats.
54An unavailable completion check pauses cleanup. `ws gc --dry-run` never archives chats.
55
56When a chat settles, T3 captures that workspace's current JJ change with
57`ws settle`; resuming clears its capture with `ws unsettle`. `ws completion`
58reports abandonment only for that same settlement, when its captured change has
59no visible version, the current working change is empty, and its ancestry has
60no nonempty work introduced since the captured repository operation. Rebased
61changes, missing captures, and later work—even beneath an empty tip—retain the directory. These atomic
62per-thread records bypass the preparation lock and are removed with the workspace.
5563
5664Only registered workspaces under `~/workspaces` are collected. JJ retains
5765snapshotted changes; ignored files are deleted with the directory. Closing T3
users/clover/packages/workspaces/default.nix+5-3
......@@ -14,9 +14,11 @@ pkgs.writeShellApplication {
1414 native
1515 ];
1616 text = ''
17 if [[ "''${1-}" == ready-hook ]]; then
18 exec node ${./workspaces.mjs} "$@"
19 fi
17 case "''${1-}" in
18 ready-hook|settle|unsettle|completion)
19 exec node ${./workspaces.mjs} "$@"
20 ;;
21 esac
2022 mkdir -p "$HOME/.local/state/workspaces"
2123 workspace_lock="$HOME/.local/state/workspaces/lock"
2224 if [[ "''${1-}" == new ]]; then
users/clover/packages/workspaces/workspaces.mjs+76
......@@ -683,6 +683,81 @@ export async function main(args) {
683683 (!fs.existsSync(records) || !fs.readdirSync(records).length)
684684 ) return;
685685 const config = JSON.parse(fs.readFileSync(configFile));
686 if (["settle", "unsettle", "completion"].includes(command)) {
687 const expectedLength = command === "unsettle" ? 2 : command === "completion" ? 5 : 4;
688 if (
689 !argument || rest.length !== expectedLength || rest[0] !== "--thread-id" ||
690 (command !== "unsettle" && rest[2] !== "--settled-at") ||
691 (command === "completion" && rest[4] !== "--json")
692 ) {
693 throw new Error(`Run ws ${command} <name> --thread-id <id>${
694 command === "unsettle" ? "" : " --settled-at <time>"
695 }${command === "completion" ? " --json" : ""}.`);
696 }
697 const directory = workspace(argument);
698 const threadId = rest[1];
699 if (!/^[a-zA-Z0-9_-]+$/.test(threadId)) {
700 throw new Error("Choose a thread ID without path separators.");
701 }
702 const file = path.join(state, "settlements", argument, `${threadId}.json`);
703 if (command === "unsettle") {
704 fs.rmSync(file, { force: true });
705 return;
706 }
707 const settledAt = rest[3];
708 if (!Number.isFinite(Date.parse(settledAt))) {
709 throw new Error("Choose a valid settlement timestamp.");
710 }
711 const captured = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file)) : null;
712 if (command === "completion" && captured?.settledAt !== settledAt) {
713 console.log(JSON.stringify({ abandoned: false }));
714 return;
715 }
716 if (command === "settle" && captured?.settledAt === settledAt) return;
717 const record = JSON.parse(fs.readFileSync(path.join(records, `${argument}.json`)));
718 if (!record.prepared) {
719 throw new Error(`Workspace ${argument} is still preparing. Run ws deps ${argument}.`);
720 }
721 if (canonical(directory) !== directory || jjRepository(directory) !== jjRepository(config.repository)) {
722 throw new Error(`Workspace ${argument} belongs to another repository. Cleanup is paused.`);
723 }
724 if (command === "settle") {
725 const operationId = run("jj", [
726 "--ignore-working-copy", "op", "log", "-n", "1", "--no-graph", "-T", "id",
727 ], directory);
728 const [changeId, commitId] = run("jj", [
729 "log", "-r", "@", "--no-graph", "-T", 'change_id ++ "\n" ++ commit_id',
730 ], directory).split("\n");
731 writeJson(file, { settledAt, changeId, commitId, operationId });
732 return;
733 }
734 if (
735 !/^[k-z]{32}$/.test(captured.changeId) ||
736 !/^[a-f0-9]{40}$/.test(captured.commitId) ||
737 !/^[a-f0-9]{128}$/.test(captured.operationId)
738 ) throw new Error("The workspace settlement record is unreadable. Cleanup is paused.");
739 const currentEmpty = run("jj", ["log", "-r", "@", "--no-graph", "-T", "empty"], directory);
740 const knownChange = run("jj", [
741 "--ignore-working-copy", "log", "-r", captured.commitId, "--no-graph", "-T", "change_id",
742 ], directory);
743 if (knownChange !== captured.changeId) {
744 throw new Error("The captured workspace change is unreadable. Cleanup is paused.");
745 }
746 const visible = run("jj", [
747 "--ignore-working-copy", "log", "-r", `visible() & change_id(${captured.changeId})`,
748 "--no-graph", "-T", "commit_id",
749 ], directory);
750 // all() expands the historical baseline with the current ancestry's search space.
751 const laterWork = run("jj", [
752 "--ignore-working-copy", "log", "-r",
753 `(::@ ~ at_operation(${captured.operationId}, visible())) ~ empty()`,
754 "--no-graph", "-T", "commit_id",
755 ], directory);
756 console.log(JSON.stringify({
757 abandoned: visible === "" && currentEmpty === "true" && laterWork === "",
758 }));
759 return;
760 }
686761 if (command === "deps") {
687762 const file = path.join(records, `${argument}.json`);
688763 const record = JSON.parse(fs.readFileSync(file));
......@@ -874,6 +949,7 @@ export async function main(args) {
874949 );
875950 fs.rmSync(directory, { recursive: true });
876951 fs.rmSync(file);
952 fs.rmSync(path.join(state, "settlements", id), { recursive: true, force: true });
877953 console.log(`Removed workspace ${id}`);
878954 continue;
879955 }
users/clover/packages/workspaces/workspaces.test.mjs+61
......@@ -680,6 +680,66 @@ exec "$WORKSPACE_TEST_PNPM" "$@"
680680 await main(["gc"]);
681681 assert.ok(fs.existsSync(first), "a settled replacement chat keeps its workspace");
682682 assert.equal(readRecord().idleSince, null);
683 const settledAt = (await client.snapshot()).threads.find(
684 (thread) => thread.id === freshRecord.threadId,
685 ).settledAt;
686 const captureArgs = ["first", "--thread-id", freshRecord.threadId, "--settled-at", settledAt];
687 const completion = async (timestamp = settledAt) => {
688 const output = [];
689 const log = mock.method(console, "log", (value) => output.push(value));
690 try {
691 await main(["completion", "first", "--thread-id", freshRecord.threadId,
692 "--settled-at", timestamp, "--json"]);
693 assert.equal(output.length, 1);
694 return JSON.parse(output[0]);
695 } finally {
696 log.mock.restore();
697 }
698 };
699 assert.deepEqual(await completion(), { abandoned: false }, "missing capture cannot prove abandonment");
700 fs.writeFileSync(path.join(first, "settled-work.txt"), "work captured at settlement\n");
701 await main(["settle", ...captureArgs]);
702 const captureFile = path.join(directory, ".local/state/workspaces/settlements/first", `${freshRecord.threadId}.json`);
703 const capturedContents = fs.readFileSync(captureFile, "utf8");
704 const captured = JSON.parse(capturedContents);
705 assert.equal(captured.changeId, run("jj", ["log", "-r", "@", "--no-graph", "-T", "change_id"], {
706 cwd: first, encoding: "utf8",
707 }).trim(), "capture uses the working change itself");
708 assert.deepEqual(await completion(), { abandoned: false }, "visible captured change stays alive");
709 run("jj", ["rebase", "-r", "@", "-d", latestMain], { cwd: first, stdio: "pipe" });
710 assert.deepEqual(await completion(), { abandoned: false }, "rebased change keeps its identity and workspace");
711 run("jj", ["new", "@"], { cwd: first, stdio: "pipe" });
712 fs.writeFileSync(path.join(first, "later-work.txt"), "keep later nonempty ancestor\n");
713 run("jj", ["new", "@"], { cwd: first, stdio: "pipe" });
714 const laterChange = run("jj", ["log", "-r", "@-", "--no-graph", "-T", "change_id"], {
715 cwd: first, encoding: "utf8",
716 }).trim();
717 run("jj", ["abandon", captured.changeId], { cwd: first, stdio: "pipe" });
718 assert.deepEqual(await completion(), { abandoned: false },
719 "later nonempty work behind an empty tip prevents abandonment cleanup");
720 assert.equal(fs.readFileSync(path.join(first, "later-work.txt"), "utf8"), "keep later nonempty ancestor\n");
721 run("jj", ["abandon", laterChange], { cwd: first, stdio: "pipe" });
722 assert.deepEqual(await completion(), { abandoned: true }, "real JJ abandonment releases captured work");
723 await main(["settle", ...captureArgs]);
724 assert.equal(fs.readFileSync(captureFile, "utf8"), capturedContents,
725 "repeated settlement does not recapture a moved working change");
726 const newWork = path.join(first, "new-work.txt");
727 fs.writeFileSync(newWork, "keep this new work\n");
728 assert.deepEqual(await completion(), { abandoned: false }, "new nonempty work prevents abandoned cleanup");
729 fs.rmSync(newWork);
730 assert.deepEqual(await completion(), { abandoned: true });
731 fs.renameSync(path.join(first, ".jj"), path.join(first, ".jj-hidden"));
732 try {
733 await assert.rejects(completion(), /ENOENT/);
734 } finally {
735 fs.renameSync(path.join(first, ".jj-hidden"), path.join(first, ".jj"));
736 }
737 const laterSettlement = new Date(Date.parse(settledAt) + 1000).toISOString();
738 assert.deepEqual(await completion(laterSettlement), { abandoned: false }, "another settlement cannot reuse the capture");
739 await main(["unsettle", "first", "--thread-id", freshRecord.threadId]);
740 assert.equal(fs.existsSync(captureFile), false, "resuming clears the thread capture");
741 assert.deepEqual(await completion(), { abandoned: false });
742 await main(["settle", ...captureArgs]);
683743 archiveHandler = async ({ workspacePath }) => {
684744 if (workspacePath !== first) return { archivedThreadIds: [] };
685745 await client.dispatch({ type: "thread.unsettle", threadId: freshRecord.threadId, reason: "user" });
......@@ -702,6 +762,7 @@ exec "$WORKSPACE_TEST_PNPM" "$@"
702762 age();
703763 await main(["gc"]);
704764 assert.equal(fs.existsSync(first), false, "merged archived workspace is collected after grace");
765 assert.equal(fs.existsSync(path.dirname(captureFile)), false, "collection removes settlement captures");
705766 assert.ok(archiveRequests.some(({ workspacePath }) => workspacePath === first));
706767 assert.ok(archiveRequests.every(({ workspacePath }) =>
707768 path.dirname(workspacePath) === path.join(directory, "workspaces")