notesoup 0.60.0 → 0.60.1

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.
@@ -1,21 +1,20 @@
1
1
  import { execFileSync, spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { errorMessage } from "../error-message.js";
5
5
  /** Lock runtime artifacts are not notes and must not appear in snapshots or `git status`. */
6
- const RUNTIME_IGNORE = ".dream.lock*";
7
- /** Add the runtime-artifact pattern to the repository's local exclude, once. */
6
+ const RUNTIME_IGNORE = ["/.dream.lock*", "/.project-claim.sqlite", "/.project-claim.sqlite-*", "/.project-pending-*/"];
7
+ /** Install root-only excludes before staging; fail the audit rather than snapshot runtime files. */
8
8
  function ensureRuntimeIgnored(home) {
9
- try {
10
- const exclude = join(home, ".git", "info", "exclude");
11
- const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
12
- if (current.split(/\r?\n/).includes(RUNTIME_IGNORE))
13
- return;
14
- mkdirSync(dirname(exclude), { recursive: true });
15
- const prefix = current.length > 0 && !current.endsWith("\n") ? `${current}\n` : current;
16
- writeFileSync(exclude, `${prefix}${RUNTIME_IGNORE}\n`);
17
- }
18
- catch { /* best effort: an unignored lock only adds noise to the audit */ }
9
+ const exclude = join(home, ".git", "info", "exclude");
10
+ const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
11
+ const lines = new Set(current.split(/\r?\n/));
12
+ const missing = RUNTIME_IGNORE.filter(pattern => !lines.has(pattern));
13
+ if (!missing.length)
14
+ return;
15
+ mkdirSync(dirname(exclude), { recursive: true });
16
+ const prefix = current.length && !current.endsWith("\n") ? "\n" : "";
17
+ appendFileSync(exclude, prefix + missing.join("\n") + "\n");
19
18
  }
20
19
  /** Snapshot at begin and end; a repository without HEAD gets an empty baseline commit. */
21
20
  export function gitCommit(home, message) {
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join, resolve, sep } from "node:path";
4
+ import { trySqliteLock } from "../sqlite-lock.js";
4
5
  import { slugify } from "./paths.js";
5
6
  function errno(error) {
6
7
  return typeof error === "object" && error !== null ? error.code : undefined;
@@ -135,85 +136,50 @@ function updateMarker(namespace, marker) {
135
136
  }
136
137
  return { ...namespace, ...marker };
137
138
  }
138
- const claimSleep = new Int32Array(new SharedArrayBuffer(4));
139
- function awaitClaim(path, attempt) {
140
- const deadline = performance.now() + 5_000;
141
- for (;;) {
142
- const result = attempt();
143
- if (result !== undefined)
144
- return result;
145
- const remaining = deadline - performance.now();
146
- if (remaining <= 0)
147
- throw new Error(`Timed out waiting for project claim at ${path}`);
148
- Atomics.wait(claimSleep, 0, 0, Math.min(10, remaining));
149
- }
139
+ function checkoutMarker(cwd) {
140
+ const path = canonicalRoot(cwd);
141
+ return { id: originRemote(path) ?? path, path };
150
142
  }
151
143
  /** Resolve and claim the readable notebook for one repository identity. */
152
144
  export function resolveProjectNamespace(cwd, home) {
153
- mkdirSync(projectRoot(home), { recursive: true });
154
- // Serialize the scan as well as publication: an unmarked directory seen under
155
- // this lock is legacy, not another resolver between mkdir and marker write.
156
- const lock = join(home, ".project-claim");
157
- awaitClaim(lock, () => {
158
- try {
159
- mkdirSync(lock);
160
- return true;
161
- }
162
- catch (error) {
163
- if (errno(error) === "EEXIST")
164
- return undefined;
165
- throw error;
166
- }
167
- });
145
+ const expected = checkoutMarker(cwd);
146
+ const current = projectNamespaces(home).find(candidate => candidate.id === expected.id);
147
+ if (current?.path === expected.path)
148
+ return current;
149
+ const root = projectRoot(home);
150
+ mkdirSync(root, { recursive: true });
151
+ const lockPath = join(home, ".project-claim.sqlite");
152
+ const release = trySqliteLock(lockPath, 5000);
153
+ if (!release)
154
+ throw new Error(`Timed out waiting for project claim at ${lockPath}`);
168
155
  try {
169
- return claimProjectNamespace(cwd, home);
170
- }
171
- finally {
172
- rmdirSync(lock);
173
- }
174
- }
175
- function claimProjectNamespace(cwd, home) {
176
- const root = canonicalRoot(cwd);
177
- const remote = originRemote(root);
178
- const id = remote ?? root;
179
- const markerRoot = projectRoot(home);
180
- mkdirSync(markerRoot, { recursive: true });
181
- const namespaces = projectNamespaces(home);
182
- let found = namespaces.find(candidate => candidate.id === id);
183
- if (!found && remote) {
184
- found = namespaces.find(candidate => candidate.id === root);
156
+ // The checkout may have gained an origin and a peer may have already adopted it.
157
+ const marker = checkoutMarker(cwd);
158
+ const { id, path } = marker;
159
+ const namespaces = projectNamespaces(home);
160
+ const found = namespaces.find(candidate => candidate.id === id) ?? namespaces.find(candidate => candidate.id === path);
185
161
  if (found)
186
- found = updateMarker(found, { id: remote, path: root });
187
- }
188
- if (found) {
189
- if (found.path !== root)
190
- found = updateMarker(found, { id: found.id, path: root });
191
- return found;
192
- }
193
- const base = slugify(basename(root));
194
- // The claim lock makes this a stable snapshot of legacy, unmarked names.
195
- const taken = new Set(readdirSync(markerRoot));
196
- for (let suffix = 0;; suffix++) {
197
- const name = suffix === 0 ? base : `${base}-${suffix}`;
198
- if (taken.has(name))
199
- continue;
200
- const dir = join(markerRoot, name);
201
- try {
202
- mkdirSync(dir);
203
- }
204
- catch (error) {
205
- if (errno(error) !== "EEXIST")
162
+ return found.id === id && found.path === path ? found : updateMarker(found, marker);
163
+ const base = slugify(basename(path));
164
+ for (let suffix = 0;; suffix++) {
165
+ const name = suffix === 0 ? base : `${base}-${suffix}`;
166
+ const dir = join(root, name);
167
+ if (lstatSync(dir, { throwIfNoEntry: false }))
168
+ continue; // Includes unmarked legacy names.
169
+ const staged = mkdtempSync(join(home, ".project-pending-"));
170
+ try {
171
+ writeFileSync(join(staged, ".project"), JSON.stringify(marker));
172
+ renameSync(staged, dir);
173
+ }
174
+ catch (error) {
175
+ rmSync(staged, { recursive: true, force: true });
206
176
  throw error;
207
- // A writer outside this protocol may have won after the snapshot.
208
- // Never mistake its incomplete publication for a different identity.
209
- let winner = awaitClaim(join(dir, ".project"), () => readMarker(dir));
210
- if (winner.id !== id && !(remote && winner.id === root))
211
- continue;
212
- if (winner.id !== id || winner.path !== root)
213
- winner = updateMarker(winner, { id, path: root });
214
- return winner;
177
+ }
178
+ return { name, dir, ...marker };
215
179
  }
216
- return updateMarker({ name, dir, id, path: root }, { id, path: root });
180
+ }
181
+ finally {
182
+ release();
217
183
  }
218
184
  }
219
185
  /** Existing root discovery, including linked worktrees, without invoking Git. */
@@ -0,0 +1,2 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export declare function trySqliteLock(path: string, waitMs: 0 | 5000): (() => void) | undefined;
@@ -0,0 +1,17 @@
1
+ /** The open transaction is the lock. Never unlink the database, even after a crash. */
2
+ export function trySqliteLock(path, waitMs) {
3
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
4
+ if (!sqlite?.DatabaseSync)
5
+ throw new Error("Notesoup locks require built-in node:sqlite (Node 22.13+).");
6
+ const db = new sqlite.DatabaseSync(path);
7
+ try {
8
+ db.exec(`PRAGMA busy_timeout = ${waitMs}; BEGIN IMMEDIATE`);
9
+ }
10
+ catch (error) {
11
+ db.close();
12
+ if (error instanceof Error && "errcode" in error && error.errcode === 5)
13
+ return undefined; // SQLITE_BUSY
14
+ throw error;
15
+ }
16
+ return () => db.close(); // Closing rolls back the empty transaction.
17
+ }
@@ -1,17 +1,15 @@
1
- /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
1
  import { Type, type Static } from "typebox";
3
2
  import { type NotesIdentity } from "../notes/index.js";
4
- import { type DreamLock } from "../dream/lock.js";
5
3
  import { type Outcome } from "../result.js";
6
4
  /** The one open dream per session; the host owns where it lives. */
7
5
  type DreamOpening = {
8
6
  project: string;
9
- lock: DreamLock;
7
+ release: () => void;
10
8
  generation: number;
11
9
  };
12
10
  export type DreamState = {
13
11
  project?: string;
14
- lock?: DreamLock;
12
+ release?: () => void;
15
13
  pending?: DreamOpening;
16
14
  generation?: number;
17
15
  };
@@ -1,10 +1,11 @@
1
1
  /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
+ import { join } from "node:path";
2
3
  import { Type } from "typebox";
3
4
  import { localIso } from "../notes/frontmatter.js";
4
5
  import { createNotesStore, noteIdentity } from "../notes/index.js";
5
6
  import { projectNamespaces } from "../notes/project-namespace.js";
6
7
  import { gitCommit } from "../dream/git.js";
7
- import { acquireDreamLock, dreamLockPath, releaseDreamLock } from "../dream/lock.js";
8
+ import { trySqliteLock } from "../sqlite-lock.js";
8
9
  import { failure, success } from "../result.js";
9
10
  import { renderOutcome, resultSchema } from "./result.js";
10
11
  import { failureOf, listedFile, ListedFileSchema, NoteIdentitySchema, renderListData, snapshot, SnapshotSchema } from "./notes.js";
@@ -18,21 +19,19 @@ function nextGeneration(state) {
18
19
  }
19
20
  /** Drop an open dream without an end commit, e.g. when its session shuts down. */
20
21
  export function abandonDream(state) {
21
- const pending = state.pending;
22
- if (pending)
23
- releaseDreamLock(pending.lock);
24
- if (state.lock && state.lock !== pending?.lock)
25
- releaseDreamLock(state.lock);
22
+ state.pending?.release();
23
+ state.release?.();
26
24
  nextGeneration(state);
27
25
  delete state.project;
28
- delete state.lock;
26
+ delete state.release;
29
27
  delete state.pending;
30
28
  }
31
29
  /** Release an opening without disturbing a newer opening in the same state. */
32
30
  function releaseOpening(state, opening) {
33
- releaseDreamLock(opening.lock);
34
- if (currentOpening(state, opening))
35
- delete state.pending;
31
+ if (!currentOpening(state, opening))
32
+ return;
33
+ opening.release();
34
+ delete state.pending;
36
35
  }
37
36
  function cancelledOpening(state, opening) {
38
37
  releaseOpening(state, opening);
@@ -67,11 +66,11 @@ export const dreamBegin = {
67
66
  if (project !== identity.projectKey && !projectNamespaces(identity.home).some(namespace => namespace.name === project)) {
68
67
  return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
69
68
  }
70
- const lock = acquireDreamLock(dreamLockPath(identity.home));
71
- if (!lock)
72
- return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home)}. If none is running, delete that file by hand.`);
73
- // Publish ownership before the first await. Shutdown can therefore release this exact token.
74
- const opening = { project, lock, generation: nextGeneration(state) };
69
+ const release = trySqliteLock(join(identity.home, ".dream.lock.sqlite"), 0);
70
+ if (!release)
71
+ return failure("already_dreaming", "Another dream is open in this notes home.");
72
+ // Publish ownership before the first await so shutdown can release this transaction.
73
+ const opening = { project, release, generation: nextGeneration(state) };
75
74
  state.pending = opening;
76
75
  try {
77
76
  const store = createNotesStore({ ...identity, dreaming: project });
@@ -102,7 +101,7 @@ export const dreamBegin = {
102
101
  if (!currentOpening(state, opening))
103
102
  return cancelledOpening(state, opening);
104
103
  state.project = opening.project;
105
- state.lock = opening.lock;
104
+ state.release = opening.release;
106
105
  delete state.pending;
107
106
  return success({ project, baseline: baseline.commit, ...listed.data });
108
107
  }
@@ -1,13 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
3
  import fs from "node:fs/promises";
4
4
  import { syncBuiltinESMExports } from "node:module";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import test from "node:test";
8
- import { execFileSync } from "node:child_process";
8
+ import { once } from "node:events";
9
+ import { execFileSync, spawn } from "node:child_process";
9
10
  import { Check } from "typebox/value";
10
- import { createNotesStore } from "../src/notes/index.js";
11
+ import { createNotesStore, projectKey } from "../src/notes/index.js";
11
12
  import { abandonDream, dreamBegin, dreamEnd, dreamForget, dreamingIdentity } from "../src/tools/dream.js";
12
13
  import { notesRead, notesUpdate, notesWrite } from "../src/tools/notes.js";
13
14
  import { notesToolContext } from "../src/tools/notes-context.js";
@@ -43,7 +44,6 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
43
44
  assert.ok(begun.data.files.every(f => typeof f.last_accessed === "string"), "the dream's list shows each note's last access");
44
45
  assert.match(dreamBegin.render(begun), /\| accessed /);
45
46
  assert.equal((await dreamBegin.execute({}, me, state)).ok, false, "only one dream at a time");
46
- assert.ok(existsSync(join(home, ".dream.lock")), "the notes-home lock is held");
47
47
  assert.equal((await dreamBegin.execute({ project: "beta" }, as("other", "alpha"), {})).ok, false, "another session can't dream the same project");
48
48
  assert.ok((await notesWrite.execute({ address: "@projects/beta/rule", content: "merged" }, ident())).ok);
49
49
  assert.ok((await notesUpdate.execute({ address: "@sessions/b1/checkpoint", edits: [{ oldText: "old", newText: "new" }] }, ident())).ok);
@@ -60,13 +60,12 @@ test("a dream opens one other project, writes its notes, deletes only crumpled o
60
60
  assert.equal(existsSync(join(home, "pi", "session", "b2", "trash.md")), false);
61
61
  const ended = await dreamEnd.execute({}, me, state);
62
62
  assert.ok(ended.ok && ended.data.commit && ended.data.commit !== begun.data.baseline, "dream_end commits the changes");
63
- assert.equal(existsSync(join(home, ".dream.lock")), false, "the lock is released");
64
63
  assert.equal(execFileSync("git", ["status", "--porcelain"], { cwd: home, encoding: "utf8" }), "", "the audit leaves a clean tree");
65
64
  assert.equal((await notesWrite.execute({ address: "@projects/beta/rule", content: "x" }, ident())).ok, false, "closed again");
66
65
  assert.equal((await dreamEnd.execute({}, me, state)).ok, false);
67
66
  });
68
67
  test("pending openings exclude concurrent begins and stale cleanup preserves a newer generation", async (t) => {
69
- const { home, as } = fixture(t);
68
+ const { as } = fixture(t);
70
69
  const me = as("s", "alpha");
71
70
  const state = {};
72
71
  const old = dreamBegin.execute({}, me, state);
@@ -78,20 +77,18 @@ test("pending openings exclude concurrent begins and stale cleanup preserves a n
78
77
  assert.ok(!concurrent.ok && concurrent.error.code === "already_dreaming");
79
78
  assert.equal(state.pending, pending);
80
79
  abandonDream(state);
81
- assert.equal(existsSync(join(home, ".dream.lock")), false);
82
80
  const newer = dreamBegin.execute({ project: "beta" }, me, state);
83
81
  const newerPending = state.pending;
84
82
  assert.ok(newerPending && newerPending.generation > pending.generation);
85
- const token = readFileSync(join(home, ".dream.lock"), "utf8");
86
83
  const cancelled = await old;
87
84
  assert.ok(!cancelled.ok && cancelled.error.code === "cancelled");
88
- assert.equal(readFileSync(join(home, ".dream.lock"), "utf8"), token);
85
+ const refused = await dreamBegin.execute({}, me, {});
86
+ assert.ok(!refused.ok && refused.error.code === "already_dreaming");
89
87
  const begun = await newer;
90
88
  assert.ok(begun.ok);
91
89
  assert.equal(state.project, "beta");
92
90
  assert.equal(state.pending, undefined);
93
91
  assert.ok((await dreamEnd.execute({}, me, state)).ok);
94
- assert.equal(existsSync(join(home, ".dream.lock")), false);
95
92
  });
96
93
  test("a thrown scan releases pending ownership before propagating the defect", async (t) => {
97
94
  const { home, as } = fixture(t);
@@ -106,10 +103,9 @@ test("a thrown scan releases pending ownership before propagating the defect", a
106
103
  syncBuiltinESMExports();
107
104
  t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports(); });
108
105
  await assert.rejects(dreamBegin.execute({}, as("s", "alpha"), state), error => error === sentinel);
109
- assert.equal(existsSync(join(home, ".dream.lock")), false);
110
106
  assert.equal(state.pending, undefined);
111
107
  assert.equal(state.project, undefined);
112
- assert.equal(state.lock, undefined);
108
+ assert.equal(state.release, undefined);
113
109
  t.mock.restoreAll();
114
110
  syncBuiltinESMExports();
115
111
  assert.ok((await dreamBegin.execute({}, as("s", "alpha"), state)).ok, "the same state can retry after a failed scan");
@@ -122,10 +118,9 @@ test("baseline failure releases pending ownership and permits a retry", async (t
122
118
  writeFileSync(join(home, ".git"), "not a Git repository");
123
119
  const failed = await dreamBegin.execute({}, me, state);
124
120
  assert.ok(!failed.ok && failed.error.code === "audit_failed");
125
- assert.equal(existsSync(join(home, ".dream.lock")), false);
126
121
  assert.equal(state.pending, undefined);
127
122
  assert.equal(state.project, undefined);
128
- assert.equal(state.lock, undefined);
123
+ assert.equal(state.release, undefined);
129
124
  const ended = await dreamEnd.execute({}, me, state);
130
125
  assert.ok(!ended.ok && ended.error.code === "not_dreaming");
131
126
  rmSync(join(home, ".git"));
@@ -220,11 +215,41 @@ test("named-project mutation receipts carry their project metadata and fit their
220
215
  assert.equal(Check(dreamForget.outputSchema, forgotten.data), true, "dream_forget accepts its own named-project receipt");
221
216
  assert.ok((await dreamEnd.execute({}, me, state)).ok);
222
217
  });
218
+ test("a killed dream releases its lock without blocking project claims or note writes", { timeout: 20_000 }, async (t) => {
219
+ const { as } = fixture(t);
220
+ const script = `
221
+ import { dreamBegin } from ${JSON.stringify(new URL("../src/tools/dream.js", import.meta.url).href)};
222
+ globalThis.dream = {};
223
+ const result = await dreamBegin.execute({}, JSON.parse(process.argv[1]), globalThis.dream);
224
+ if (!result.ok) throw new Error(result.error.message);
225
+ process.send("open");
226
+ setInterval(() => {}, 60000);
227
+ `;
228
+ const child = spawn(process.execPath, ["--input-type=module", "-e", script, JSON.stringify(as("child", "alpha"))], { stdio: ["ignore", "ignore", "inherit", "ipc"] });
229
+ t.after(() => { child.kill("SIGKILL"); });
230
+ const exit = once(child, "exit");
231
+ assert.equal(await Promise.race([once(child, "message").then(([message]) => message), exit]), "open");
232
+ const next = as("next", "beta");
233
+ const state = {};
234
+ const refused = await dreamBegin.execute({}, next, state);
235
+ assert.ok(!refused.ok && refused.error.code === "already_dreaming");
236
+ assert.equal(projectKey("/work/another", next.home), "another");
237
+ await createNotesStore(next).write("@project/live", "still writable");
238
+ assert.ok(child.kill("SIGKILL"));
239
+ assert.deepEqual(await exit, [null, "SIGKILL"]);
240
+ assert.ok((await dreamBegin.execute({}, next, state)).ok);
241
+ assert.equal((await createNotesStore(next).read("@project/live"))?.body, "still writable");
242
+ assert.ok((await dreamEnd.execute({}, next, state)).ok);
243
+ });
223
244
  test("a notes-home lock prevents interleaved dream Git audits", async (t) => {
224
245
  const { home, as } = fixture(t);
225
246
  const alpha = as("alpha-session", "alpha"), beta = as("beta-session", "beta");
226
247
  await createNotesStore(alpha).write("@project/note", "before alpha");
227
248
  await createNotesStore(beta).write("@project/note", "before beta");
249
+ // A crashed project claim may leave a staged marker. Neither it nor the lock DB belongs in Git.
250
+ const staged = mkdtempSync(join(home, ".project-pending-"));
251
+ writeFileSync(join(staged, ".project"), "{}");
252
+ projectKey("/work/another", home);
228
253
  const alphaState = {}, betaState = {};
229
254
  const begun = await dreamBegin.execute({ project: "alpha" }, alpha, alphaState);
230
255
  assert.ok(begun.ok);
@@ -237,6 +262,9 @@ test("a notes-home lock prevents interleaved dream Git audits", async (t) => {
237
262
  const ended = await dreamEnd.execute({}, alpha, alphaState);
238
263
  assert.ok(ended.ok && ended.data.commit !== undefined);
239
264
  assert.notEqual(ended.data.commit, begun.data.baseline);
265
+ for (const commit of [begun.data.baseline, ended.data.commit]) {
266
+ assert.equal(execFileSync("git", ["ls-tree", "--name-only", commit], { cwd: home, encoding: "utf8" }), "project\n");
267
+ }
240
268
  const changed = execFileSync("git", ["show", "--format=", "--name-only", ended.data.commit], { cwd: home, encoding: "utf8" });
241
269
  assert.match(changed, /project\/alpha\/note\.md/);
242
270
  assert.doesNotMatch(changed, /project\/beta\/note\.md/);
@@ -1,7 +1,7 @@
1
1
  import { notesIdentityFromPi } from "../plugins/pi/notes/adapter.js";
2
2
  import { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "../src/boot/text.js";
3
3
  import assert from "node:assert/strict";
4
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
5
5
  import fs from "node:fs/promises";
6
6
  import { syncBuiltinESMExports } from "node:module";
7
7
  import { dirname, join } from "node:path";
@@ -31,7 +31,6 @@ for (const scanFails of [false, true]) {
31
31
  const otherCtx = context(manager(), undefined, undefined, true, join(testEnvironment.cwd, "other-project"));
32
32
  const other = notesIdentityFromPi(otherCtx);
33
33
  assert.notEqual(other.projectKey, me.projectKey);
34
- const lockPath = join(me.home, ".dream.lock");
35
34
  const original = fs.readdir;
36
35
  let enter;
37
36
  let release;
@@ -52,20 +51,17 @@ for (const scanFails of [false, true]) {
52
51
  t.after(() => { release(); t.mock.restoreAll(); syncBuiltinESMExports(); });
53
52
  const opening = call(captured, "dream_begin", {}, ctx);
54
53
  await entered;
55
- assert.ok(existsSync(lockPath), "begin acquired ownership before the controlled scan await");
54
+ assert.equal(resultError(await call(captured, "dream_begin", {}, otherCtx)).code, "already_dreaming");
56
55
  assert.equal(resultError(await call(captured, "dream_begin", {}, ctx)).code, "already_dreaming");
57
56
  await runHandlers(captured, "session_shutdown", { type: "session_shutdown" }, ctx);
58
- assert.equal(existsSync(lockPath), false, "the registered shutdown handler releases pending ownership");
59
57
  assert.equal(resultError(await call(captured, "dream_end", {}, ctx)).code, "not_dreaming");
60
58
  const newer = resultData(await call(captured, "dream_begin", {}, otherCtx));
61
59
  assert.equal(newer.project, other.projectKey, "another project can immediately begin after shutdown");
62
- const newerToken = readFileSync(lockPath, "utf8");
63
60
  release();
64
61
  assert.equal(resultError(await opening).code, "cancelled", "the stale opener cannot return success or resurrect state");
65
- assert.equal(readFileSync(lockPath, "utf8"), newerToken, "stale cleanup cannot release the newer owner's token");
62
+ assert.equal(resultError(await call(captured, "dream_begin", {}, ctx)).code, "already_dreaming", "stale cleanup cannot unlock the newer dream");
66
63
  assert.equal(resultError(await call(captured, "dream_end", {}, ctx)).code, "not_dreaming");
67
64
  resultData(await call(captured, "dream_end", {}, otherCtx));
68
- assert.equal(existsSync(lockPath), false);
69
65
  });
70
66
  }
71
67
  test("notes_list browses and searches recent-first snapshots", async () => {
@@ -28,7 +28,7 @@ function fixture(t) {
28
28
  return { root, home, repo, marker, identity };
29
29
  }
30
30
  // Each participant imports the real built module and operates on the same disk.
31
- // Optional pauses widen publication/snapshot windows without faking fs outcomes.
31
+ // Pause immediately before publication, with the real writer transaction held.
32
32
  const claimWorker = `
33
33
  import fs from "node:fs";
34
34
  import { syncBuiltinESMExports } from "node:module";
@@ -42,35 +42,25 @@ function wait(name) {
42
42
  Atomics.wait(sleep, 0, 0, 5);
43
43
  }
44
44
  }
45
- function paused() { fs.writeFileSync(join(control, "paused"), ""); wait("continue"); }
46
45
  if (pause) {
47
- const mkdir = fs.mkdirSync, readdir = fs.readdirSync, read = fs.readFileSync;
48
- fs.mkdirSync = function(path, ...args) {
49
- const result = mkdir(path, ...args);
50
- if (pause === "publication" && path === join(home, "project", "api")) paused();
51
- return result;
52
- };
53
- fs.readdirSync = function(path, ...args) {
54
- const result = readdir(path, ...args);
55
- if (pause === "snapshot" && path === join(home, "project") && args.length === 0) paused();
56
- return result;
57
- };
58
- fs.readFileSync = function(path, ...args) {
59
- try { return read(path, ...args); } catch (error) {
60
- if (path === join(home, "project", "api", ".project") && error.code === "ENOENT") fs.writeFileSync(join(control, "missing"), "");
61
- throw error;
46
+ const rename = fs.renameSync;
47
+ fs.renameSync = function(from, to) {
48
+ if (to === join(home, "project", "api")) {
49
+ fs.writeFileSync(join(control, "paused"), "");
50
+ wait("continue");
62
51
  }
52
+ return rename(from, to);
63
53
  };
64
54
  syncBuiltinESMExports();
65
55
  }
66
- const { projectKey } = await import(${JSON.stringify(new URL("../src/notes/project-namespace.js", import.meta.url).href)});
56
+ const { projectKey, createNotesStore } = await import(${JSON.stringify(new URL("../src/notes/index.js", import.meta.url).href)});
67
57
  fs.writeFileSync(join(control, "ready"), "");
68
58
  wait("start");
69
59
  const key = projectKey(cwd, home);
70
- const dir = join(home, "project", key);
71
- const probe = join(dir, "probe-" + process.pid);
72
- fs.writeFileSync(probe, "usable");
73
- console.log(JSON.stringify({ key, marker: JSON.parse(fs.readFileSync(join(dir, ".project"), "utf8")), probe: fs.readFileSync(probe, "utf8") }));
60
+ const notes = createNotesStore({ home, projectKey: key, sessionId: "session", agent: "test", model: "test" });
61
+ const probe = "@project/probe-" + process.pid;
62
+ await notes.write(probe, "usable");
63
+ console.log(JSON.stringify({ key, marker: JSON.parse(fs.readFileSync(join(home, "project", key, ".project"), "utf8")), probe: (await notes.read(probe)).body }));
74
64
  `;
75
65
  async function waitForFile(path) {
76
66
  const deadline = Date.now() + 10_000;
@@ -93,6 +83,7 @@ function racer(t, root, cwd, home, pause = "") {
93
83
  });
94
84
  return {
95
85
  result,
86
+ kill: () => child.kill("SIGKILL"),
96
87
  wait: (stage) => waitForFile(join(control, stage)),
97
88
  release: (stage) => writeFileSync(join(control, stage), ""),
98
89
  };
@@ -118,7 +109,6 @@ test("sixteen first claimants converge on one usable notebook for root and remot
118
109
  assert.equal(new Set(keys).size, 1);
119
110
  assert.deepEqual(readdirSync(join(home, "project")), [keys[0]]);
120
111
  assert.equal(marker(keys[0]).id, remote ? "host/team/api" : cwd);
121
- assert.equal(existsSync(join(home, ".project-claim")), false);
122
112
  });
123
113
  });
124
114
  test("different concurrent identities retain distinct suffixes", async (t) => {
@@ -134,72 +124,28 @@ test("different concurrent identities retain distinct suffixes", async (t) => {
134
124
  assert.deepEqual(results.map(result => JSON.parse(result.stdout).key).sort(), ["api", "api-1"]);
135
125
  assert.deepEqual(readdirSync(join(home, "project")).sort(), ["api", "api-1"]);
136
126
  });
137
- test("a claimant waits for another process between directory creation and marker publication", async (t) => {
127
+ test("a killed claimant releases its transaction without publishing a partial notebook", async (t) => {
138
128
  const { root, home, repo } = fixture(t);
139
129
  const cwd = repo("api");
140
- const first = racer(t, root, cwd, home, "publication");
141
- await first.wait("ready");
142
- first.release("start");
143
- await first.wait("paused");
144
- assert.equal(existsSync(join(home, "project/api/.project")), false);
145
- const second = racer(t, root, cwd, home);
146
- await second.wait("ready");
147
- second.release("start");
148
- await delay(100);
149
- assert.deepEqual(readdirSync(join(home, "project")), ["api"]);
150
- first.release("continue");
151
- for (const result of await Promise.all([first.result, second.result])) {
152
- assert.equal(result.code, 0, result.stderr);
153
- assert.equal(JSON.parse(result.stdout).key, "api");
154
- }
155
- });
156
- test("a directory appearing after the snapshot waits for its marker before adoption or suffixing", async (t) => {
157
- for (const same of [true, false])
158
- await t.test(same ? "adopt matching root as remote" : "suffix a different identity", async (t) => {
159
- const { root, home, repo, marker } = fixture(t);
160
- const cwd = repo("api", "https://host/team/api");
161
- const worker = racer(t, root, cwd, home, "snapshot");
162
- await worker.wait("ready");
163
- worker.release("start");
164
- await worker.wait("paused");
165
- mkdirSync(join(home, "project/api"));
166
- worker.release("continue");
167
- await worker.wait("missing");
168
- writeFileSync(join(home, "project/api/.project"), JSON.stringify({ id: same ? cwd : "host/other/api", path: "/old/root" }));
169
- const result = await worker.result;
170
- assert.equal(result.code, 0, result.stderr);
171
- const key = same ? "api" : "api-1";
172
- assert.equal(JSON.parse(result.stdout).key, key);
173
- assert.deepEqual(marker(key), { id: "host/team/api", path: cwd });
174
- if (!same)
175
- assert.deepEqual(marker("api"), { id: "host/other/api", path: "/old/root" });
176
- });
177
- });
178
- test("an unfinished claim times out without silently allocating another notebook", async (t) => {
179
- const { root, home, repo } = fixture(t);
180
- const worker = racer(t, root, repo("api"), home, "snapshot");
181
- await worker.wait("ready");
182
- worker.release("start");
183
- await worker.wait("paused");
184
- mkdirSync(join(home, "project/api"));
185
- worker.release("continue");
186
- const result = await worker.result;
187
- assert.notEqual(result.code, 0);
188
- assert.match(result.stderr, /Timed out waiting for project claim.*api/);
189
- assert.deepEqual(readdirSync(join(home, "project")), ["api"]);
190
- assert.equal(existsSync(join(home, ".project-claim")), false);
191
- });
192
- test("a stuck claim lock has a bounded timeout and is never stolen", async (t) => {
193
- const { root, home, repo } = fixture(t);
194
- mkdirSync(join(home, ".project-claim"), { recursive: true });
195
- const worker = racer(t, root, repo("api"), home);
196
- await worker.wait("ready");
197
- worker.release("start");
198
- const result = await worker.result;
199
- assert.notEqual(result.code, 0);
200
- assert.match(result.stderr, /Timed out waiting for project claim.*\.project-claim/);
201
- assert.deepEqual(readdirSync(join(home, "project")), []);
202
- assert.equal(existsSync(join(home, ".project-claim")), true);
130
+ const stable = repo("stable");
131
+ assert.equal(projectKey(stable, home), "stable");
132
+ const holder = racer(t, root, cwd, home, "publication");
133
+ await holder.wait("ready");
134
+ holder.release("start");
135
+ await holder.wait("paused");
136
+ // An unchanged identity needs no writer lock. Another claimant cannot steal it.
137
+ assert.equal(projectKey(stable, home), "stable");
138
+ assert.throws(() => projectKey(cwd, home), /Timed out waiting for project claim/);
139
+ assert.deepEqual(readdirSync(join(home, "project")), ["stable"]);
140
+ assert.ok(holder.kill());
141
+ assert.equal((await holder.result).code, null);
142
+ const next = racer(t, root, cwd, home);
143
+ await next.wait("ready");
144
+ next.release("start");
145
+ const result = await next.result;
146
+ assert.equal(result.code, 0, result.stderr);
147
+ assert.deepEqual(JSON.parse(result.stdout), { key: "api", marker: { id: cwd, path: cwd }, probe: "usable" });
148
+ assert.deepEqual(readdirSync(join(home, "project")).sort(), ["api", "stable"]);
203
149
  });
204
150
  test("malformed marker evidence refuses instead of becoming an unmarked legacy notebook", t => {
205
151
  const { home, repo } = fixture(t);
@@ -210,7 +156,6 @@ test("malformed marker evidence refuses instead of becoming an unmarked legacy n
210
156
  assert.throws(() => projectKey(cwd, home), /Invalid project marker.*api/);
211
157
  assert.equal(readFileSync(join(home, "project/api/.project"), "utf8"), raw);
212
158
  assert.deepEqual(readdirSync(join(home, "project")), ["api"]);
213
- assert.equal(existsSync(join(home, ".project-claim")), false);
214
159
  }
215
160
  });
216
161
  function data(result) {