notesoup 0.51.9 → 0.52.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -10
- package/dist/plugins/claude/src/history.js +9 -12
- package/dist/plugins/pi/notes/tools.d.ts +1 -1
- package/dist/plugins/pi/notes/tools.js +26 -7
- package/dist/plugins/pi/tool-result.d.ts +3 -2
- package/dist/plugins/pi/tool-result.js +3 -1
- package/dist/src/dream/git.d.ts +2 -3
- package/dist/src/dream/git.js +3 -8
- package/dist/src/dream/lock.d.ts +10 -27
- package/dist/src/dream/lock.js +16 -79
- package/dist/src/history/query.js +2 -1
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/identity.d.ts +2 -0
- package/dist/src/notes/identity.js +3 -1
- package/dist/src/notes/store.d.ts +2 -0
- package/dist/src/notes/store.js +40 -4
- package/dist/src/tools/dream.d.ts +113 -0
- package/dist/src/tools/dream.js +112 -0
- package/dist/src/tools/history.js +1 -1
- package/dist/src/tools/notes.d.ts +15 -1
- package/dist/src/tools/notes.js +4 -4
- package/dist/test/claude-history.test.js +49 -2
- package/dist/test/claude-mod.test.js +136 -30
- package/dist/test/dependencies.test.js +3 -6
- package/dist/test/dream-skill.test.js +2 -3
- package/dist/test/dream-tools.test.js +67 -0
- package/docs/claude-code-mod.md +2 -2
- package/docs/notes-library.md +1 -1
- package/docs/skills.md +12 -15
- package/package.json +2 -5
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +36 -29
- package/plugins/claude/hooks/register.ts +71 -47
- package/plugins/claude/src/history.ts +9 -11
- package/plugins/pi/notes/tools.ts +25 -8
- package/plugins/pi/tool-result.ts +4 -1
- package/src/dream/git.ts +3 -8
- package/src/dream/lock.ts +18 -66
- package/src/history/query.ts +2 -1
- package/src/notes/errors.ts +1 -1
- package/src/notes/identity.ts +4 -1
- package/src/notes/store.ts +37 -4
- package/src/tools/dream.ts +112 -0
- package/src/tools/history.ts +1 -1
- package/src/tools/notes.ts +4 -4
- package/dist/plugins/pi/dream/cli.d.ts +0 -10
- package/dist/plugins/pi/dream/cli.js +0 -173
- package/dist/plugins/pi/dream/runner.d.ts +0 -27
- package/dist/plugins/pi/dream/runner.js +0 -91
- package/dist/plugins/pi/dream/settings.d.ts +0 -7
- package/dist/plugins/pi/dream/settings.js +0 -17
- package/dist/src/dream/doctor.d.ts +0 -2
- package/dist/src/dream/doctor.js +0 -161
- package/dist/src/dream/gates.d.ts +0 -10
- package/dist/src/dream/gates.js +0 -26
- package/dist/src/dream/jail.d.ts +0 -11
- package/dist/src/dream/jail.js +0 -71
- package/dist/src/dream/report.d.ts +0 -7
- package/dist/src/dream/report.js +0 -34
- package/dist/src/dream/result.d.ts +0 -9
- package/dist/src/dream/settings.d.ts +0 -9
- package/dist/src/dream/settings.js +0 -16
- package/dist/test/doctor.test.d.ts +0 -1
- package/dist/test/doctor.test.js +0 -37
- package/dist/test/dream.test.d.ts +0 -1
- package/dist/test/dream.test.js +0 -150
- package/plugins/pi/dream/cli.ts +0 -118
- package/plugins/pi/dream/runner.ts +0 -92
- package/plugins/pi/dream/settings.ts +0 -17
- package/src/dream/doctor.ts +0 -118
- package/src/dream/gates.ts +0 -26
- package/src/dream/jail.ts +0 -62
- package/src/dream/report.ts +0 -32
- package/src/dream/result.ts +0 -2
- package/src/dream/settings.ts +0 -19
- /package/dist/{src/dream/result.js → test/dream-tools.test.d.ts} +0 -0
|
@@ -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 {};
|
package/dist/test/doctor.test.js
DELETED
|
@@ -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 {};
|
package/dist/test/dream.test.js
DELETED
|
@@ -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
|
-
});
|
package/plugins/pi/dream/cli.ts
DELETED
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { finishDream } from "../../../src/dream/report.js";
|
|
3
|
-
import type { DreamerSetting } from "../../../src/dream/settings.js";
|
|
4
|
-
import type { DreamResult } from "../../../src/dream/result.js";
|
|
5
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
6
|
-
import { dirname, join, resolve } from "node:path";
|
|
7
|
-
import { fileURLToPath } from "node:url";
|
|
8
|
-
import { acquireLock, failLock, lastRunPath, releaseLock } from "../../../src/dream/lock.js";
|
|
9
|
-
import { materialGate, timeGate } from "../../../src/dream/gates.js";
|
|
10
|
-
import { runDreamer, type DreamerSessionFactory } from "./runner.js";
|
|
11
|
-
import { gitCommit } from "../../../src/dream/git.js";
|
|
12
|
-
import { readDreamerSettings } from "./settings.js";
|
|
13
|
-
import { doctor } from "../../../src/dream/doctor.js";
|
|
14
|
-
import { notesRoot } from "../notes/adapter.js";
|
|
15
|
-
import { errorMessage } from "../../../src/error-message.js";
|
|
16
|
-
|
|
17
|
-
function args(argv: string[]) { const out: Record<string, string | boolean> = {}; for (let i=0;i<argv.length;i++) { const a=argv[i]!; if (a === "--force" || a === "--help") out[a.slice(2)] = true; else if (a.startsWith("--")) out[a.slice(2)] = argv[++i] ?? ""; } return out; }
|
|
18
|
-
|
|
19
|
-
/** A positive whole-number flag, or undefined when the value is not one. */
|
|
20
|
-
function wholeNumberArg(raw: string | boolean | undefined): number | undefined {
|
|
21
|
-
if (raw === undefined) return undefined;
|
|
22
|
-
if (typeof raw !== "string" || raw.trim() === "") return undefined;
|
|
23
|
-
const value = Number(raw);
|
|
24
|
-
return Number.isInteger(value) && value > 0 ? value : undefined;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** A directory flag that must carry a real path, not a missing or flag-looking value. */
|
|
28
|
-
function directoryArg(raw: string | boolean | undefined): string | undefined {
|
|
29
|
-
if (raw === undefined) return undefined;
|
|
30
|
-
if (typeof raw !== "string" || raw.trim() === "" || raw.startsWith("--")) return undefined;
|
|
31
|
-
return raw;
|
|
32
|
-
}
|
|
33
|
-
function packageRoot(): string {
|
|
34
|
-
let dir = dirname(fileURLToPath(import.meta.url));
|
|
35
|
-
while (true) { if (existsSync(join(dir, "package.json"))) return dir; const parent = dirname(dir); if (parent === dir) throw new Error("could not locate installed package root"); dir = parent; }
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** Injection seams used by tests; production uses the defaults. */
|
|
39
|
-
export type DreamDependencies = {
|
|
40
|
-
sessionFactory?: DreamerSessionFactory;
|
|
41
|
-
dreamerSettings?: (cwd?: string) => DreamerSetting;
|
|
42
|
-
runDreamer?: typeof runDreamer;
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
export async function main(argv = process.argv.slice(2), deps: DreamDependencies = {}): Promise<number> {
|
|
46
|
-
if (argv[0] === "doctor") {
|
|
47
|
-
const options = args(argv.slice(1));
|
|
48
|
-
if (options.help) { console.log("dream doctor [--notes-home <dir>] — read-only diagnostics; no model or repairs"); return 0; }
|
|
49
|
-
const home = directoryArg(options["notes-home"]);
|
|
50
|
-
if (options["notes-home"] !== undefined && home === undefined) { console.error("dream: --notes-home needs a directory path"); return 1; }
|
|
51
|
-
const root = resolve(home ?? notesRoot());
|
|
52
|
-
const issues = doctor(root);
|
|
53
|
-
console.log(issues.length ? issues.join("\n") : `dream doctor: OK (${root})`);
|
|
54
|
-
return issues.length ? 1 : 0;
|
|
55
|
-
}
|
|
56
|
-
const a = args(argv); if (a.help) { console.log("dream doctor [--notes-home <dir>] — read-only diagnostics\ndream --notes-home <dir> [--min-hours 24] [--min-sessions 3] [--force] [--dreamer <model pattern>] [--playbook <path>]\nDreamer model: --dreamer wins, else notesoup.dreamer from settings, else the automatic model. Default playbook: <installed package root>/playbook.md; --playbook overrides it."); return 0; }
|
|
57
|
-
// Validate every value flag before anything is created or gated on: a typo must refuse
|
|
58
|
-
// loudly instead of reading as "the last dream is too recent" and exiting successfully.
|
|
59
|
-
const homeArg = directoryArg(a["notes-home"]);
|
|
60
|
-
const minHours = wholeNumberArg(a["min-hours"]);
|
|
61
|
-
const minSessions = wholeNumberArg(a["min-sessions"]);
|
|
62
|
-
const badArg = a["notes-home"] !== undefined && homeArg === undefined ? "--notes-home needs a directory path"
|
|
63
|
-
: a["min-hours"] !== undefined && minHours === undefined ? "--min-hours needs a positive whole number"
|
|
64
|
-
: a["min-sessions"] !== undefined && minSessions === undefined ? "--min-sessions needs a positive whole number"
|
|
65
|
-
: undefined;
|
|
66
|
-
if (badArg) { console.error(`dream: ${badArg}`); return 1; }
|
|
67
|
-
const home = resolve(homeArg ?? notesRoot()); process.env.NOTESOUP_HOME = home; mkdirSync(home, { recursive: true });
|
|
68
|
-
const lockPath = join(home, ".dream.lock"); const stampPath = lastRunPath(lockPath);
|
|
69
|
-
const time = timeGate(stampPath, minHours ?? 24); console.log(time.reason); if (!a.force && !time.ok) return 0;
|
|
70
|
-
const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
|
|
71
|
-
const material = materialGate(home, since, minSessions ?? 3); console.log(material.reason); if (!a.force && !material.ok) return 0;
|
|
72
|
-
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${errorMessage(e)}`); return 0; } if (!lock.held) { console.log(lock.reason); return 0; }
|
|
73
|
-
const stamp = new Date(lock.startedAt).toISOString().replace(/[:.]/g, "-"); const reportPath = join(home, "dreams", `${stamp}.md`);
|
|
74
|
-
let succeeded = false;
|
|
75
|
-
try {
|
|
76
|
-
// CLI --dreamer wins over settings; settings win over the automatic model fallback.
|
|
77
|
-
let modelPattern: string | undefined;
|
|
78
|
-
if (a.dreamer) modelPattern = String(a.dreamer);
|
|
79
|
-
else {
|
|
80
|
-
const settings = (deps.dreamerSettings ?? readDreamerSettings)();
|
|
81
|
-
for (const warning of settings.warnings) console.error(warning);
|
|
82
|
-
modelPattern = settings.pattern;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// The baseline snapshot is required: without it the human gate has nothing to inspect.
|
|
86
|
-
const baseline = gitCommit(home, `baseline ${stamp}`);
|
|
87
|
-
if (!baseline.ok) { console.error(`dream: baseline audit failed: ${baseline.error}`); return 1; }
|
|
88
|
-
|
|
89
|
-
const defaultBook = join(packageRoot(), "playbook.md");
|
|
90
|
-
const playbookPath = String(a.playbook ?? defaultBook);
|
|
91
|
-
let result: DreamResult;
|
|
92
|
-
try {
|
|
93
|
-
const playbook = readFileSync(playbookPath, "utf8");
|
|
94
|
-
result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
|
|
95
|
-
} catch (e) {
|
|
96
|
-
const message = errorMessage(e);
|
|
97
|
-
console.error(message);
|
|
98
|
-
return finishDream(home, stamp, reportPath, true, message, []);
|
|
99
|
-
}
|
|
100
|
-
if (result.error) {
|
|
101
|
-
console.error(result.error);
|
|
102
|
-
return finishDream(home, stamp, reportPath, true, result.error, result.writes);
|
|
103
|
-
}
|
|
104
|
-
const code = finishDream(home, stamp, reportPath, false, result.report, result.writes);
|
|
105
|
-
if (code === 0) { succeeded = true; console.log(reportPath); }
|
|
106
|
-
return code;
|
|
107
|
-
} finally {
|
|
108
|
-
// Only the holder's own lock is released; a successor's lock is never touched.
|
|
109
|
-
if (succeeded) releaseLock(lock); else failLock(lock);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
function isEntryPoint(): boolean {
|
|
114
|
-
const entry = process.argv[1];
|
|
115
|
-
if (!entry) return false;
|
|
116
|
-
try { return realpathSync(resolve(entry)) === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; }
|
|
117
|
-
}
|
|
118
|
-
if (isEntryPoint()) main().then((code) => { process.exitCode = code; });
|
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import { jailWritePath, deleteCrumpledNote } from "../../../src/dream/jail.js";
|
|
2
|
-
import type { DreamResult, DreamWrite } from "../../../src/dream/result.js";
|
|
3
|
-
import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager, type AgentSession, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
import { Type, type Api, type Model } from "@earendil-works/pi-ai";
|
|
5
|
-
import { contentText } from "../../../src/history/history.js";
|
|
6
|
-
import { errorMessage } from "../../../src/error-message.js";
|
|
7
|
-
|
|
8
|
-
export type DreamerSession = Pick<AgentSession, "prompt" | "subscribe" | "dispose">;
|
|
9
|
-
export type DreamerSessionFactory = (options: { cwd: string; modelPattern?: string; tools: string[] }) => Promise<DreamerSession>;
|
|
10
|
-
export const DREAMER_TOOLS = ["read", "grep", "find", "ls", "write", "edit"];
|
|
11
|
-
|
|
12
|
-
function jailToolDefinition<T extends ToolDefinition<any, any, any>>(definition: T, notesHome: string): T {
|
|
13
|
-
const execute = definition.execute;
|
|
14
|
-
return {
|
|
15
|
-
...definition,
|
|
16
|
-
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
17
|
-
await jailWritePath(notesHome, (params as { path: string }).path);
|
|
18
|
-
return execute(toolCallId, params, signal, onUpdate, ctx);
|
|
19
|
-
},
|
|
20
|
-
} as T;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** The dream session's custom definitions: jailed versions of the two write built-ins, plus the jailed delete below. */
|
|
24
|
-
export function dreamerWriteToolDefinitions(notesHome: string): ToolDefinition<any, any, any>[] {
|
|
25
|
-
return [
|
|
26
|
-
jailToolDefinition(createWriteToolDefinition(notesHome), notesHome),
|
|
27
|
-
jailToolDefinition(createEditToolDefinition(notesHome), notesHome),
|
|
28
|
-
];
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const DELETE_PARAMETERS = Type.Object({ path: Type.String({ description: "Path of the crumpled note file, relative to the notes home." }) }, { additionalProperties: false });
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* The dreamer's physical delete, jailed like the writes and restricted to crumpled notes: the
|
|
35
|
-
* playbook's wastebasket rule is the only legitimate target, so a live note refuses here even
|
|
36
|
-
* before policy is consulted. The time window itself stays playbook policy, not tool law.
|
|
37
|
-
*/
|
|
38
|
-
export function dreamerDeleteToolDefinition(notesHome: string): ToolDefinition<any, any, any> {
|
|
39
|
-
return {
|
|
40
|
-
name: "delete",
|
|
41
|
-
label: "delete",
|
|
42
|
-
description: "Physically delete one crumpled note file inside the notes home. Reserved for the playbook's wastebasket rule: a crumpled note whose full retention window has passed. Live notes refuse. Deletion is permanent beyond the Git audit.",
|
|
43
|
-
parameters: DELETE_PARAMETERS,
|
|
44
|
-
async execute(_toolCallId: string, params: { path: string }, _signal: AbortSignal | undefined, _onUpdate: unknown, _ctx: unknown) {
|
|
45
|
-
return deleteCrumpledNote(notesHome, params.path);
|
|
46
|
-
},
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export const defaultDreamerSessionFactory: DreamerSessionFactory = async ({ cwd, modelPattern, tools }) => {
|
|
51
|
-
let model: Model<Api> | undefined;
|
|
52
|
-
if (modelPattern) {
|
|
53
|
-
const runtime = await ModelRuntime.create({ allowModelNetwork: false, refreshOnCreate: false });
|
|
54
|
-
const result = await resolveModelScopeWithDiagnostics([modelPattern], runtime);
|
|
55
|
-
model = result.scopedModels[0]?.model;
|
|
56
|
-
if (!model) throw new Error(`dreamer model pattern "${modelPattern}" did not resolve to an available model`);
|
|
57
|
-
}
|
|
58
|
-
const { session } = await createAgentSession({ cwd, sessionManager: SessionManager.inMemory(cwd), tools, customTools: [...dreamerWriteToolDefinitions(cwd), dreamerDeleteToolDefinition(cwd)], noTools: "all", model, thinkingLevel: "off" });
|
|
59
|
-
return session;
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Run one dream turn. A dreamer failure is returned as `error` together with the partial
|
|
64
|
-
* writes observed so far, so the caller can record partial state instead of losing it;
|
|
65
|
-
* only a failure to even start the session throws.
|
|
66
|
-
*/
|
|
67
|
-
export async function runDreamer(playbook: string, cwd: string, options: { modelPattern?: string; sessionFactory?: DreamerSessionFactory } = {}): Promise<DreamResult> {
|
|
68
|
-
const session = await (options.sessionFactory ?? defaultDreamerSessionFactory)({ cwd, modelPattern: options.modelPattern, tools: DREAMER_TOOLS });
|
|
69
|
-
let answer = "";
|
|
70
|
-
let providerError: string | undefined;
|
|
71
|
-
const writes: DreamWrite[] = [];
|
|
72
|
-
const unsubscribe = session.subscribe((event: any) => {
|
|
73
|
-
const tool = event.toolName ?? event.tool?.name;
|
|
74
|
-
const args = event.args ?? event.arguments ?? event.tool?.arguments;
|
|
75
|
-
if ((tool === "write" || tool === "edit" || tool === "delete") && args && typeof args === "object" && typeof args.path === "string") writes.push({ tool, path: args.path });
|
|
76
|
-
if (event.type !== "message_end" || event.message?.role !== "assistant") return;
|
|
77
|
-
if (event.message.stopReason === "error") { providerError = event.message.errorMessage ?? "unknown provider error"; return; }
|
|
78
|
-
answer = contentText(event.message.content);
|
|
79
|
-
});
|
|
80
|
-
try {
|
|
81
|
-
try {
|
|
82
|
-
await session.prompt(playbook);
|
|
83
|
-
} catch (error) {
|
|
84
|
-
return { report: answer, writes, error: errorMessage(error) };
|
|
85
|
-
}
|
|
86
|
-
if (providerError) return { report: answer, writes, error: `dreamer failed: ${providerError}` };
|
|
87
|
-
return { report: answer, writes };
|
|
88
|
-
} finally {
|
|
89
|
-
unsubscribe?.();
|
|
90
|
-
session.dispose();
|
|
91
|
-
}
|
|
92
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { deriveDreamer, type DreamerSetting } from "../../../src/dream/settings.js";
|
|
2
|
-
import { SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { mergeNotesoupSettings } from "../../../src/settings.js";
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Resolve the configurable dreamer model from Pi settings for a CLI invocation: global
|
|
7
|
-
* `~/.pi/agent/settings.json` merged with the project's `.pi/settings.json`, project
|
|
8
|
-
* values winning per key. A settings read failure degrades to no pattern with one warning.
|
|
9
|
-
*/
|
|
10
|
-
export function readDreamerSettings(cwd = process.cwd()): DreamerSetting {
|
|
11
|
-
try {
|
|
12
|
-
const settingsManager = SettingsManager.create(cwd, undefined, { projectTrusted: true });
|
|
13
|
-
return deriveDreamer(mergeNotesoupSettings(settingsManager.getGlobalSettings(), settingsManager.getProjectSettings()));
|
|
14
|
-
} catch (error) {
|
|
15
|
-
return { warnings: [`notesoup: could not read settings; using the automatic dreamer model (${String(error)}).`] };
|
|
16
|
-
}
|
|
17
|
-
}
|
package/src/dream/doctor.ts
DELETED
|
@@ -1,118 +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
|
-
|
|
7
|
-
/** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
|
|
8
|
-
export function doctor(home: string): string[] {
|
|
9
|
-
const issues: string[] = [];
|
|
10
|
-
const report = (path: string, message: string) => issues.push(`${relative(home, path) || "."}: ${message}`);
|
|
11
|
-
const inspect = (path: string, action: () => void) => {
|
|
12
|
-
try { action(); } catch (error) { report(path, `cannot inspect: ${errorMessage(error)}`); }
|
|
13
|
-
};
|
|
14
|
-
const directory = (path: string): boolean => {
|
|
15
|
-
const stat = lstatSync(path);
|
|
16
|
-
if (stat.isDirectory()) return true;
|
|
17
|
-
report(path, "expected a directory (symlinks are not followed); check its location/type");
|
|
18
|
-
return false;
|
|
19
|
-
};
|
|
20
|
-
const checkNote = (path: string, root: string, project?: string) => {
|
|
21
|
-
const raw = readFileSync(path, "utf8");
|
|
22
|
-
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(raw);
|
|
23
|
-
if (!match) { report(path, "missing or unclosed frontmatter; add a valid metadata block"); return; }
|
|
24
|
-
const fields = new Map<string, string>();
|
|
25
|
-
for (const line of match[1]!.split(/\r?\n/)) {
|
|
26
|
-
const field = /^([\w]+):\s*(.*?)\s*$/.exec(line);
|
|
27
|
-
if (!field) continue;
|
|
28
|
-
if (fields.has(field[1]!)) report(path, `duplicate metadata key ${field[1]}; keep one value`);
|
|
29
|
-
fields.set(field[1]!, field[2]!.replace(/^(["'])(.*)\1$/, "$2"));
|
|
30
|
-
}
|
|
31
|
-
for (const [key, valid] of Object.entries({ origin: /^(user|self|external)$/, accessCount: /^\d+$/ })) {
|
|
32
|
-
if (!valid.test(fields.get(key) ?? "")) report(path, `missing/invalid ${key}; repair frontmatter`);
|
|
33
|
-
}
|
|
34
|
-
for (const key of ["createdAt", "updatedAt", "lastAccessed", "crumpledAt"]) {
|
|
35
|
-
if (key === "crumpledAt" && !fields.has(key)) continue;
|
|
36
|
-
const value = fields.get(key);
|
|
37
|
-
if (!value || !Number.isFinite(Date.parse(value))) report(path, `missing/invalid ${key}; use an ISO timestamp`);
|
|
38
|
-
}
|
|
39
|
-
if (fields.has("scope")) report(path, "obsolete scope field; remove it (home determines scope)");
|
|
40
|
-
// Check concrete, code-formatted addresses; examples/globs and prose are not links.
|
|
41
|
-
for (const link of raw.slice(match[0].length).matchAll(/`([^`\n]+)`/g)) {
|
|
42
|
-
const address = link[1]!;
|
|
43
|
-
if (!address.endsWith(".md") || /[<>*?\s]/.test(address)) continue;
|
|
44
|
-
if (!address.startsWith("@") && basename(path) !== "MAP.md") continue;
|
|
45
|
-
try {
|
|
46
|
-
const parsed = assertAddress(address);
|
|
47
|
-
// Relative homes (@self/, @model/) name whoever is running; a static doctor
|
|
48
|
-
// cannot resolve them, so only absolute links are checked.
|
|
49
|
-
if ((parsed.scope === "agent" || parsed.scope === "model") && parsed.who === undefined) continue;
|
|
50
|
-
const targetHome = parsed.scope === "human" ? join(home, "human")
|
|
51
|
-
: parsed.scope === "project" ? project
|
|
52
|
-
: parsed.scope === "agent" ? join(home, "agents", parsed.who!)
|
|
53
|
-
: parsed.scope === "model" ? join(home, "models", parsed.who!)
|
|
54
|
-
: root;
|
|
55
|
-
if (!targetHome) { report(path, `${address}: project context unavailable; use a resolvable reference`); continue; }
|
|
56
|
-
if (!existsSync(join(targetHome, parsed.path))) report(path, `${address}: target missing; update or remove the reference`);
|
|
57
|
-
} catch { report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`); }
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
const walk = (dir: string, root: string, project?: string) => {
|
|
61
|
-
for (const name of readdirSync(dir)) {
|
|
62
|
-
const path = join(dir, name);
|
|
63
|
-
inspect(path, () => {
|
|
64
|
-
const stat = lstatSync(path);
|
|
65
|
-
if (stat.isSymbolicLink()) report(path, "symlink not inspected; replace with a regular note/directory");
|
|
66
|
-
else if (stat.isDirectory()) walk(path, root, project);
|
|
67
|
-
else if (stat.isFile() && name.endsWith(".md")) checkNote(path, root, project);
|
|
68
|
-
else report(path, "unexpected file in note home; inspect and relocate it");
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
inspect(home, () => {
|
|
73
|
-
if (!directory(home)) return;
|
|
74
|
-
for (const name of readdirSync(home)) {
|
|
75
|
-
const path = join(home, name);
|
|
76
|
-
inspect(path, () => {
|
|
77
|
-
if (name === ".dream.lock") {
|
|
78
|
-
const valid = lstatSync(path).isFile() && /^[1-9]\d* [\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}\s*$/i.test(readFileSync(path, "utf8"));
|
|
79
|
-
report(path, `${valid ? "lock present" : "malformed lock"}; verify no dream is running before manual removal; liveness not inferred`);
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
if ([".git", "dreams", "snapshots", "trash", ".dream.lock.last-run"].includes(name)) return;
|
|
83
|
-
if (name === "human") { if (directory(path)) walk(path, path); return; }
|
|
84
|
-
if (name === "agents" || name === "models") {
|
|
85
|
-
if (!directory(path)) return;
|
|
86
|
-
for (const slug of readdirSync(path)) {
|
|
87
|
-
const dir = join(path, slug);
|
|
88
|
-
inspect(dir, () => {
|
|
89
|
-
if (!SLUG_PATTERN.test(slug)) report(dir, `invalid ${name.slice(0, -1)} slug; expected [a-z0-9-]`);
|
|
90
|
-
if (!directory(dir)) return;
|
|
91
|
-
walk(dir, dir);
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
if (name === "project" || name === "pi") {
|
|
97
|
-
if (!directory(path)) return;
|
|
98
|
-
const homes = name === "pi" ? join(path, "session") : path;
|
|
99
|
-
if (name === "pi") {
|
|
100
|
-
for (const entry of readdirSync(path)) if (entry !== "session") report(join(path, entry), "unexpected directory; expected pi/session/<id>/");
|
|
101
|
-
if (!existsSync(homes) || !directory(homes)) return;
|
|
102
|
-
}
|
|
103
|
-
for (const id of readdirSync(homes)) {
|
|
104
|
-
const root = join(homes, id);
|
|
105
|
-
inspect(root, () => {
|
|
106
|
-
if (!directory(root)) return;
|
|
107
|
-
if (name === "project" && !/^.+-[\da-f]{8}$/.test(id)) report(root, "invalid project key; expected <name>-<8 hex>");
|
|
108
|
-
walk(root, root, name === "project" ? root : undefined);
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
return;
|
|
112
|
-
}
|
|
113
|
-
report(path, "unexpected root entry; expected human/, project/, agents/, models/, pi/session/ or dream artifacts");
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
});
|
|
117
|
-
return issues;
|
|
118
|
-
}
|
package/src/dream/gates.ts
DELETED
|
@@ -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
|
-
export type GateResult = { ok: boolean; reason: string };
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* The scheduler reads the last-run sidecar, not the lock: the lock's lifetime says
|
|
9
|
-
* nothing about when the last dream ran, while the sidecar records exactly that.
|
|
10
|
-
*/
|
|
11
|
-
export function timeGate(stampPath: string, minHours: number, now = Date.now()): GateResult {
|
|
12
|
-
if (!existsSync(stampPath)) return { ok: true, reason: "time gate: no prior dream" };
|
|
13
|
-
const age = now - statSync(stampPath).mtimeMs;
|
|
14
|
-
return age >= minHours * 3600000 ? { ok: true, reason: "time gate: stale" } : { ok: false, reason: "time gate: last dream is too recent" };
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function materialGate(home: string, sinceMtime: number, minSessions: number): GateResult {
|
|
18
|
-
const root = sessionHomesRoot(home);
|
|
19
|
-
let changed = 0;
|
|
20
|
-
if (existsSync(root)) for (const dir of readdirSync(root, { withFileTypes: true })) {
|
|
21
|
-
if (!dir.isDirectory()) continue;
|
|
22
|
-
const files = readdirSync(join(root, dir.name), { withFileTypes: true });
|
|
23
|
-
if (files.some((f) => f.isFile() && statSync(join(root, dir.name, f.name)).mtimeMs > sinceMtime)) changed++;
|
|
24
|
-
}
|
|
25
|
-
return changed >= minSessions ? { ok: true, reason: `material gate: ${changed} changed sessions` } : { ok: false, reason: `material gate: only ${changed} changed sessions` };
|
|
26
|
-
}
|