notesoup 0.0.0-stage → 0.40.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.
- package/LICENSE +21 -0
- package/README.md +94 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +17 -0
- package/dist/src/boot/text.js +48 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +156 -0
- package/dist/src/history/history.js +212 -0
- package/dist/src/history/query.d.ts +63 -0
- package/dist/src/history/query.js +201 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +103 -0
- package/dist/src/notes/store.js +474 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +9 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +7 -0
- package/dist/src/pi/tool-names.js +7 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +58 -0
- package/dist/src/tools/history.js +210 -0
- package/dist/src/tools/notes.d.ts +250 -0
- package/dist/src/tools/notes.js +360 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +82 -0
- package/dist/src/tools/result.js +104 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +367 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +633 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +274 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +515 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +530 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +78 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9265 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +240 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +58 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +286 -0
- package/src/history/query.ts +222 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +494 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +11 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +9 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +234 -0
- package/src/tools/notes.ts +381 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +144 -0
- package/src/tools/schema.ts +31 -0
|
@@ -0,0 +1,117 @@
|
|
|
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
|
+
|
|
6
|
+
/** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
|
|
7
|
+
export function doctor(home: string): string[] {
|
|
8
|
+
const issues: string[] = [];
|
|
9
|
+
const report = (path: string, message: string) => issues.push(`${relative(home, path) || "."}: ${message}`);
|
|
10
|
+
const inspect = (path: string, action: () => void) => {
|
|
11
|
+
try { action(); } catch (error) { report(path, `cannot inspect: ${error instanceof Error ? error.message : String(error)}`); }
|
|
12
|
+
};
|
|
13
|
+
const directory = (path: string): boolean => {
|
|
14
|
+
const stat = lstatSync(path);
|
|
15
|
+
if (stat.isDirectory()) return true;
|
|
16
|
+
report(path, "expected a directory (symlinks are not followed); check its location/type");
|
|
17
|
+
return false;
|
|
18
|
+
};
|
|
19
|
+
const checkNote = (path: string, root: string, project?: string) => {
|
|
20
|
+
const raw = readFileSync(path, "utf8");
|
|
21
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(raw);
|
|
22
|
+
if (!match) { report(path, "missing or unclosed frontmatter; add a valid metadata block"); return; }
|
|
23
|
+
const fields = new Map<string, string>();
|
|
24
|
+
for (const line of match[1]!.split(/\r?\n/)) {
|
|
25
|
+
const field = /^([\w]+):\s*(.*?)\s*$/.exec(line);
|
|
26
|
+
if (!field) continue;
|
|
27
|
+
if (fields.has(field[1]!)) report(path, `duplicate metadata key ${field[1]}; keep one value`);
|
|
28
|
+
fields.set(field[1]!, field[2]!.replace(/^(["'])(.*)\1$/, "$2"));
|
|
29
|
+
}
|
|
30
|
+
for (const [key, valid] of Object.entries({ origin: /^(user|self|external)$/, accessCount: /^\d+$/ })) {
|
|
31
|
+
if (!valid.test(fields.get(key) ?? "")) report(path, `missing/invalid ${key}; repair frontmatter`);
|
|
32
|
+
}
|
|
33
|
+
for (const key of ["createdAt", "updatedAt", "lastAccessed", "crumpledAt"]) {
|
|
34
|
+
if (key === "crumpledAt" && !fields.has(key)) continue;
|
|
35
|
+
const value = fields.get(key);
|
|
36
|
+
if (!value || !Number.isFinite(Date.parse(value))) report(path, `missing/invalid ${key}; use an ISO timestamp`);
|
|
37
|
+
}
|
|
38
|
+
if (fields.has("scope")) report(path, "obsolete scope field; remove it (home determines scope)");
|
|
39
|
+
// Check concrete, code-formatted addresses; examples/globs and prose are not links.
|
|
40
|
+
for (const link of raw.slice(match[0].length).matchAll(/`([^`\n]+)`/g)) {
|
|
41
|
+
const address = link[1]!;
|
|
42
|
+
if (!address.endsWith(".md") || /[<>*?\s]/.test(address)) continue;
|
|
43
|
+
if (!address.startsWith("@") && basename(path) !== "MAP.md") continue;
|
|
44
|
+
try {
|
|
45
|
+
const parsed = assertAddress(address);
|
|
46
|
+
// Relative homes (@self/, @model/) name whoever is running; a static doctor
|
|
47
|
+
// cannot resolve them, so only absolute links are checked.
|
|
48
|
+
if ((parsed.scope === "agent" || parsed.scope === "model") && parsed.who === undefined) continue;
|
|
49
|
+
const targetHome = parsed.scope === "human" ? join(home, "human")
|
|
50
|
+
: parsed.scope === "project" ? project
|
|
51
|
+
: parsed.scope === "agent" ? join(home, "agents", parsed.who!)
|
|
52
|
+
: parsed.scope === "model" ? join(home, "models", parsed.who!)
|
|
53
|
+
: root;
|
|
54
|
+
if (!targetHome) { report(path, `${address}: project context unavailable; use a resolvable reference`); continue; }
|
|
55
|
+
if (!existsSync(join(targetHome, parsed.path))) report(path, `${address}: target missing; update or remove the reference`);
|
|
56
|
+
} catch { report(path, `${address}: invalid address; ${ADDRESS_FORMS}`); }
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const walk = (dir: string, root: string, project?: string) => {
|
|
60
|
+
for (const name of readdirSync(dir)) {
|
|
61
|
+
const path = join(dir, name);
|
|
62
|
+
inspect(path, () => {
|
|
63
|
+
const stat = lstatSync(path);
|
|
64
|
+
if (stat.isSymbolicLink()) report(path, "symlink not inspected; replace with a regular note/directory");
|
|
65
|
+
else if (stat.isDirectory()) walk(path, root, project);
|
|
66
|
+
else if (stat.isFile() && name.endsWith(".md")) checkNote(path, root, project);
|
|
67
|
+
else report(path, "unexpected file in note home; inspect and relocate it");
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
inspect(home, () => {
|
|
72
|
+
if (!directory(home)) return;
|
|
73
|
+
for (const name of readdirSync(home)) {
|
|
74
|
+
const path = join(home, name);
|
|
75
|
+
inspect(path, () => {
|
|
76
|
+
if (name === ".dream.lock") {
|
|
77
|
+
const valid = lstatSync(path).isFile() && /^[1-9]\d* [\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}\s*$/i.test(readFileSync(path, "utf8"));
|
|
78
|
+
report(path, `${valid ? "lock present" : "malformed lock"}; verify no dream is running before manual removal; liveness not inferred`);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if ([".git", "dreams", "snapshots", "trash", ".dream.lock.last-run"].includes(name)) return;
|
|
82
|
+
if (name === "human") { if (directory(path)) walk(path, path); return; }
|
|
83
|
+
if (name === "agents" || name === "models") {
|
|
84
|
+
if (!directory(path)) return;
|
|
85
|
+
for (const slug of readdirSync(path)) {
|
|
86
|
+
const dir = join(path, slug);
|
|
87
|
+
inspect(dir, () => {
|
|
88
|
+
if (!SLUG_PATTERN.test(slug)) report(dir, `invalid ${name.slice(0, -1)} slug; expected [a-z0-9-]`);
|
|
89
|
+
if (!directory(dir)) return;
|
|
90
|
+
walk(dir, dir);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (name === "project" || name === "pi") {
|
|
96
|
+
if (!directory(path)) return;
|
|
97
|
+
const homes = name === "pi" ? join(path, "session") : path;
|
|
98
|
+
if (name === "pi") {
|
|
99
|
+
for (const entry of readdirSync(path)) if (entry !== "session") report(join(path, entry), "unexpected directory; expected pi/session/<id>/");
|
|
100
|
+
if (!existsSync(homes) || !directory(homes)) return;
|
|
101
|
+
}
|
|
102
|
+
for (const id of readdirSync(homes)) {
|
|
103
|
+
const root = join(homes, id);
|
|
104
|
+
inspect(root, () => {
|
|
105
|
+
if (!directory(root)) return;
|
|
106
|
+
if (name === "project" && !/^.+-[\da-f]{8}$/.test(id)) report(root, "invalid project key; expected <name>-<8 hex>");
|
|
107
|
+
walk(root, root, name === "project" ? root : undefined);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
report(path, "unexpected root entry; expected human/, project/, agents/, models/, pi/session/ or dream artifacts");
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
return issues;
|
|
117
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
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
|
+
}
|
package/src/dream/git.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Outcome of one audit commit. `ok: true` always carries a real `commit` snapshot;
|
|
7
|
+
* `empty: true` only means no files changed (an empty baseline commit or no commit was
|
|
8
|
+
* needed). `ok: false` means the audit layer could not guarantee a snapshot.
|
|
9
|
+
*/
|
|
10
|
+
export type AuditResult =
|
|
11
|
+
| { ok: true; commit: string; empty: boolean }
|
|
12
|
+
| { ok: false; error: string };
|
|
13
|
+
|
|
14
|
+
/** Lock runtime artifacts are not notes and must not appear in snapshots or `git status`. */
|
|
15
|
+
const RUNTIME_IGNORE = ".dream.lock*";
|
|
16
|
+
|
|
17
|
+
/** Add the runtime-artifact pattern to the repository's local exclude, once. */
|
|
18
|
+
function ensureRuntimeIgnored(home: string): void {
|
|
19
|
+
try {
|
|
20
|
+
const exclude = join(home, ".git", "info", "exclude");
|
|
21
|
+
const current = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
|
|
22
|
+
if (current.split(/\r?\n/).includes(RUNTIME_IGNORE)) return;
|
|
23
|
+
mkdirSync(dirname(exclude), { recursive: true });
|
|
24
|
+
const prefix = current.length > 0 && !current.endsWith("\n") ? `${current}\n` : current;
|
|
25
|
+
writeFileSync(exclude, `${prefix}${RUNTIME_IGNORE}\n`);
|
|
26
|
+
} catch { /* best effort: an unignored lock only adds noise to the audit */ }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Git audit layer for a dream run: one commit before (baseline) and one after (dream),
|
|
31
|
+
* so the human gate reviews `git show` instead of trusting a report, and rollback is
|
|
32
|
+
* `git revert`. The caller decides how loud a failure is; this function only reports it.
|
|
33
|
+
* A clean tree on an established repository commits nothing; a repository with no HEAD
|
|
34
|
+
* gets an empty baseline commit, because an audit run with no snapshot is not a success.
|
|
35
|
+
*/
|
|
36
|
+
export function gitCommit(home: string, message: string): AuditResult {
|
|
37
|
+
try {
|
|
38
|
+
if (!existsSync(join(home, ".git"))) {
|
|
39
|
+
execFileSync("git", ["init", "-q"], { cwd: home, stdio: "ignore" });
|
|
40
|
+
}
|
|
41
|
+
ensureRuntimeIgnored(home);
|
|
42
|
+
execFileSync("git", ["add", "-A"], { cwd: home, stdio: "ignore" });
|
|
43
|
+
let clean = false;
|
|
44
|
+
try {
|
|
45
|
+
execFileSync("git", ["diff", "--cached", "--quiet"], { cwd: home, stdio: "ignore" });
|
|
46
|
+
clean = true; // clean tree — no empty commit on an established repository
|
|
47
|
+
} catch { clean = false; }
|
|
48
|
+
const before = headCommit(home);
|
|
49
|
+
if (!clean) {
|
|
50
|
+
execFileSync("git", ["commit", "-q", "-m", message], { cwd: home, stdio: "ignore" });
|
|
51
|
+
console.log(`git: committed "${message}"`);
|
|
52
|
+
} else if (before === undefined) {
|
|
53
|
+
// A newly initialized repository has no snapshot at all; give the audit one.
|
|
54
|
+
execFileSync("git", ["commit", "-q", "--allow-empty", "-m", message], { cwd: home, stdio: "ignore" });
|
|
55
|
+
console.log(`git: committed "${message}"`);
|
|
56
|
+
}
|
|
57
|
+
const commit = headCommit(home);
|
|
58
|
+
if (commit === undefined) return { ok: false, error: "audit commit produced no snapshot (no HEAD)" };
|
|
59
|
+
return { ok: true, commit, empty: clean };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
62
|
+
console.log(`git audit layer failed: ${reason}`);
|
|
63
|
+
return { ok: false, error: reason };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** HEAD sha, or undefined when the repository has no commit yet. */
|
|
68
|
+
function headCommit(home: string): string | undefined {
|
|
69
|
+
try {
|
|
70
|
+
const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: home, encoding: "utf8" }).trim();
|
|
71
|
+
return head.length > 0 ? head : undefined;
|
|
72
|
+
} catch { return undefined; }
|
|
73
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
|
|
5
|
+
function isOutside(notesHome: string, target: string): boolean {
|
|
6
|
+
const fromHome = relative(notesHome, target);
|
|
7
|
+
return fromHome === ".." || fromHome.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(fromHome);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export async function jailWritePath(notesHome: string, path: string, options: { createParent?: boolean } = {}): Promise<string> {
|
|
11
|
+
let realNotesHome: string;
|
|
12
|
+
try {
|
|
13
|
+
realNotesHome = await realpath(notesHome);
|
|
14
|
+
} catch {
|
|
15
|
+
throw new Error(`write jail: cannot resolve notes home ${notesHome}`);
|
|
16
|
+
}
|
|
17
|
+
const target = resolve(realNotesHome, path);
|
|
18
|
+
const targetParent = dirname(target);
|
|
19
|
+
if (isOutside(realNotesHome, targetParent)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
|
|
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) await mkdir(targetParent, { recursive: true });
|
|
24
|
+
let realTargetParent: string;
|
|
25
|
+
try {
|
|
26
|
+
realTargetParent = await realpath(targetParent);
|
|
27
|
+
} catch {
|
|
28
|
+
throw new Error(`write jail: cannot resolve target parent in notes home ${notesHome}`);
|
|
29
|
+
}
|
|
30
|
+
if (isOutside(realNotesHome, realTargetParent)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
|
|
31
|
+
let targetStats;
|
|
32
|
+
try {
|
|
33
|
+
targetStats = await lstat(target);
|
|
34
|
+
} catch (error: any) {
|
|
35
|
+
if (error.code !== "ENOENT") throw new Error(`write jail: cannot inspect target in notes home ${notesHome}`);
|
|
36
|
+
}
|
|
37
|
+
if (targetStats?.isSymbolicLink()) {
|
|
38
|
+
let realTarget: string;
|
|
39
|
+
try {
|
|
40
|
+
realTarget = await realpath(target);
|
|
41
|
+
} catch {
|
|
42
|
+
throw new Error(`write jail: cannot resolve target in notes home ${notesHome}`);
|
|
43
|
+
}
|
|
44
|
+
if (isOutside(realNotesHome, realTarget)) throw new Error(`write jail: ${path} is outside notes home ${notesHome}`);
|
|
45
|
+
}
|
|
46
|
+
if (targetStats && targetStats.nlink > 1) throw new Error(`write jail: ${path} has hard links and is not allowed in notes home ${notesHome}`);
|
|
47
|
+
return target;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Physical deletion refuses live notes even before playbook policy is consulted. */
|
|
51
|
+
export async function deleteCrumpledNote(notesHome: string, path: string) {
|
|
52
|
+
const target = await jailWritePath(notesHome, path, { createParent: false });
|
|
53
|
+
let raw: string;
|
|
54
|
+
try {
|
|
55
|
+
raw = await readFile(target, "utf8");
|
|
56
|
+
} catch (error: any) {
|
|
57
|
+
throw new Error(`delete: cannot read ${path} in notes home: ${error.message}`);
|
|
58
|
+
}
|
|
59
|
+
if (parseNote(raw).meta.crumpledAt === undefined) throw new Error(`delete: ${path} is not a crumpled note; only the wastebasket rule permits deletion`);
|
|
60
|
+
await unlink(target);
|
|
61
|
+
return { content: [{ type: "text" as const, text: `deleted ${path}` }], details: undefined };
|
|
62
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
|
|
3
|
+
|
|
4
|
+
export type LockState = {
|
|
5
|
+
path: string;
|
|
6
|
+
held: boolean;
|
|
7
|
+
reason?: string;
|
|
8
|
+
startedAt: number;
|
|
9
|
+
/** mtime of the last-run sidecar before this run took the lock; failLock restores it. */
|
|
10
|
+
priorStampMtime?: number;
|
|
11
|
+
/** Random identity written into the lock file; cleanup only removes the lock it wrote. */
|
|
12
|
+
token?: string;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The scheduler's last-run timestamp lives in a sidecar beside the lock, never in the
|
|
17
|
+
* lock file itself: acquiring, releasing or cleaning up the lock touches only the PID
|
|
18
|
+
* marker, so lock lifecycle does not destroy the timestamp the time gate reads.
|
|
19
|
+
*/
|
|
20
|
+
export function lastRunPath(lockPath: string): string {
|
|
21
|
+
return `${lockPath}.last-run`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function readText(path: string): string | undefined {
|
|
25
|
+
try { return readFileSync(path, "utf8"); } catch { return undefined; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function stampMtime(stampPath: string): number | undefined {
|
|
29
|
+
try { return statSync(stampPath).mtimeMs; } catch { return undefined; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Cleanup ownership: only the exact marker this run wrote may be removed. The token is
|
|
34
|
+
* diagnostic and guards cleanup; it never grants permission to take an existing lock.
|
|
35
|
+
*/
|
|
36
|
+
function ownsLock(lock: LockState): boolean {
|
|
37
|
+
if (!lock.held || !lock.token) return false;
|
|
38
|
+
return readText(lock.path)?.trim() === `${process.pid} ${lock.token}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Acquire the dream lock with Git-style exclusive existence locking: one O_CREAT|O_EXCL
|
|
43
|
+
* creation. An existing path refuses acquisition regardless of its contents, PID, or age,
|
|
44
|
+
* and is never read for permission, replaced, or removed. There is no automatic stale
|
|
45
|
+
* recovery; a crash-left lock is human cleanup after confirming no dream is running.
|
|
46
|
+
*/
|
|
47
|
+
export function acquireLock(path: string): LockState {
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
const priorStampMtime = stampMtime(lastRunPath(path));
|
|
50
|
+
const token = randomUUID();
|
|
51
|
+
try {
|
|
52
|
+
writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
|
|
53
|
+
} catch {
|
|
54
|
+
return { path, held: false, reason: "lock gate: lock already exists", startedAt: now };
|
|
55
|
+
}
|
|
56
|
+
// Only a held lock advances the scheduler timestamp.
|
|
57
|
+
try { writeFileSync(lastRunPath(path), new Date(now).toISOString()); } catch { /* advisory */ }
|
|
58
|
+
return { path, held: true, startedAt: now, priorStampMtime, token };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Release only the lock this run acquired. Idempotent: repeated cleanup does nothing. */
|
|
62
|
+
export function releaseLock(lock: LockState): void {
|
|
63
|
+
if (!lock.held) return;
|
|
64
|
+
if (ownsLock(lock)) { try { unlinkSync(lock.path); } catch { /* best effort */ } }
|
|
65
|
+
lock.held = false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* A failed run must not advance the scheduler: restore the previous timestamp, or remove
|
|
70
|
+
* the one this run wrote when there was none. Only this run's own marker is removed, and
|
|
71
|
+
* the state is marked released so a later cleanup attempt is harmless.
|
|
72
|
+
*/
|
|
73
|
+
export function failLock(lock: LockState): void {
|
|
74
|
+
if (!lock.held) return;
|
|
75
|
+
if (ownsLock(lock)) {
|
|
76
|
+
const stampPath = lastRunPath(lock.path);
|
|
77
|
+
if (lock.priorStampMtime === undefined) { try { unlinkSync(stampPath); } catch { /* best effort */ } }
|
|
78
|
+
else { try { utimesSync(stampPath, new Date(), new Date(lock.priorStampMtime)); } catch { /* best effort */ } }
|
|
79
|
+
try { unlinkSync(lock.path); } catch { /* best effort */ }
|
|
80
|
+
}
|
|
81
|
+
lock.held = false;
|
|
82
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { gitCommit } from "./git.js";
|
|
4
|
+
import type { DreamWrite } from "./result.js";
|
|
5
|
+
|
|
6
|
+
function writeList(writes: DreamWrite[]): string {
|
|
7
|
+
return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Best-effort text write; returns the failure message instead of throwing. */
|
|
11
|
+
function writeText(path: string, content: string): string | undefined {
|
|
12
|
+
try { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, content); return undefined; }
|
|
13
|
+
catch (error) { return error instanceof Error ? error.message : String(error); }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function appendText(path: string, content: string): string | undefined {
|
|
17
|
+
try { appendFileSync(path, content); return undefined; }
|
|
18
|
+
catch (error) { return error instanceof Error ? error.message : String(error); }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Close one dream: record the report, then run the final audit commit. The audit always
|
|
23
|
+
* runs even when the report cannot be written, and a failed audit is appended to the
|
|
24
|
+
* report (when it exists) as well as named on stderr, so neither failure hides the other.
|
|
25
|
+
*/
|
|
26
|
+
export function finishDream(home: string, stamp: string, reportPath: string, failed: boolean, body: string, writes: DreamWrite[]): number {
|
|
27
|
+
const header = failed ? `# Dream ${stamp} (failed)` : `# Dream ${stamp}`;
|
|
28
|
+
let reportError = writeText(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`);
|
|
29
|
+
const audit = gitCommit(home, `dream ${stamp}${failed ? " (failed)" : ""}`);
|
|
30
|
+
if (!audit.ok) {
|
|
31
|
+
console.error(`dream: final audit failed: ${audit.error}`);
|
|
32
|
+
reportError ??= appendText(reportPath, `\n## Final audit failed\n\n${audit.error}\n`);
|
|
33
|
+
}
|
|
34
|
+
if (reportError) console.error(`dream: could not write report at ${reportPath}: ${reportError}`);
|
|
35
|
+
return failed || !audit.ok || reportError !== undefined ? 1 : 0;
|
|
36
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { NOTESOUP_DREAMER_KEY, NOTESOUP_SETTINGS_KEY, type NotesoupSettings } from "../settings.js";
|
|
2
|
+
|
|
3
|
+
export type DreamerSetting = { pattern?: string; 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 function deriveDreamer(settings: NotesoupSettings): DreamerSetting {
|
|
10
|
+
const raw = settings.dreamer;
|
|
11
|
+
if (raw === undefined) 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
|
+
}
|