notesoup 0.51.9 → 0.52.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.
Files changed (72) hide show
  1. package/README.md +3 -10
  2. package/dist/plugins/claude/src/history.js +3 -7
  3. package/dist/plugins/pi/notes/tools.d.ts +1 -1
  4. package/dist/plugins/pi/notes/tools.js +26 -7
  5. package/dist/plugins/pi/tool-result.d.ts +3 -2
  6. package/dist/plugins/pi/tool-result.js +3 -1
  7. package/dist/src/dream/git.d.ts +2 -3
  8. package/dist/src/dream/git.js +3 -8
  9. package/dist/src/dream/lock.d.ts +10 -27
  10. package/dist/src/dream/lock.js +16 -79
  11. package/dist/src/notes/errors.d.ts +1 -1
  12. package/dist/src/notes/identity.d.ts +2 -0
  13. package/dist/src/notes/identity.js +3 -1
  14. package/dist/src/notes/store.d.ts +2 -0
  15. package/dist/src/notes/store.js +40 -4
  16. package/dist/src/tools/dream.d.ts +113 -0
  17. package/dist/src/tools/dream.js +112 -0
  18. package/dist/src/tools/notes.d.ts +15 -1
  19. package/dist/src/tools/notes.js +4 -4
  20. package/dist/test/claude-history.test.js +18 -2
  21. package/dist/test/claude-mod.test.js +115 -30
  22. package/dist/test/dependencies.test.js +3 -6
  23. package/dist/test/dream-skill.test.js +2 -3
  24. package/dist/test/dream-tools.test.js +67 -0
  25. package/docs/claude-code-mod.md +1 -1
  26. package/docs/notes-library.md +1 -1
  27. package/docs/skills.md +12 -15
  28. package/package.json +2 -5
  29. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  30. package/plugins/claude/dist/claude/helper.js +30 -22
  31. package/plugins/claude/hooks/register.ts +52 -33
  32. package/plugins/claude/src/history.ts +3 -6
  33. package/plugins/pi/notes/tools.ts +25 -8
  34. package/plugins/pi/tool-result.ts +4 -1
  35. package/src/dream/git.ts +3 -8
  36. package/src/dream/lock.ts +18 -66
  37. package/src/notes/errors.ts +1 -1
  38. package/src/notes/identity.ts +4 -1
  39. package/src/notes/store.ts +37 -4
  40. package/src/tools/dream.ts +112 -0
  41. package/src/tools/notes.ts +4 -4
  42. package/dist/plugins/pi/dream/cli.d.ts +0 -10
  43. package/dist/plugins/pi/dream/cli.js +0 -173
  44. package/dist/plugins/pi/dream/runner.d.ts +0 -27
  45. package/dist/plugins/pi/dream/runner.js +0 -91
  46. package/dist/plugins/pi/dream/settings.d.ts +0 -7
  47. package/dist/plugins/pi/dream/settings.js +0 -17
  48. package/dist/src/dream/doctor.d.ts +0 -2
  49. package/dist/src/dream/doctor.js +0 -161
  50. package/dist/src/dream/gates.d.ts +0 -10
  51. package/dist/src/dream/gates.js +0 -26
  52. package/dist/src/dream/jail.d.ts +0 -11
  53. package/dist/src/dream/jail.js +0 -71
  54. package/dist/src/dream/report.d.ts +0 -7
  55. package/dist/src/dream/report.js +0 -34
  56. package/dist/src/dream/result.d.ts +0 -9
  57. package/dist/src/dream/settings.d.ts +0 -9
  58. package/dist/src/dream/settings.js +0 -16
  59. package/dist/test/doctor.test.d.ts +0 -1
  60. package/dist/test/doctor.test.js +0 -37
  61. package/dist/test/dream.test.d.ts +0 -1
  62. package/dist/test/dream.test.js +0 -150
  63. package/plugins/pi/dream/cli.ts +0 -118
  64. package/plugins/pi/dream/runner.ts +0 -92
  65. package/plugins/pi/dream/settings.ts +0 -17
  66. package/src/dream/doctor.ts +0 -118
  67. package/src/dream/gates.ts +0 -26
  68. package/src/dream/jail.ts +0 -62
  69. package/src/dream/report.ts +0 -32
  70. package/src/dream/result.ts +0 -2
  71. package/src/dream/settings.ts +0 -19
  72. /package/dist/{src/dream/result.js → test/dream-tools.test.d.ts} +0 -0
@@ -1,161 +0,0 @@
1
- import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
2
- import { basename, join, relative } from "node:path";
3
- import { ADDRESS_FORMS, assertAddress } from "../notes/address.js";
4
- import { SLUG_PATTERN } from "../notes/paths.js";
5
- import { errorMessage } from "../error-message.js";
6
- /** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
7
- export function doctor(home) {
8
- const issues = [];
9
- const report = (path, message) => issues.push(`${relative(home, path) || "."}: ${message}`);
10
- const inspect = (path, action) => {
11
- try {
12
- action();
13
- }
14
- catch (error) {
15
- report(path, `cannot inspect: ${errorMessage(error)}`);
16
- }
17
- };
18
- const directory = (path) => {
19
- const stat = lstatSync(path);
20
- if (stat.isDirectory())
21
- return true;
22
- report(path, "expected a directory (symlinks are not followed); check its location/type");
23
- return false;
24
- };
25
- const checkNote = (path, root, project) => {
26
- const raw = readFileSync(path, "utf8");
27
- const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(raw);
28
- if (!match) {
29
- report(path, "missing or unclosed frontmatter; add a valid metadata block");
30
- return;
31
- }
32
- const fields = new Map();
33
- for (const line of match[1].split(/\r?\n/)) {
34
- const field = /^([\w]+):\s*(.*?)\s*$/.exec(line);
35
- if (!field)
36
- continue;
37
- if (fields.has(field[1]))
38
- report(path, `duplicate metadata key ${field[1]}; keep one value`);
39
- fields.set(field[1], field[2].replace(/^(["'])(.*)\1$/, "$2"));
40
- }
41
- for (const [key, valid] of Object.entries({ origin: /^(user|self|external)$/, accessCount: /^\d+$/ })) {
42
- if (!valid.test(fields.get(key) ?? ""))
43
- report(path, `missing/invalid ${key}; repair frontmatter`);
44
- }
45
- for (const key of ["createdAt", "updatedAt", "lastAccessed", "crumpledAt"]) {
46
- if (key === "crumpledAt" && !fields.has(key))
47
- continue;
48
- const value = fields.get(key);
49
- if (!value || !Number.isFinite(Date.parse(value)))
50
- report(path, `missing/invalid ${key}; use an ISO timestamp`);
51
- }
52
- if (fields.has("scope"))
53
- report(path, "obsolete scope field; remove it (home determines scope)");
54
- // Check concrete, code-formatted addresses; examples/globs and prose are not links.
55
- for (const link of raw.slice(match[0].length).matchAll(/`([^`\n]+)`/g)) {
56
- const address = link[1];
57
- if (!address.endsWith(".md") || /[<>*?\s]/.test(address))
58
- continue;
59
- if (!address.startsWith("@") && basename(path) !== "MAP.md")
60
- continue;
61
- try {
62
- const parsed = assertAddress(address);
63
- // Relative homes (@self/, @model/) name whoever is running; a static doctor
64
- // cannot resolve them, so only absolute links are checked.
65
- if ((parsed.scope === "agent" || parsed.scope === "model") && parsed.who === undefined)
66
- continue;
67
- const targetHome = parsed.scope === "human" ? join(home, "human")
68
- : parsed.scope === "project" ? project
69
- : parsed.scope === "agent" ? join(home, "agents", parsed.who)
70
- : parsed.scope === "model" ? join(home, "models", parsed.who)
71
- : root;
72
- if (!targetHome) {
73
- report(path, `${address}: project context unavailable; use a resolvable reference`);
74
- continue;
75
- }
76
- if (!existsSync(join(targetHome, parsed.path)))
77
- report(path, `${address}: target missing; update or remove the reference`);
78
- }
79
- catch {
80
- report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`);
81
- }
82
- }
83
- };
84
- const walk = (dir, root, project) => {
85
- for (const name of readdirSync(dir)) {
86
- const path = join(dir, name);
87
- inspect(path, () => {
88
- const stat = lstatSync(path);
89
- if (stat.isSymbolicLink())
90
- report(path, "symlink not inspected; replace with a regular note/directory");
91
- else if (stat.isDirectory())
92
- walk(path, root, project);
93
- else if (stat.isFile() && name.endsWith(".md"))
94
- checkNote(path, root, project);
95
- else
96
- report(path, "unexpected file in note home; inspect and relocate it");
97
- });
98
- }
99
- };
100
- inspect(home, () => {
101
- if (!directory(home))
102
- return;
103
- for (const name of readdirSync(home)) {
104
- const path = join(home, name);
105
- inspect(path, () => {
106
- if (name === ".dream.lock") {
107
- const valid = lstatSync(path).isFile() && /^[1-9]\d* [\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}\s*$/i.test(readFileSync(path, "utf8"));
108
- report(path, `${valid ? "lock present" : "malformed lock"}; verify no dream is running before manual removal; liveness not inferred`);
109
- return;
110
- }
111
- if ([".git", "dreams", "snapshots", "trash", ".dream.lock.last-run"].includes(name))
112
- return;
113
- if (name === "human") {
114
- if (directory(path))
115
- walk(path, path);
116
- return;
117
- }
118
- if (name === "agents" || name === "models") {
119
- if (!directory(path))
120
- return;
121
- for (const slug of readdirSync(path)) {
122
- const dir = join(path, slug);
123
- inspect(dir, () => {
124
- if (!SLUG_PATTERN.test(slug))
125
- report(dir, `invalid ${name.slice(0, -1)} slug; expected [a-z0-9-]`);
126
- if (!directory(dir))
127
- return;
128
- walk(dir, dir);
129
- });
130
- }
131
- return;
132
- }
133
- if (name === "project" || name === "pi") {
134
- if (!directory(path))
135
- return;
136
- const homes = name === "pi" ? join(path, "session") : path;
137
- if (name === "pi") {
138
- for (const entry of readdirSync(path))
139
- if (entry !== "session")
140
- report(join(path, entry), "unexpected directory; expected pi/session/<id>/");
141
- if (!existsSync(homes) || !directory(homes))
142
- return;
143
- }
144
- for (const id of readdirSync(homes)) {
145
- const root = join(homes, id);
146
- inspect(root, () => {
147
- if (!directory(root))
148
- return;
149
- if (name === "project" && !/^.+-[\da-f]{8}$/.test(id))
150
- report(root, "invalid project key; expected <name>-<8 hex>");
151
- walk(root, root, name === "project" ? root : undefined);
152
- });
153
- }
154
- return;
155
- }
156
- report(path, "unexpected root entry; expected human/, project/, agents/, models/, pi/session/ or dream artifacts");
157
- });
158
- }
159
- });
160
- return issues;
161
- }
@@ -1,10 +0,0 @@
1
- export type GateResult = {
2
- ok: boolean;
3
- reason: string;
4
- };
5
- /**
6
- * The scheduler reads the last-run sidecar, not the lock: the lock's lifetime says
7
- * nothing about when the last dream ran, while the sidecar records exactly that.
8
- */
9
- export declare function timeGate(stampPath: string, minHours: number, now?: number): GateResult;
10
- export declare function materialGate(home: string, sinceMtime: number, minSessions: number): GateResult;
@@ -1,26 +0,0 @@
1
- import { existsSync, readdirSync, statSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { sessionHomesRoot } from "../notes/paths.js";
4
- /**
5
- * The scheduler reads the last-run sidecar, not the lock: the lock's lifetime says
6
- * nothing about when the last dream ran, while the sidecar records exactly that.
7
- */
8
- export function timeGate(stampPath, minHours, now = Date.now()) {
9
- if (!existsSync(stampPath))
10
- return { ok: true, reason: "time gate: no prior dream" };
11
- const age = now - statSync(stampPath).mtimeMs;
12
- return age >= minHours * 3600000 ? { ok: true, reason: "time gate: stale" } : { ok: false, reason: "time gate: last dream is too recent" };
13
- }
14
- export function materialGate(home, sinceMtime, minSessions) {
15
- const root = sessionHomesRoot(home);
16
- let changed = 0;
17
- if (existsSync(root))
18
- for (const dir of readdirSync(root, { withFileTypes: true })) {
19
- if (!dir.isDirectory())
20
- continue;
21
- const files = readdirSync(join(root, dir.name), { withFileTypes: true });
22
- if (files.some((f) => f.isFile() && statSync(join(root, dir.name, f.name)).mtimeMs > sinceMtime))
23
- changed++;
24
- }
25
- return changed >= minSessions ? { ok: true, reason: `material gate: ${changed} changed sessions` } : { ok: false, reason: `material gate: only ${changed} changed sessions` };
26
- }
@@ -1,11 +0,0 @@
1
- export declare function jailWritePath(notesHome: string, path: string, options?: {
2
- createParent?: boolean;
3
- }): Promise<string>;
4
- /** Physical deletion refuses live notes even before playbook policy is consulted. */
5
- export declare function deleteCrumpledNote(notesHome: string, path: string): Promise<{
6
- content: {
7
- type: "text";
8
- text: string;
9
- }[];
10
- details: undefined;
11
- }>;
@@ -1,71 +0,0 @@
1
- import { lstat, mkdir, readFile, realpath, unlink } from "node:fs/promises";
2
- import { dirname, isAbsolute, relative, resolve } from "node:path";
3
- import { parseNote } from "../notes/frontmatter.js";
4
- function isOutside(notesHome, target) {
5
- const fromHome = relative(notesHome, target);
6
- return fromHome === ".." || fromHome.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(fromHome);
7
- }
8
- export async function jailWritePath(notesHome, path, options = {}) {
9
- let realNotesHome;
10
- try {
11
- realNotesHome = await realpath(notesHome);
12
- }
13
- catch {
14
- throw new Error(`Can't open the notes home ${notesHome}.`);
15
- }
16
- const target = resolve(realNotesHome, path);
17
- const targetParent = dirname(target);
18
- if (isOutside(realNotesHome, targetParent))
19
- throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
20
- // write creates parent directories itself. Create only after the lexical check, then
21
- // canonicalize the parent so a symlink cannot lead the underlying tool out of home.
22
- // delete passes createParent:false: the parent must already exist for there to be anything to remove.
23
- if (options.createParent !== false)
24
- await mkdir(targetParent, { recursive: true });
25
- let realTargetParent;
26
- try {
27
- realTargetParent = await realpath(targetParent);
28
- }
29
- catch {
30
- throw new Error(`Can't open the folder of ${path} in the notes home.`);
31
- }
32
- if (isOutside(realNotesHome, realTargetParent))
33
- throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
34
- let targetStats;
35
- try {
36
- targetStats = await lstat(target);
37
- }
38
- catch (error) {
39
- if (error.code !== "ENOENT")
40
- throw new Error(`Can't check ${path} in the notes home.`);
41
- }
42
- if (targetStats?.isSymbolicLink()) {
43
- let realTarget;
44
- try {
45
- realTarget = await realpath(target);
46
- }
47
- catch {
48
- throw new Error(`Can't follow the link at ${path} in the notes home.`);
49
- }
50
- if (isOutside(realNotesHome, realTarget))
51
- throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
52
- }
53
- if (targetStats && targetStats.nlink > 1)
54
- throw new Error(`${path} has other hard links, which may reach outside the notes home; leave it alone.`);
55
- return target;
56
- }
57
- /** Physical deletion refuses live notes even before playbook policy is consulted. */
58
- export async function deleteCrumpledNote(notesHome, path) {
59
- const target = await jailWritePath(notesHome, path, { createParent: false });
60
- let raw;
61
- try {
62
- raw = await readFile(target, "utf8");
63
- }
64
- catch (error) {
65
- throw new Error(`Can't read ${path} in the notes home: ${error.message}`);
66
- }
67
- if (parseNote(raw).meta.crumpledAt === undefined)
68
- throw new Error(`${path} isn't crumpled; only crumpled notes can be deleted.`);
69
- await unlink(target);
70
- return { content: [{ type: "text", text: `deleted ${path}` }], details: undefined };
71
- }
@@ -1,7 +0,0 @@
1
- import type { DreamWrite } from "./result.js";
2
- /**
3
- * Close one dream: record the report, then run the final audit commit. The audit always
4
- * runs even when the report cannot be written, and a failed audit is appended to the
5
- * report (when it exists) as well as named on stderr, so neither failure hides the other.
6
- */
7
- export declare function finishDream(home: string, stamp: string, reportPath: string, failed: boolean, body: string, writes: DreamWrite[]): number;
@@ -1,34 +0,0 @@
1
- import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
2
- import { dirname } from "node:path";
3
- import { gitCommit } from "./git.js";
4
- import { errorMessage } from "../error-message.js";
5
- function writeList(writes) {
6
- return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
7
- }
8
- /** Best-effort filesystem step; returns the failure message instead of throwing. */
9
- function attempt(action) {
10
- try {
11
- action();
12
- return undefined;
13
- }
14
- catch (error) {
15
- return errorMessage(error);
16
- }
17
- }
18
- /**
19
- * Close one dream: record the report, then run the final audit commit. The audit always
20
- * runs even when the report cannot be written, and a failed audit is appended to the
21
- * report (when it exists) as well as named on stderr, so neither failure hides the other.
22
- */
23
- export function finishDream(home, stamp, reportPath, failed, body, writes) {
24
- const header = failed ? `# Dream ${stamp} (failed)` : `# Dream ${stamp}`;
25
- let reportError = attempt(() => { mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`); });
26
- const audit = gitCommit(home, `dream ${stamp}${failed ? " (failed)" : ""}`);
27
- if (!audit.ok) {
28
- console.error(`dream: final audit failed: ${audit.error}`);
29
- reportError ??= attempt(() => appendFileSync(reportPath, `\n## Final audit failed\n\n${audit.error}\n`));
30
- }
31
- if (reportError)
32
- console.error(`dream: could not write report at ${reportPath}: ${reportError}`);
33
- return failed || !audit.ok || reportError !== undefined ? 1 : 0;
34
- }
@@ -1,9 +0,0 @@
1
- export type DreamWrite = {
2
- tool: "write" | "edit" | "delete";
3
- path: string;
4
- };
5
- export type DreamResult = {
6
- report: string;
7
- writes: DreamWrite[];
8
- error?: string;
9
- };
@@ -1,9 +0,0 @@
1
- export type DreamerSetting = {
2
- pattern?: string;
3
- warnings: string[];
4
- };
5
- /**
6
- * `notesoup.dreamer` is a non-empty model pattern. Anything else present is ignored
7
- * with one warning; absent means no configured pattern, so the automatic model applies.
8
- */
9
- export declare function deriveDreamer(settings: Record<string, unknown>): DreamerSetting;
@@ -1,16 +0,0 @@
1
- import { NOTESOUP_SETTINGS_KEY } from "../settings.js";
2
- /** Nested under the "notesoup" settings key; the dream CLI is the only reader. */
3
- const NOTESOUP_DREAMER_KEY = "dreamer";
4
- /**
5
- * `notesoup.dreamer` is a non-empty model pattern. Anything else present is ignored
6
- * with one warning; absent means no configured pattern, so the automatic model applies.
7
- */
8
- export function deriveDreamer(settings) {
9
- const raw = settings[NOTESOUP_DREAMER_KEY];
10
- if (raw === undefined)
11
- return { warnings: [] };
12
- if (typeof raw !== "string" || raw.trim().length === 0) {
13
- return { warnings: [`notesoup: ${NOTESOUP_SETTINGS_KEY}.${NOTESOUP_DREAMER_KEY} must be a non-empty string; ignoring it.`] };
14
- }
15
- return { pattern: raw.trim(), warnings: [] };
16
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,37 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { main } from "../plugins/pi/dream/cli.js";
3
- import { doctor } from "../src/dream/doctor.js";
4
- import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
5
- import test from "node:test";
6
- import { tmpdir } from "node:os";
7
- import { join } from "node:path";
8
- const note = "---\norigin: self\ncreatedAt: 2026-01-01T00:00:00Z\nupdatedAt: 2026-01-01T00:00:00Z\nlastAccessed: 2026-01-01T00:00:00Z\naccessCount: 0\n---\n\n";
9
- test("doctor ignores unknown frontmatter keys while validating canonical metadata", (t) => {
10
- const root = mkdtempSync(join(tmpdir(), "dream-doctor-extra-"));
11
- t.after(() => rmSync(root, { recursive: true, force: true }));
12
- mkdirSync(join(root, "human"));
13
- writeFileSync(join(root, "human/extra.md"), note.replace("accessCount: 0", "accessCount: 0\ncreated_at: 2025-01-01\nupdated_at: 2025-01-01\nlast_accessed: 2025-01-01\naccess_count: 7\nsource_window: old\nrecurrence_count: 2\nrecurrence_windows: old"));
14
- assert.deepEqual(doctor(root), [], "unknown fields have no special diagnostics");
15
- });
16
- test("doctor validates crumpledAt as an optional ISO timestamp", (t) => {
17
- const root = mkdtempSync(join(tmpdir(), "dream-doctor-crumpled-"));
18
- t.after(() => rmSync(root, { recursive: true, force: true }));
19
- mkdirSync(join(root, "human"));
20
- writeFileSync(join(root, "human/valid.md"), note.replace("accessCount: 0", "accessCount: 0\ncrumpledAt: 2026-01-02T00:00:00Z"));
21
- writeFileSync(join(root, "human/bad.md"), note.replace("accessCount: 0", "accessCount: 0\ncrumpledAt: yesterday"));
22
- assert.deepEqual(doctor(root), ["human/bad.md: missing/invalid crumpledAt; use an ISO timestamp"]);
23
- });
24
- test("doctor validates without repairing files or running the dreamer", async () => {
25
- const root = mkdtempSync(join(tmpdir(), "dream-doctor-test-"));
26
- mkdirSync(join(root, "human"));
27
- writeFileSync(join(root, "human/a.md"), note);
28
- writeFileSync(join(root, "human/MAP.md"), `${note}- \`a.md\``);
29
- const before = readFileSync(join(root, "human/a.md"));
30
- assert.deepEqual(doctor(root), []);
31
- assert.equal(await main(["doctor", "--notes-home", root], { runDreamer: async () => { throw new Error("must not run"); } }), 0);
32
- assert.deepEqual(readFileSync(join(root, "human/a.md")), before);
33
- assert.deepEqual(readdirSync(root), ["human"]);
34
- const missing = join(root, "absent");
35
- assert.equal(await main(["doctor", "--notes-home", missing]), 1);
36
- assert.equal(existsSync(missing), false);
37
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,150 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { execFileSync } from "node:child_process";
3
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
- import test from "node:test";
5
- import { tmpdir } from "node:os";
6
- import { basename, join } from "node:path";
7
- import { acquireLock, releaseLock } from "../src/dream/lock.js";
8
- import { dreamerDeleteToolDefinition, dreamerWriteToolDefinitions } from "../plugins/pi/dream/runner.js";
9
- import { main } from "../plugins/pi/dream/cli.js";
10
- const fixture = () => mkdtempSync(join(tmpdir(), "dream-test-"));
11
- function scriptedSession(run) {
12
- return async ({ cwd }) => {
13
- let handler = () => { };
14
- const session = {
15
- subscribe(next) { handler = next; return () => { }; },
16
- async prompt() { run(handler, cwd); },
17
- dispose() { },
18
- };
19
- return session;
20
- };
21
- }
22
- async function captureErrors(run) {
23
- const errors = [];
24
- const original = console.error;
25
- console.error = (...parts) => { errors.push(parts.map(String).join(" ")); };
26
- try {
27
- return { code: await run(), errors };
28
- }
29
- finally {
30
- console.error = original;
31
- }
32
- }
33
- test("dream lock refuses existing owners and preserves ownership", () => {
34
- const home = fixture();
35
- const lock = join(home, ".dream.lock");
36
- writeFileSync(lock, "999999 dead-owner");
37
- const refused = acquireLock(lock);
38
- assert.equal(refused.held, false);
39
- assert.equal(refused.reason, "lock gate: lock already exists");
40
- assert.equal(readFileSync(lock, "utf8"), "999999 dead-owner");
41
- rmSync(lock);
42
- const held = acquireLock(lock);
43
- assert.equal(held.held, true);
44
- const contender = acquireLock(lock);
45
- assert.equal(contender.held, false);
46
- assert.equal(readFileSync(lock, "utf8").trim(), `${process.pid} ${held.token}`);
47
- writeFileSync(lock, "123 other-owner");
48
- releaseLock(held);
49
- assert.equal(readFileSync(lock, "utf8"), "123 other-owner", "release cannot remove a replacement owner");
50
- const own = acquireLock(lock);
51
- assert.equal(own.held, false);
52
- rmSync(lock);
53
- const released = acquireLock(lock);
54
- assert.equal(released.held, true);
55
- releaseLock(released);
56
- assert.equal(existsSync(lock), false, "release removes the lock this run owns");
57
- });
58
- test("dreamer writes stay inside the notes home, including symlink escapes", async () => {
59
- const home = fixture();
60
- const outside = fixture();
61
- const tools = new Map(dreamerWriteToolDefinitions(home).map((tool) => [tool.name, tool]));
62
- const ctx = { cwd: home };
63
- await tools.get("write").execute("write", { path: "global/x.md", content: "one" }, undefined, undefined, ctx);
64
- assert.equal(readFileSync(join(home, "global/x.md"), "utf8"), "one");
65
- const rejects = async (tool, path) => {
66
- const params = tool === "write" ? { path, content: "outside" } : { path, edits: [{ oldText: "one", newText: "outside" }] };
67
- await assert.rejects(() => tools.get(tool).execute("escape", params, undefined, undefined, ctx), /dream-test/);
68
- };
69
- await rejects("write", "../outside.md");
70
- await rejects("edit", "/tmp/outside.md");
71
- symlinkSync(outside, join(home, "escape"));
72
- await rejects("write", "escape/outside.md");
73
- assert.equal(existsSync(join(outside, "outside.md")), false);
74
- });
75
- test("dreamer delete is jailed to the notes home and refuses live notes", async () => {
76
- const home = fixture();
77
- const outside = fixture();
78
- mkdirSync(join(home, "global"), { recursive: true });
79
- const frontmatter = "---\norigin: self\ncreatedAt: 2026-09-01T00:00:00.000+08:00\nupdatedAt: 2026-09-01T00:00:00.000+08:00\nlastAccessed: 2026-09-01T00:00:00.000+08:00\naccessCount: 0\n";
80
- writeFileSync(join(home, "global/dead.md"), `${frontmatter}crumpledAt: 2026-09-02T00:00:00.000+08:00\n---\ndead\n`);
81
- writeFileSync(join(home, "global/live.md"), `${frontmatter}---\nlive\n`);
82
- writeFileSync(join(outside, "keep.md"), "stay");
83
- const del = dreamerDeleteToolDefinition(home);
84
- const ctx = { cwd: home };
85
- await del.execute("d1", { path: "global/dead.md" }, undefined, undefined, ctx);
86
- assert.equal(existsSync(join(home, "global/dead.md")), false);
87
- await assert.rejects(() => del.execute("d2", { path: "global/live.md" }, undefined, undefined, ctx), /global\/live\.md/);
88
- assert.equal(existsSync(join(home, "global/live.md")), true);
89
- await assert.rejects(() => del.execute("d3", { path: join("..", basename(outside), "keep.md") }, undefined, undefined, ctx), /outside the notes home/);
90
- symlinkSync(join(outside, "keep.md"), join(home, "link.md"));
91
- await assert.rejects(() => del.execute("d4", { path: "link.md" }, undefined, undefined, ctx), /outside the notes home/);
92
- assert.equal(existsSync(join(outside, "keep.md")), true);
93
- });
94
- test("CLI lists dreamer deletions in the report", async () => {
95
- const home = fixture();
96
- const sessionFactory = scriptedSession((handler, cwd) => {
97
- mkdirSync(join(cwd, "global"), { recursive: true });
98
- handler({ type: "tool_execution_start", toolName: "delete", args: { path: "global/dead.md" } });
99
- handler({ type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "dreamt" }] } });
100
- });
101
- const { code, errors } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory, dreamerSettings: () => ({ warnings: [] }) }));
102
- assert.equal(code, 0, errors.join("\n"));
103
- const reports = readdirSync(join(home, "dreams"));
104
- assert.equal(reports.length, 1);
105
- assert.match(readFileSync(join(home, "dreams", reports[0]), "utf8"), /- delete: global\/dead\.md/);
106
- });
107
- test("CLI records a final audit failure and preserves the report", async () => {
108
- const home = fixture();
109
- const sessionFactory = scriptedSession((_handler, cwd) => {
110
- mkdirSync(join(cwd, "global"), { recursive: true });
111
- writeFileSync(join(cwd, "global/ok.md"), "ok");
112
- rmSync(join(cwd, ".git"), { recursive: true, force: true });
113
- writeFileSync(join(cwd, ".git"), "broken");
114
- });
115
- const { code, errors } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory, dreamerSettings: () => ({ warnings: [] }) }));
116
- assert.notEqual(code, 0);
117
- assert.ok(errors.some((line) => /final audit failed/.test(line)));
118
- const reports = readdirSync(join(home, "dreams"));
119
- assert.equal(reports.length, 1);
120
- assert.match(readFileSync(join(home, "dreams", reports[0]), "utf8"), /Final audit failed/);
121
- });
122
- test("CLI commits partial writes when report writing fails", async () => {
123
- const home = fixture();
124
- writeFileSync(join(home, "dreams"), "not a directory");
125
- const sessionFactory = scriptedSession((handler, cwd) => {
126
- mkdirSync(join(cwd, "global"), { recursive: true });
127
- writeFileSync(join(cwd, "global/partial.md"), "half");
128
- handler({ type: "tool_execution_start", toolName: "write", args: { path: "global/partial.md", content: "half" } });
129
- handler({ type: "message_end", message: { role: "assistant", stopReason: "error", errorMessage: "Insufficient Balance" } });
130
- });
131
- const { code, errors } = await captureErrors(() => main(["--notes-home", home, "--force"], { sessionFactory, dreamerSettings: () => ({ warnings: [] }) }));
132
- assert.notEqual(code, 0);
133
- assert.ok(errors.some((line) => /could not write report/.test(line)));
134
- assert.match(execFileSync("git", ["log", "--format=%s"], { cwd: home, encoding: "utf8" }).trim(), /\(failed\)/);
135
- assert.equal(execFileSync("git", ["show", "HEAD:global/partial.md"], { cwd: home, encoding: "utf8" }), "half");
136
- });
137
- test("CLI refuses a malformed flag value before creating anything", async () => {
138
- const numberHome = join(fixture(), "notes");
139
- const badNumber = await captureErrors(() => main(["--notes-home", numberHome, "--min-hours", "abc"], { dreamerSettings: () => ({ warnings: [] }) }));
140
- assert.equal(badNumber.code, 1);
141
- assert.ok(badNumber.errors.some((line) => /--min-hours needs a positive whole number/.test(line)), badNumber.errors.join("\n"));
142
- assert.equal(existsSync(numberHome), false, "a bad number is refused before the home is created");
143
- for (const value of ["", "--force"]) {
144
- const home = join(fixture(), "notes");
145
- const badHome = await captureErrors(() => main(["--notes-home", value], { dreamerSettings: () => ({ warnings: [] }) }));
146
- assert.equal(badHome.code, 1, `--notes-home ${JSON.stringify(value)} is refused`);
147
- assert.ok(badHome.errors.some((line) => /--notes-home needs a directory path/.test(line)), badHome.errors.join("\n"));
148
- assert.equal(existsSync(home), false, "a flag-looking path never becomes the home");
149
- }
150
- });