@astrosheep/pi-context 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +22 -1
  2. package/dist/src/budget.js +10 -8
  3. package/dist/src/dream/cli.js +108 -24
  4. package/dist/src/dream/gates.js +13 -8
  5. package/dist/src/dream/git.js +71 -0
  6. package/dist/src/dream/lock.js +78 -37
  7. package/dist/src/dream/runner.js +90 -21
  8. package/dist/src/history-tools.js +5 -5
  9. package/dist/src/history.js +11 -6
  10. package/dist/src/index.js +14 -15
  11. package/dist/src/notes/address.js +31 -0
  12. package/dist/src/{memory → notes}/frontmatter.js +7 -5
  13. package/dist/src/{notes.js → notes/model.js} +1 -1
  14. package/dist/src/{memory → notes}/paths.js +7 -3
  15. package/dist/src/{memory → notes}/store.js +47 -74
  16. package/dist/src/notes/tools.js +153 -0
  17. package/dist/src/prompts.js +38 -29
  18. package/dist/src/protocol.js +9 -4
  19. package/dist/src/thresholds.js +33 -3
  20. package/dist/src/tool-output.js +4 -1
  21. package/dist/src/warning.js +3 -3
  22. package/dist/test/agent-loop.test.js +6 -4
  23. package/dist/test/coherence.test.js +5 -1
  24. package/dist/test/dream.test.js +419 -35
  25. package/dist/test/history.test.js +6 -1
  26. package/dist/test/integration.test.js +107 -47
  27. package/dist/test/{memory.test.js → notes.test.js} +154 -50
  28. package/dist/test/pagination.property.test.js +1 -1
  29. package/package.json +5 -5
  30. package/playbook.md +30 -3
  31. package/src/budget.ts +11 -9
  32. package/src/dream/cli.ts +95 -17
  33. package/src/dream/gates.ts +14 -7
  34. package/src/dream/git.ts +73 -0
  35. package/src/dream/lock.ts +67 -24
  36. package/src/dream/runner.ts +87 -20
  37. package/src/history-tools.ts +5 -5
  38. package/src/history.ts +12 -7
  39. package/src/index.ts +13 -14
  40. package/src/notes/address.ts +33 -0
  41. package/src/{memory → notes}/frontmatter.ts +7 -5
  42. package/src/{notes.ts → notes/model.ts} +2 -2
  43. package/src/{memory → notes}/paths.ts +8 -3
  44. package/src/{memory → notes}/store.ts +49 -79
  45. package/src/notes/tools.ts +132 -0
  46. package/src/prompts.ts +39 -29
  47. package/src/protocol.ts +9 -4
  48. package/src/thresholds.ts +38 -6
  49. package/src/tool-output.ts +4 -1
  50. package/src/warning.ts +3 -3
  51. package/dist/src/dream/apply.js +0 -87
  52. package/dist/src/dream/manifest.js +0 -16
  53. package/dist/src/memory/tools.js +0 -175
  54. package/src/dream/apply.ts +0 -47
  55. package/src/dream/manifest.ts +0 -21
  56. package/src/memory/tools.ts +0 -175
@@ -1,43 +1,427 @@
1
1
  import test from "node:test";
2
- import nodeAssert from "node:assert/strict";
3
- import { mkdtempSync, mkdirSync, readFileSync, readdirSync, statSync, utimesSync, writeFileSync, existsSync } from "node:fs";
2
+ import assert from "node:assert/strict";
3
+ import { execFile, execFileSync } from "node:child_process";
4
+ import { existsSync, linkSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
5
+ import { mkdtempSync } from "node:fs";
4
6
  import { tmpdir } from "node:os";
5
7
  import { join } from "node:path";
6
- import { spawnSync } from "node:child_process";
7
- import { defaultDreamerSessionFactory, runDreamer, READ_ONLY_TOOLS } from "../src/dream/runner.js";
8
- const cli = join(process.cwd(), "dist/src/dream/cli.js");
9
- const assert = nodeAssert;
10
- assert.match = (value, expected) => nodeAssert.ok(typeof expected === "string" ? value.includes(expected) : expected.test(value));
11
- function fixture() { const home = mkdtempSync(join(tmpdir(), "dream-")); mkdirSync(join(home, "pi/session"), { recursive: true }); return home; }
12
- function note(home, session, name, body, window) { const dir = join(home, "pi/session", session); mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, name), `---\nscope: session\norigin: self\nstatus: active\nsource_window: ${window}\ncreated_at: 2020-01-01T00:00:00.000Z\nupdated_at: 2020-01-01T00:00:00.000Z\nlast_accessed: 2020-01-01T00:00:00.000Z\naccess_count: 0\n---\n\n${body}`); }
13
- function dreamer(home, manifest, sentinel) { const file = join(home, "dreamer.mjs"); writeFileSync(file, `import {writeFileSync} from 'node:fs'; ${sentinel ? `writeFileSync(${JSON.stringify(sentinel)}, 'spawned');` : ""} process.stdin.resume(); process.stdin.on('end',()=>process.stdout.write(${JSON.stringify(JSON.stringify(manifest))}));`); return `node ${file}`; }
14
- function run(home, extra = []) { return spawnSync(process.execPath, [cli, "--notes-home", home, ...extra], { encoding: "utf8" }); }
8
+ import { acquireLock, failLock, lastRunPath, releaseLock } from "../src/dream/lock.js";
9
+ import { materialGate, timeGate } from "../src/dream/gates.js";
10
+ import { defaultDreamerSessionFactory, dreamerWriteToolDefinitions, runDreamer, DREAMER_TOOLS } from "../src/dream/runner.js";
11
+ import { gitCommit } from "../src/dream/git.js";
12
+ import { main } from "../src/dream/cli.js";
13
+ import { deriveDreamer, mergePiContextSettings, readDreamerSettings } from "../src/thresholds.js";
14
+ import { PI_CONTEXT_DREAMER_KEY, PI_CONTEXT_SETTINGS_KEY } from "../src/protocol.js";
15
+ import { contentText } from "../src/history.js";
16
+ function fixture() { return mkdtempSync(join(tmpdir(), "dream-")); }
15
17
  function old(path) { const d = new Date(Date.now() - 48 * 3600_000); utimesSync(path, d, d); }
16
- test("dream time gate skips first, names reason, and does not spawn", () => { const h = fixture(); const sentinel = join(h, "sentinel"); const lock = join(h, ".dream.lock"); writeFileSync(lock, "999999"); const fresh = new Date(); utimesSync(lock, fresh, fresh); const r = run(h, ["--dreamer", dreamer(h, { report: "x" }, sentinel)]); assert.equal(r.status, 0); assert.match(r.stdout, "time gate"); assert.equal(existsSync(sentinel), false); });
17
- test("material gate skips when too few session directories changed", () => { const h = fixture(); const lock = join(h, ".dream.lock"); writeFileSync(lock, "999999"); old(lock); note(h, "only", "a.md", "a", "w"); const r = run(h, ["--min-sessions", "3", "--dreamer", dreamer(h, { report: "x" })]); assert.equal(r.status, 0); assert.match(r.stdout, "material gate"); });
18
- test("force bypasses time and material gates and external dreamer runs", () => { const h = fixture(); const r = run(h, ["--force", "--dreamer", dreamer(h, { report: "forced" })]); assert.equal(r.status, 0); assert.match(readFileSync(readdirSync(join(h, "dreams")).map(x => join(h, "dreams", x))[0], "utf8"), "forced"); });
19
- test("live PID lock excludes and dead PID is reclaimed", () => { const h = fixture(); const lock = join(h, ".dream.lock"); writeFileSync(lock, String(process.pid)); const r = run(h, ["--force", "--dreamer", dreamer(h, { report: "no" })]); assert.equal(r.status, 0); assert.match(r.stdout, "lock gate"); writeFileSync(lock, "999999"); old(lock); const ok = run(h, ["--force", "--dreamer", dreamer(h, { report: "reclaimed" })]); assert.equal(ok.status, 0); });
20
- test("external dreamer manifest merges recurrence, proposes global promotion, trashes, and reports", () => { const h = fixture(); note(h, "dream", "a.md", "one", "window-a"); note(h, "dream", "b.md", "two", "window-b"); note(h, "dream", "trash.md", "gone", "window-c"); const m = { merge: [{ into: "a.md", from: ["b.md"] }], promote: [{ path: "a.md", to: "global", reason: "shared" }], trash: [{ path: "trash.md", reason: "obsolete" }], report: "I dreamed on 2026-09-19." }; const r = run(h, ["--force", "--dreamer", dreamer(h, m)]); assert.equal(r.status, 0, r.stderr); const merged = readFileSync(join(h, "pi/session/dream/a.md"), "utf8"); assert.match(merged, "one"); assert.match(merged, "two"); assert.match(merged, "recurrence_count: 1"); assert.match(readFileSync(join(h, "pi/session/dream/b.md"), "utf8"), "status: superseded"); assert.equal(existsSync(join(h, "pi/session/dream/trash.md")), false); const trash = readdirSync(join(h, "trash"))[0]; assert.equal(readFileSync(join(h, "trash", trash, "session", "trash.md"), "utf8").includes("gone"), true); const reports = readdirSync(join(h, "dreams")); const report = readFileSync(join(h, "dreams", reports[0]), "utf8"); assert.match(report, "I dreamed"); assert.match(report, "proposal: promote"); assert.match(report, "trashed"); });
21
- test("invalid manifest path makes zero writes and exits nonzero", () => { const h = fixture(); note(h, "s1", "a.md", "one", "w"); const before = readFileSync(join(h, "pi/session/s1/a.md"), "utf8"); const r = run(h, ["--force", "--dreamer", dreamer(h, { merge: [{ into: "missing.md", from: ["a.md"] }], report: "bad" })]); assert.notEqual(r.status, 0); assert.match(r.stderr, "missing.md"); assert.equal(readFileSync(join(h, "pi/session/s1/a.md"), "utf8"), before); assert.equal(existsSync(join(h, "dreams")), false); });
22
- test("failed run restores prior lock mtime", () => { const h = fixture(); const lock = join(h, ".dream.lock"); writeFileSync(lock, "999999"); const prior = Date.now() - 48 * 3600_000; utimesSync(lock, new Date(prior), new Date(prior)); const r = run(h, ["--force", "--dreamer", dreamer(h, { merge: [{ into: "missing", from: [] }], report: "x" })]); assert.notEqual(r.status, 0); assert.ok(Math.abs(statSync(lock).mtimeMs - prior) < 2000); });
23
- test("SDK dreamer captures assistant event and receives read-only allowlist", async () => {
18
+ /** A session whose prompt runs a scripted interaction with the recorded event handler. */
19
+ function scriptedSession(run) {
20
+ return async ({ cwd }) => {
21
+ let handler = () => { };
22
+ const session = {
23
+ subscribe(next) { handler = next; return () => { }; },
24
+ async prompt() { run(handler, cwd); },
25
+ dispose() { },
26
+ };
27
+ return session;
28
+ };
29
+ }
30
+ function successSession() {
31
+ return scriptedSession((handler) => handler({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "done" }] } }));
32
+ }
33
+ /** Capture console.error lines without letting CLI chatter pollute the test output. */
34
+ async function captureErrors(run) {
35
+ const errors = [];
36
+ const original = console.error;
37
+ console.error = (...parts) => { errors.push(parts.map(String).join(" ")); };
38
+ try {
39
+ return { code: await run(), errors };
40
+ }
41
+ finally {
42
+ console.error = original;
43
+ }
44
+ }
45
+ test("time and material gates preserve skip decisions and reasons", () => {
46
+ const home = fixture();
47
+ const lock = join(home, ".dream.lock");
48
+ const stamp = lastRunPath(lock);
49
+ assert.deepEqual(timeGate(stamp, 24).ok, true, "no prior dream passes");
50
+ writeFileSync(stamp, new Date().toISOString());
51
+ const fresh = timeGate(stamp, 24);
52
+ assert.equal(fresh.ok, false);
53
+ assert.equal(fresh.reason, "time gate: last dream is too recent");
54
+ old(stamp);
55
+ assert.equal(timeGate(stamp, 24).ok, true);
56
+ mkdirSync(join(home, "pi/session/one"), { recursive: true });
57
+ writeFileSync(join(home, "pi/session/one/a.md"), "a");
58
+ const material = materialGate(home, statSync(stamp).mtimeMs, 1);
59
+ assert.equal(material.ok, true);
60
+ assert.match(material.reason, /material gate: 1 changed sessions/);
61
+ assert.equal(materialGate(home, Date.now(), 2).ok, false);
62
+ // The lock file's own mtime no longer carries the scheduler timestamp.
63
+ writeFileSync(lock, "1");
64
+ old(lock);
65
+ assert.equal(timeGate(stamp, 24).ok, true, "the sidecar survives an old lock file");
66
+ });
67
+ test("failure restores the last-run timestamp and cleanup is idempotent", () => {
68
+ const home = fixture();
69
+ const lock = join(home, ".dream.lock");
70
+ const stamp = lastRunPath(lock);
71
+ writeFileSync(stamp, new Date(Date.now() - 48 * 3600_000).toISOString());
72
+ old(stamp);
73
+ const prior = statSync(stamp).mtimeMs;
74
+ const held = acquireLock(lock);
75
+ assert.equal(held.held, true);
76
+ assert.equal(readFileSync(lock, "utf8").trim(), `${process.pid} ${held.token}`, "the lock records its owner and token");
77
+ assert.ok(statSync(stamp).mtimeMs > prior + 1000, "a held lock advances the last-run sidecar, not itself");
78
+ failLock(held);
79
+ assert.equal(held.held, false, "failure marks the state released");
80
+ assert.ok(Math.abs(statSync(stamp).mtimeMs - prior) < 2000, "a failed run restores the last-run timestamp");
81
+ assert.equal(existsSync(lock), false, "a failed run releases its lock");
82
+ // Repeated cleanup on an already-released state is harmless.
83
+ const settled = statSync(stamp).mtimeMs;
84
+ failLock(held);
85
+ releaseLock(held);
86
+ assert.ok(Math.abs(statSync(stamp).mtimeMs - settled) < 1000, "repeated failure cleanup changes nothing");
87
+ const released = acquireLock(lock);
88
+ assert.equal(released.held, true);
89
+ releaseLock(released);
90
+ releaseLock(released);
91
+ assert.equal(released.held, false, "release marks the state released");
92
+ assert.equal(existsSync(lock), false, "release removes the PID marker");
93
+ assert.equal(existsSync(stamp), true, "the timestamp sidecar survives release");
94
+ });
95
+ test("any existing lock refuses acquisition and is left byte-identical", () => {
96
+ const home = fixture();
97
+ const lock = join(home, ".dream.lock");
98
+ const stamp = lastRunPath(lock);
99
+ const markers = [
100
+ `${process.pid} live-owner`, // a live owner's marker
101
+ "999999", // a dead PID
102
+ "999999 dead-token", // a dead PID with a token
103
+ "", // empty
104
+ "not-a-pid", // malformed
105
+ ];
106
+ for (const marker of markers) {
107
+ writeFileSync(lock, marker);
108
+ old(lock);
109
+ const result = acquireLock(lock);
110
+ assert.equal(result.held, false, `refuses an existing marker ${JSON.stringify(marker)}`);
111
+ assert.equal(result.reason, "lock gate: lock already exists");
112
+ assert.equal(readFileSync(lock, "utf8"), marker, "the existing marker is byte-identical");
113
+ }
114
+ assert.equal(existsSync(stamp), false, "a refused acquisition writes no timestamp");
115
+ });
116
+ test("an acquired lock blocks every later contender until released", () => {
117
+ const home = fixture();
118
+ const lock = join(home, ".dream.lock");
119
+ const first = acquireLock(lock);
120
+ assert.equal(first.held, true);
121
+ const second = acquireLock(lock);
122
+ assert.equal(second.held, false);
123
+ assert.equal(second.reason, "lock gate: lock already exists");
124
+ assert.equal(readFileSync(lock, "utf8").trim(), `${process.pid} ${first.token}`, "the holder's marker is untouched");
125
+ });
126
+ test("cleanup never removes a successor's lock, even repeated", () => {
127
+ const home = fixture();
128
+ const lock = join(home, ".dream.lock");
129
+ const stamp = lastRunPath(lock);
130
+ const mine = acquireLock(lock);
131
+ assert.equal(mine.held, true);
132
+ // A successor acquires after ours is externally gone (human/supported protocol).
133
+ unlinkSync(lock);
134
+ const successor = acquireLock(lock);
135
+ assert.equal(successor.held, true);
136
+ const successorStamp = Date.now() - 5000;
137
+ utimesSync(stamp, new Date(), new Date(successorStamp));
138
+ failLock(mine);
139
+ releaseLock(mine);
140
+ assert.equal(mine.held, false, "the old state is marked released by the first cleanup");
141
+ assert.equal(readFileSync(lock, "utf8").trim(), `${process.pid} ${successor.token}`, "the successor's lock survives");
142
+ assert.ok(Math.abs(statSync(stamp).mtimeMs - successorStamp) < 1000, "the successor's timestamp survives");
143
+ });
144
+ /** Each child makes one actual acquisition attempt; a holder stays alive so later attempts see it. */
145
+ async function acquireRaceOutcomes(lock, contenders) {
146
+ const moduleUrl = new URL("../src/dream/lock.js", import.meta.url).href;
147
+ const script = [
148
+ `import { acquireLock, releaseLock } from ${JSON.stringify(moduleUrl)};`,
149
+ `const result = acquireLock(${JSON.stringify(lock)});`,
150
+ `if (result.held) await new Promise((resolve) => setTimeout(resolve, 1200));`,
151
+ `process.stdout.write(result.held ? "held" : "lost");`,
152
+ `if (result.held) releaseLock(result);`,
153
+ ].join("\n");
154
+ const contender = () => new Promise((resolve, reject) => {
155
+ execFile(process.execPath, ["--input-type=module", "-e", script], (error, stdout) => error ? reject(error) : resolve(stdout.trim()));
156
+ });
157
+ return Promise.all(Array.from({ length: contenders }, contender));
158
+ }
159
+ test("concurrent acquisitions of an absent lock yield exactly one held:true", async () => {
160
+ const home = fixture();
161
+ const lock = join(home, ".dream.lock");
162
+ assert.equal(existsSync(lock), false, "the lock starts absent");
163
+ const outcomes = await acquireRaceOutcomes(lock, 8);
164
+ assert.equal(outcomes.filter((outcome) => outcome === "held").length, 1, "exactly one actual held:true return");
165
+ });
166
+ test("dreamer write jail accepts home files and refuses escapes", async () => {
167
+ const home = fixture();
168
+ const tools = new Map(dreamerWriteToolDefinitions(home).map((tool) => [tool.name, tool]));
169
+ const ctx = { cwd: home };
170
+ await tools.get("write").execute("write", { path: "global/x.md", content: "one" }, undefined, undefined, ctx);
171
+ assert.equal(readFileSync(join(home, "global/x.md"), "utf8"), "one");
172
+ const rejectsOutsideHome = async (tool, path) => {
173
+ const params = tool === "write" ? { path, content: "outside" } : { path, edits: [{ oldText: "one", newText: "outside" }] };
174
+ await assert.rejects(() => tools.get(tool).execute("escape", params, undefined, undefined, ctx), (error) => error.message.includes(home));
175
+ };
176
+ for (const tool of ["write", "edit"]) {
177
+ await rejectsOutsideHome(tool, "/tmp/dream-jail-outside.md");
178
+ await rejectsOutsideHome(tool, "../dream-jail-outside.md");
179
+ }
180
+ const outside = fixture();
181
+ symlinkSync(outside, join(home, "escape"));
182
+ await rejectsOutsideHome("write", "escape/outside.md");
183
+ await rejectsOutsideHome("edit", "escape/outside.md");
184
+ assert.equal(existsSync(join(outside, "outside.md")), false, "the jail does not write through an in-home symlink");
185
+ const outsideFile = join(outside, "outside.md");
186
+ writeFileSync(outsideFile, "outside");
187
+ symlinkSync(outsideFile, join(home, "global/outside-link.md"));
188
+ await rejectsOutsideHome("write", "global/outside-link.md");
189
+ assert.equal(readFileSync(outsideFile, "utf8"), "outside", "the jail does not write through a symlinked file outside home");
190
+ linkSync(outsideFile, join(home, "global/hardlink.md"));
191
+ await rejectsOutsideHome("write", "global/hardlink.md");
192
+ assert.equal(readFileSync(outsideFile, "utf8"), "outside", "the jail does not write through a hardlinked file outside home");
193
+ const insideFile = join(home, "global/inside.md");
194
+ writeFileSync(insideFile, "inside");
195
+ symlinkSync(insideFile, join(home, "global/inside-link.md"));
196
+ await tools.get("write").execute("write", { path: "global/inside-link.md", content: "updated" }, undefined, undefined, ctx);
197
+ assert.equal(readFileSync(insideFile, "utf8"), "updated", "the jail permits a symlinked file that resolves inside home");
198
+ // The jail has no `.git` special case: an in-home `.git` path is written like any other.
199
+ await tools.get("write").execute("write", { path: ".git/config", content: "not protected" }, undefined, undefined, ctx);
200
+ assert.equal(readFileSync(join(home, ".git/config"), "utf8"), "not protected", "the dream write jail does not protect .git");
201
+ });
202
+ test("dreamer allowlist contains only the file tools and reports their writes", async () => {
24
203
  let configured = [];
25
- const session = { subscribe(handler) { this.handler = handler; return () => { }; }, handler: (_event) => { }, async prompt(_text) { this.handler({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: '{"report":"stub"}' }] } }); }, dispose() { } };
26
- const manifest = await runDreamer("playbook", "/tmp/notes", { sessionFactory: async (options) => { configured = options.tools; return session; } });
27
- assert.deepEqual(manifest, { report: "stub" });
28
- assert.deepEqual(configured, READ_ONLY_TOOLS);
29
- assert.equal(configured.includes("notes_write"), false);
30
- assert.equal(configured.includes("notes_edit"), false);
31
- });
32
- test("SDK dreamer surfaces provider stopReason error instead of manifest-parse lie", async () => {
33
- const session = { subscribe(handler) { this.handler = handler; return () => { }; }, handler: (_event) => { }, async prompt(_text) { this.handler({ type: "message_end", message: { role: "assistant", content: [], stopReason: "error", errorMessage: "402: {\"error\":{\"message\":\"Insufficient Balance\"}}" } }); }, dispose() { } };
34
- await assert.rejects(() => runDreamer("playbook", "/tmp/notes", { sessionFactory: async () => session }), /Insufficient Balance/);
35
- await assert.rejects(() => runDreamer("playbook", "/tmp/notes", { sessionFactory: async () => session }), /402/);
36
- });
37
- test("SDK dreamer parse failure keeps existing manifest message without provider error", async () => {
38
- const session = { subscribe(handler) { this.handler = handler; return () => { }; }, handler: (_event) => { }, async prompt(_text) { this.handler({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "sorry, I could not do that" }] } }); }, dispose() { } };
39
- await assert.rejects(() => runDreamer("playbook", "/tmp/notes", { sessionFactory: async () => session }), /did not return a valid JSON manifest/);
204
+ const session = {
205
+ subscribe(handler) { this.handler = handler; return () => { }; },
206
+ handler: (_event) => { },
207
+ async prompt(_text) { this.handler({ type: "tool_execution_start", toolName: "write", args: { path: "global/a.md", content: "a" } }); this.handler({ type: "tool_execution_start", toolName: "edit", args: { path: "project/p.md", edits: [] } }); this.handler({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "done" }, { type: "text", text: "again" }] } }); },
208
+ dispose() { },
209
+ };
210
+ const result = await runDreamer("playbook", "/tmp/notes", { sessionFactory: async (options) => { configured = options.tools; return session; } });
211
+ assert.deepEqual(configured, DREAMER_TOOLS);
212
+ assert.deepEqual(configured, ["read", "grep", "find", "ls", "write", "edit"]);
213
+ assert.equal(configured.some((tool) => tool.startsWith("notes_")), false);
214
+ assert.deepEqual(result.writes, [{ tool: "write", path: "global/a.md" }, { tool: "edit", path: "project/p.md" }]);
215
+ assert.equal(result.report, "done\nagain");
216
+ assert.equal(result.report, contentText([{ type: "text", text: "done" }, { type: "text", text: "again" }]), "dream and history share the text projection");
217
+ assert.equal(result.error, undefined);
218
+ });
219
+ test("dreamer session has exactly the jailed file-tool allowlist", async () => {
220
+ const session = await defaultDreamerSessionFactory({ cwd: fixture(), tools: DREAMER_TOOLS });
221
+ try {
222
+ assert.deepEqual(session.agent.state.tools.map((tool) => tool.name).sort(), [...DREAMER_TOOLS].sort());
223
+ }
224
+ finally {
225
+ session.dispose();
226
+ }
227
+ });
228
+ test("playbook describes plain files and the retained frontmatter", () => {
229
+ const playbook = readFileSync(join(process.cwd(), "playbook.md"), "utf8");
230
+ assert.equal(playbook.includes("notes_"), false);
231
+ for (const field of ["origin", "status", "stale", "created_at", "updated_at", "last_accessed", "access_count"])
232
+ assert.match(playbook, new RegExp(`^${field}:`, "m"));
233
+ assert.equal(/^scope:/m.test(playbook), false, "scope is derived from the address rather than persisted");
234
+ assert.match(playbook, /Nothing is physically deleted/);
235
+ });
236
+ test("provider errors are reported with partial writes instead of parsing a response", async () => {
237
+ const factory = scriptedSession((handler) => {
238
+ handler({ type: "tool_execution_start", toolName: "write", args: { path: "global/partial.md", content: "half" } });
239
+ handler({ type: "message_end", message: { role: "assistant", stopReason: "error", errorMessage: "Insufficient Balance" } });
240
+ });
241
+ const result = await runDreamer("playbook", "/tmp/notes", { sessionFactory: factory });
242
+ assert.match(result.error ?? "", /Insufficient Balance/);
243
+ assert.deepEqual(result.writes, [{ tool: "write", path: "global/partial.md" }]);
40
244
  });
41
245
  test("default dreamer rejects an unresolvable model pattern", async () => {
42
- await assert.rejects(() => defaultDreamerSessionFactory({ cwd: "/tmp/notes", modelPattern: "definitely-not-a-real-model", tools: READ_ONLY_TOOLS }), /definitely-not-a-real-model/);
246
+ await assert.rejects(() => defaultDreamerSessionFactory({ cwd: "/tmp/notes", modelPattern: "definitely-not-a-real-model", tools: DREAMER_TOOLS }), /definitely-not-a-real-model/);
247
+ });
248
+ test("git audit layer commits baseline and dream, stays silent when clean, keeps file content", () => {
249
+ const home = fixture();
250
+ writeFileSync(join(home, "a.md"), "one");
251
+ const baseline = gitCommit(home, "baseline t");
252
+ assert.equal(baseline.ok, true);
253
+ const clean = gitCommit(home, "dream t"); // clean tree — no empty commit
254
+ assert.equal(clean.ok, true);
255
+ assert.equal(clean.empty, true);
256
+ const log1 = execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim();
257
+ assert.equal(log1, "baseline t");
258
+ writeFileSync(join(home, "a.md"), "two");
259
+ const second = gitCommit(home, "dream t2");
260
+ assert.equal(second.ok, true);
261
+ assert.equal(second.empty, false);
262
+ const log2 = execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim();
263
+ assert.equal(log2, "dream t2\nbaseline t");
264
+ assert.equal(readFileSync(join(home, "a.md"), "utf8"), "two"); // notes themselves untouched by the layer
265
+ const before = execFileSync("git", ["show", "HEAD~1:a.md"], { cwd: home, encoding: "utf8" }).trim();
266
+ assert.equal(before, "one"); // rollback information actually recorded
267
+ });
268
+ test("git audit layer gives a newly initialized empty repository a real baseline snapshot", () => {
269
+ const home = fixture();
270
+ const baseline = gitCommit(home, "baseline empty");
271
+ assert.equal(baseline.ok, true);
272
+ if (baseline.ok) {
273
+ assert.notEqual(baseline.commit, "", "the baseline carries a real commit, not an empty marker");
274
+ assert.equal(baseline.empty, true, "no files changed");
275
+ }
276
+ assert.equal(execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim(), "baseline empty");
277
+ });
278
+ test("git audit layer reports its failure instead of swallowing it", () => {
279
+ const missing = gitCommit(join(fixture(), "missing", "home"), "x");
280
+ assert.equal(missing.ok, false);
281
+ const broken = fixture();
282
+ writeFileSync(join(broken, ".git"), "not a git directory");
283
+ const result = gitCommit(broken, "x");
284
+ assert.equal(result.ok, false);
285
+ if (!result.ok)
286
+ assert.ok(result.error.length > 0, "the audit failure names its cause");
287
+ });
288
+ test("CLI: a failed final audit is recorded in the report and in the exit status", async () => {
289
+ const home = fixture();
290
+ const sessionFactory = scriptedSession((_handler, cwd) => {
291
+ mkdirSync(join(cwd, "global"), { recursive: true });
292
+ writeFileSync(join(cwd, "global/ok.md"), "ok");
293
+ // Break the repository after the baseline so only the final audit fails.
294
+ rmSync(join(cwd, ".git"), { recursive: true, force: true });
295
+ writeFileSync(join(cwd, ".git"), "broken");
296
+ });
297
+ const { code, errors } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory, dreamerSettings: () => ({ warnings: [] }) }));
298
+ assert.notEqual(code, 0, "a dream with no final snapshot is not a success");
299
+ assert.ok(errors.some((line) => /final audit failed/.test(line)), "the audit failure is named");
300
+ const reports = readdirSync(join(home, "dreams"));
301
+ assert.equal(reports.length, 1);
302
+ assert.match(readFileSync(join(home, "dreams", reports[0]), "utf8"), /Final audit failed/, "the success report records the audit failure");
303
+ });
304
+ test("CLI: a report-write failure does not prevent the final failure audit", async () => {
305
+ const home = fixture();
306
+ writeFileSync(join(home, "dreams"), "not a directory");
307
+ const sessionFactory = scriptedSession((handler, cwd) => {
308
+ mkdirSync(join(cwd, "global"), { recursive: true });
309
+ writeFileSync(join(cwd, "global/partial.md"), "half");
310
+ handler({ type: "tool_execution_start", toolName: "write", args: { path: "global/partial.md", content: "half" } });
311
+ handler({ type: "message_end", message: { role: "assistant", stopReason: "error", errorMessage: "Insufficient Balance" } });
312
+ });
313
+ const { code, errors } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory, dreamerSettings: () => ({ warnings: [] }) }));
314
+ assert.notEqual(code, 0);
315
+ assert.ok(errors.some((line) => /could not write report/.test(line)), "the report failure is surfaced");
316
+ assert.match(execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim(), /\(failed\)/, "the final failure audit still ran");
317
+ assert.equal(execFileSync("git", ["show", "HEAD:global/partial.md"], { cwd: home, encoding: "utf8" }), "half", "the partial write is still committed");
318
+ });
319
+ test("CLI: an unwritable report is a failure even when the dreamer succeeds", async () => {
320
+ const home = fixture();
321
+ writeFileSync(join(home, "dreams"), "not a directory");
322
+ const { code, errors } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory: successSession(), dreamerSettings: () => ({ warnings: [] }) }));
323
+ assert.notEqual(code, 0, "a missing report is not a success");
324
+ assert.ok(errors.some((line) => /could not write report/.test(line)), "the report failure is surfaced");
325
+ assert.notEqual(execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim(), "", "the final audit still ran");
326
+ });
327
+ test("CLI: a failed baseline audit aborts before the dreamer and preserves the notes bytes", async () => {
328
+ const home = fixture();
329
+ writeFileSync(join(home, "keep.md"), "keep me");
330
+ writeFileSync(join(home, ".git"), "not a git directory"); // every git command fails
331
+ let started = false;
332
+ const { code } = await captureErrors(() => main(["--notes-home", home, "--force"], {
333
+ sessionFactory: async () => { started = true; return {}; },
334
+ dreamerSettings: () => ({ warnings: [] }),
335
+ }));
336
+ assert.notEqual(code, 0, "a missing baseline is a failed run");
337
+ assert.equal(started, false, "the dreamer never starts without a baseline");
338
+ assert.equal(readFileSync(join(home, "keep.md"), "utf8"), "keep me", "the notes bytes survive");
339
+ assert.equal(existsSync(join(home, "dreams")), false, "no dream report is written");
340
+ });
341
+ test("CLI: a dreamer failure records the failure and the partial write in a final commit", async () => {
342
+ const home = fixture();
343
+ const sessionFactory = scriptedSession((handler, cwd) => {
344
+ mkdirSync(join(cwd, "global"), { recursive: true });
345
+ writeFileSync(join(cwd, "global/partial.md"), "half");
346
+ handler({ type: "tool_execution_start", toolName: "write", args: { path: "global/partial.md", content: "half" } });
347
+ handler({ type: "message_end", message: { role: "assistant", stopReason: "error", errorMessage: "Insufficient Balance" } });
348
+ });
349
+ const { code } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory, dreamerSettings: () => ({ warnings: [] }) }));
350
+ assert.notEqual(code, 0);
351
+ const reports = readdirSync(join(home, "dreams"));
352
+ assert.equal(reports.length, 1, "one failure report");
353
+ const report = readFileSync(join(home, "dreams", reports[0]), "utf8");
354
+ assert.match(report, /Insufficient Balance/, "the report contains the failure");
355
+ assert.match(report, /global\/partial\.md/, "the report names the partial write");
356
+ const log = execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim();
357
+ assert.match(log, /\(failed\)/, "the partial state is committed as a failure");
358
+ assert.equal(execFileSync("git", ["show", "HEAD:global/partial.md"], { cwd: home, encoding: "utf8" }), "half");
359
+ });
360
+ test("CLI: a successful run commits its report and leaves the audited tree clean", async () => {
361
+ const home = fixture();
362
+ writeFileSync(join(home, "seed.md"), "seed");
363
+ const { code } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory: successSession(), dreamerSettings: () => ({ warnings: [] }) }));
364
+ assert.equal(code, 0);
365
+ assert.equal(execFileSync("git", ["status", "--porcelain"], { cwd: home, encoding: "utf8" }).trim(), "", "the audited tree is clean after the lock is released");
366
+ const tracked = execFileSync("git", ["ls-files"], { cwd: home, encoding: "utf8" }).trim().split("\n");
367
+ assert.equal(tracked.some((file) => file.startsWith(".dream.lock")), false, "lock artifacts stay out of the snapshot");
368
+ assert.equal(tracked.includes("seed.md"), true);
369
+ });
370
+ test("CLI: --force does not bypass an existing lock", async () => {
371
+ const home = fixture();
372
+ writeFileSync(join(home, ".dream.lock"), "999999 dead-owner");
373
+ let started = false;
374
+ const { code } = await captureErrors(() => main(["--notes-home", home, "--force"], {
375
+ sessionFactory: async () => { started = true; return {}; },
376
+ dreamerSettings: () => ({ warnings: [] }),
377
+ }));
378
+ assert.equal(code, 0, "an existing lock skips the run rather than failing");
379
+ assert.equal(started, false, "--force never reaches the dreamer while the lock exists");
380
+ assert.equal(readFileSync(join(home, ".dream.lock"), "utf8"), "999999 dead-owner", "the existing lock is byte-identical");
381
+ assert.equal(existsSync(join(home, "dreams")), false, "no dream report is written");
382
+ });
383
+ test("dreamer setting is a non-empty string; project overrides global; invalid values warn and fall back", () => {
384
+ assert.deepEqual(deriveDreamer({}), { warnings: [] }, "absent setting falls back silently");
385
+ assert.deepEqual(deriveDreamer({ dreamer: "openai/gpt-x" }), { pattern: "openai/gpt-x", warnings: [] });
386
+ const merged = mergePiContextSettings({ [PI_CONTEXT_SETTINGS_KEY]: { [PI_CONTEXT_DREAMER_KEY]: "global/model" } }, { [PI_CONTEXT_SETTINGS_KEY]: { [PI_CONTEXT_DREAMER_KEY]: "project/model" } });
387
+ assert.equal(deriveDreamer(merged).pattern, "project/model", "project wins per key");
388
+ for (const invalid of ["", " ", 42, null]) {
389
+ const result = deriveDreamer({ dreamer: invalid });
390
+ assert.equal(result.pattern, undefined, `invalid ${JSON.stringify(invalid)} is ignored`);
391
+ assert.equal(result.warnings.length, 1, "one warning per invalid value");
392
+ assert.match(result.warnings[0], /dreamer/);
393
+ }
394
+ });
395
+ test("readDreamerSettings reads the project setting over the global one through SettingsManager", () => {
396
+ const cwd = mkdtempSync(join(tmpdir(), "dream-cwd-"));
397
+ const agentDir = mkdtempSync(join(tmpdir(), "dream-agent-"));
398
+ const prior = process.env.PI_CODING_AGENT_DIR;
399
+ process.env.PI_CODING_AGENT_DIR = agentDir;
400
+ try {
401
+ writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ [PI_CONTEXT_SETTINGS_KEY]: { [PI_CONTEXT_DREAMER_KEY]: "global/model" } }));
402
+ mkdirSync(join(cwd, ".pi"), { recursive: true });
403
+ writeFileSync(join(cwd, ".pi", "settings.json"), JSON.stringify({ [PI_CONTEXT_SETTINGS_KEY]: { [PI_CONTEXT_DREAMER_KEY]: "project/model" } }));
404
+ assert.equal(readDreamerSettings(cwd).pattern, "project/model");
405
+ writeFileSync(join(cwd, ".pi", "settings.json"), JSON.stringify({}));
406
+ assert.equal(readDreamerSettings(cwd).pattern, "global/model", "global applies when the project does not set the key");
407
+ }
408
+ finally {
409
+ if (prior === undefined)
410
+ delete process.env.PI_CODING_AGENT_DIR;
411
+ else
412
+ process.env.PI_CODING_AGENT_DIR = prior;
413
+ }
414
+ });
415
+ test("CLI: --dreamer wins over settings, settings win over the automatic fallback", async () => {
416
+ const home = fixture();
417
+ const seen = [];
418
+ const success = successSession();
419
+ const run = (argv, settings) => main(["--notes-home", home, "--force", ...argv], {
420
+ sessionFactory: async (options) => { seen.push(options.modelPattern); return success({ cwd: home, tools: DREAMER_TOOLS }); },
421
+ dreamerSettings: () => settings,
422
+ });
423
+ await captureErrors(() => run([], { pattern: "settings/model", warnings: [] }));
424
+ await captureErrors(() => run(["--dreamer", "cli/model"], { pattern: "settings/model", warnings: [] }));
425
+ await captureErrors(() => run([], { warnings: [] }));
426
+ assert.deepEqual(seen, ["settings/model", "cli/model", undefined]);
43
427
  });
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { resetV2WindowId, visibleItem } from "../src/history.js";
3
+ import { contentText, resetV2WindowId, rootWindowId, visibleItem } from "../src/history.js";
4
4
  test("visibleItem reports a plain fitting prefix and names the full length", () => {
5
5
  const item = visibleItem({ windowId: "w", itemId: "i", role: "user", content: "abcdef", createdAt: undefined }, 4);
6
6
  assert.equal(Array.from(item.truncated_content).length, 4);
@@ -19,3 +19,8 @@ test("persisted reset IDs are opaque within the supported protocol version", ()
19
19
  assert.equal(resetV2WindowId({ piContext: "reset-v2", windowId: 123 }), undefined);
20
20
  assert.equal(resetV2WindowId(null), undefined);
21
21
  });
22
+ test("text content projection and root window IDs have stable shared forms", () => {
23
+ const content = [{ type: "text", text: "first" }, { type: "toolCall", name: "ignored" }, { type: "text", text: "second" }];
24
+ assert.equal(contentText(content), "first\nsecond");
25
+ assert.equal(rootWindowId("12345678-abcd"), "pcw:12345678:root");
26
+ });