notesoup 0.51.8 → 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 (78) 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 +27 -7
  5. package/dist/plugins/pi/render.d.ts +40 -0
  6. package/dist/plugins/pi/render.js +168 -0
  7. package/dist/plugins/pi/runtime.js +3 -0
  8. package/dist/plugins/pi/tool-result.d.ts +5 -2
  9. package/dist/plugins/pi/tool-result.js +4 -1
  10. package/dist/src/dream/git.d.ts +2 -3
  11. package/dist/src/dream/git.js +3 -8
  12. package/dist/src/dream/lock.d.ts +10 -27
  13. package/dist/src/dream/lock.js +16 -79
  14. package/dist/src/notes/errors.d.ts +1 -1
  15. package/dist/src/notes/identity.d.ts +2 -0
  16. package/dist/src/notes/identity.js +3 -1
  17. package/dist/src/notes/store.d.ts +2 -0
  18. package/dist/src/notes/store.js +40 -4
  19. package/dist/src/tools/dream.d.ts +113 -0
  20. package/dist/src/tools/dream.js +112 -0
  21. package/dist/src/tools/notes.d.ts +15 -1
  22. package/dist/src/tools/notes.js +4 -4
  23. package/dist/test/claude-history.test.js +18 -2
  24. package/dist/test/claude-mod.test.js +115 -30
  25. package/dist/test/dependencies.test.js +3 -6
  26. package/dist/test/dream-skill.test.js +2 -3
  27. package/dist/test/dream-tools.test.js +67 -0
  28. package/dist/test/pi-render.test.js +89 -0
  29. package/docs/claude-code-mod.md +1 -1
  30. package/docs/notes-library.md +1 -1
  31. package/docs/skills.md +12 -15
  32. package/package.json +151 -149
  33. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  34. package/plugins/claude/dist/claude/helper.js +30 -22
  35. package/plugins/claude/hooks/register.ts +52 -33
  36. package/plugins/claude/src/history.ts +3 -6
  37. package/plugins/pi/notes/tools.ts +26 -8
  38. package/plugins/pi/render.ts +165 -0
  39. package/plugins/pi/runtime.ts +3 -0
  40. package/plugins/pi/tool-result.ts +9 -1
  41. package/src/dream/git.ts +3 -8
  42. package/src/dream/lock.ts +18 -66
  43. package/src/notes/errors.ts +1 -1
  44. package/src/notes/identity.ts +4 -1
  45. package/src/notes/store.ts +37 -4
  46. package/src/tools/dream.ts +112 -0
  47. package/src/tools/notes.ts +4 -4
  48. package/dist/plugins/pi/dream/cli.d.ts +0 -10
  49. package/dist/plugins/pi/dream/cli.js +0 -173
  50. package/dist/plugins/pi/dream/runner.d.ts +0 -27
  51. package/dist/plugins/pi/dream/runner.js +0 -91
  52. package/dist/plugins/pi/dream/settings.d.ts +0 -7
  53. package/dist/plugins/pi/dream/settings.js +0 -17
  54. package/dist/src/dream/doctor.d.ts +0 -2
  55. package/dist/src/dream/doctor.js +0 -161
  56. package/dist/src/dream/gates.d.ts +0 -10
  57. package/dist/src/dream/gates.js +0 -26
  58. package/dist/src/dream/jail.d.ts +0 -11
  59. package/dist/src/dream/jail.js +0 -71
  60. package/dist/src/dream/report.d.ts +0 -7
  61. package/dist/src/dream/report.js +0 -34
  62. package/dist/src/dream/result.d.ts +0 -9
  63. package/dist/src/dream/settings.d.ts +0 -9
  64. package/dist/src/dream/settings.js +0 -16
  65. package/dist/test/doctor.test.js +0 -37
  66. package/dist/test/dream.test.d.ts +0 -1
  67. package/dist/test/dream.test.js +0 -150
  68. package/plugins/pi/dream/cli.ts +0 -118
  69. package/plugins/pi/dream/runner.ts +0 -92
  70. package/plugins/pi/dream/settings.ts +0 -17
  71. package/src/dream/doctor.ts +0 -118
  72. package/src/dream/gates.ts +0 -26
  73. package/src/dream/jail.ts +0 -62
  74. package/src/dream/report.ts +0 -32
  75. package/src/dream/result.ts +0 -2
  76. package/src/dream/settings.ts +0 -19
  77. /package/dist/{src/dream/result.js → test/dream-tools.test.d.ts} +0 -0
  78. /package/dist/test/{doctor.test.d.ts → pi-render.test.d.ts} +0 -0
@@ -22,7 +22,7 @@ const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@pr
22
22
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
23
23
  * Convert expected refusals; unexpected errors propagate unchanged.
24
24
  */
25
- function failureOf(error: unknown): Outcome<never> {
25
+ export function failureOf(error: unknown): Outcome<never> {
26
26
  if (error instanceof NoteError) return failure(error.code, error.message);
27
27
  // Address, glob, and query guards raise declared types; nothing else is converted.
28
28
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
@@ -169,7 +169,7 @@ export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
169
169
  type Snapshot<T> = Omit<NotesListData, "files"> & { files: T[] };
170
170
 
171
171
  /** Keep identities intact. Only search previews may shrink to make the first row fit. */
172
- function snapshot<T extends { address: string }>(
172
+ export function snapshot<T extends { address: string }>(
173
173
  rows: T[],
174
174
  limit: number | undefined,
175
175
  status: NoteQueryStatus,
@@ -196,7 +196,7 @@ function snapshot<T extends { address: string }>(
196
196
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
197
197
  }
198
198
 
199
- function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
199
+ export function listedFile(row: Pick<NoteRow, "address" | "meta">, identity: NotesIdentity): NotesListData["files"][number] {
200
200
  return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
201
201
  }
202
202
 
@@ -300,7 +300,7 @@ export const notesRead = {
300
300
 
301
301
  export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, crumpled: CRUMPLED_LIST_PARAMETER }, { additionalProperties: false });
302
302
 
303
- function renderListData(data: NotesListData): string {
303
+ export function renderListData(data: NotesListData): string {
304
304
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
305
305
  for (const file of data.files) {
306
306
  lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env node
2
- import type { DreamerSetting } from "../../../src/dream/settings.js";
3
- import { runDreamer, type DreamerSessionFactory } from "./runner.js";
4
- /** Injection seams used by tests; production uses the defaults. */
5
- export type DreamDependencies = {
6
- sessionFactory?: DreamerSessionFactory;
7
- dreamerSettings?: (cwd?: string) => DreamerSetting;
8
- runDreamer?: typeof runDreamer;
9
- };
10
- export declare function main(argv?: string[], deps?: DreamDependencies): Promise<number>;
@@ -1,173 +0,0 @@
1
- #!/usr/bin/env node
2
- import { finishDream } from "../../../src/dream/report.js";
3
- import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
4
- import { dirname, join, resolve } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { acquireLock, failLock, lastRunPath, releaseLock } from "../../../src/dream/lock.js";
7
- import { materialGate, timeGate } from "../../../src/dream/gates.js";
8
- import { runDreamer } from "./runner.js";
9
- import { gitCommit } from "../../../src/dream/git.js";
10
- import { readDreamerSettings } from "./settings.js";
11
- import { doctor } from "../../../src/dream/doctor.js";
12
- import { notesRoot } from "../notes/adapter.js";
13
- import { errorMessage } from "../../../src/error-message.js";
14
- function args(argv) { const out = {}; for (let i = 0; i < argv.length; i++) {
15
- const a = argv[i];
16
- if (a === "--force" || a === "--help")
17
- out[a.slice(2)] = true;
18
- else if (a.startsWith("--"))
19
- out[a.slice(2)] = argv[++i] ?? "";
20
- } return out; }
21
- /** A positive whole-number flag, or undefined when the value is not one. */
22
- function wholeNumberArg(raw) {
23
- if (raw === undefined)
24
- return undefined;
25
- if (typeof raw !== "string" || raw.trim() === "")
26
- return undefined;
27
- const value = Number(raw);
28
- return Number.isInteger(value) && value > 0 ? value : undefined;
29
- }
30
- /** A directory flag that must carry a real path, not a missing or flag-looking value. */
31
- function directoryArg(raw) {
32
- if (raw === undefined)
33
- return undefined;
34
- if (typeof raw !== "string" || raw.trim() === "" || raw.startsWith("--"))
35
- return undefined;
36
- return raw;
37
- }
38
- function packageRoot() {
39
- let dir = dirname(fileURLToPath(import.meta.url));
40
- while (true) {
41
- if (existsSync(join(dir, "package.json")))
42
- return dir;
43
- const parent = dirname(dir);
44
- if (parent === dir)
45
- throw new Error("could not locate installed package root");
46
- dir = parent;
47
- }
48
- }
49
- export async function main(argv = process.argv.slice(2), deps = {}) {
50
- if (argv[0] === "doctor") {
51
- const options = args(argv.slice(1));
52
- if (options.help) {
53
- console.log("dream doctor [--notes-home <dir>] — read-only diagnostics; no model or repairs");
54
- return 0;
55
- }
56
- const home = directoryArg(options["notes-home"]);
57
- if (options["notes-home"] !== undefined && home === undefined) {
58
- console.error("dream: --notes-home needs a directory path");
59
- return 1;
60
- }
61
- const root = resolve(home ?? notesRoot());
62
- const issues = doctor(root);
63
- console.log(issues.length ? issues.join("\n") : `dream doctor: OK (${root})`);
64
- return issues.length ? 1 : 0;
65
- }
66
- const a = args(argv);
67
- if (a.help) {
68
- 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.");
69
- return 0;
70
- }
71
- // Validate every value flag before anything is created or gated on: a typo must refuse
72
- // loudly instead of reading as "the last dream is too recent" and exiting successfully.
73
- const homeArg = directoryArg(a["notes-home"]);
74
- const minHours = wholeNumberArg(a["min-hours"]);
75
- const minSessions = wholeNumberArg(a["min-sessions"]);
76
- const badArg = a["notes-home"] !== undefined && homeArg === undefined ? "--notes-home needs a directory path"
77
- : a["min-hours"] !== undefined && minHours === undefined ? "--min-hours needs a positive whole number"
78
- : a["min-sessions"] !== undefined && minSessions === undefined ? "--min-sessions needs a positive whole number"
79
- : undefined;
80
- if (badArg) {
81
- console.error(`dream: ${badArg}`);
82
- return 1;
83
- }
84
- const home = resolve(homeArg ?? notesRoot());
85
- process.env.NOTESOUP_HOME = home;
86
- mkdirSync(home, { recursive: true });
87
- const lockPath = join(home, ".dream.lock");
88
- const stampPath = lastRunPath(lockPath);
89
- const time = timeGate(stampPath, minHours ?? 24);
90
- console.log(time.reason);
91
- if (!a.force && !time.ok)
92
- return 0;
93
- const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
94
- const material = materialGate(home, since, minSessions ?? 3);
95
- console.log(material.reason);
96
- if (!a.force && !material.ok)
97
- return 0;
98
- let lock;
99
- try {
100
- lock = acquireLock(lockPath);
101
- }
102
- catch (e) {
103
- console.log(`lock gate: ${errorMessage(e)}`);
104
- return 0;
105
- }
106
- if (!lock.held) {
107
- console.log(lock.reason);
108
- return 0;
109
- }
110
- const stamp = new Date(lock.startedAt).toISOString().replace(/[:.]/g, "-");
111
- const reportPath = join(home, "dreams", `${stamp}.md`);
112
- let succeeded = false;
113
- try {
114
- // CLI --dreamer wins over settings; settings win over the automatic model fallback.
115
- let modelPattern;
116
- if (a.dreamer)
117
- modelPattern = String(a.dreamer);
118
- else {
119
- const settings = (deps.dreamerSettings ?? readDreamerSettings)();
120
- for (const warning of settings.warnings)
121
- console.error(warning);
122
- modelPattern = settings.pattern;
123
- }
124
- // The baseline snapshot is required: without it the human gate has nothing to inspect.
125
- const baseline = gitCommit(home, `baseline ${stamp}`);
126
- if (!baseline.ok) {
127
- console.error(`dream: baseline audit failed: ${baseline.error}`);
128
- return 1;
129
- }
130
- const defaultBook = join(packageRoot(), "playbook.md");
131
- const playbookPath = String(a.playbook ?? defaultBook);
132
- let result;
133
- try {
134
- const playbook = readFileSync(playbookPath, "utf8");
135
- result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
136
- }
137
- catch (e) {
138
- const message = errorMessage(e);
139
- console.error(message);
140
- return finishDream(home, stamp, reportPath, true, message, []);
141
- }
142
- if (result.error) {
143
- console.error(result.error);
144
- return finishDream(home, stamp, reportPath, true, result.error, result.writes);
145
- }
146
- const code = finishDream(home, stamp, reportPath, false, result.report, result.writes);
147
- if (code === 0) {
148
- succeeded = true;
149
- console.log(reportPath);
150
- }
151
- return code;
152
- }
153
- finally {
154
- // Only the holder's own lock is released; a successor's lock is never touched.
155
- if (succeeded)
156
- releaseLock(lock);
157
- else
158
- failLock(lock);
159
- }
160
- }
161
- function isEntryPoint() {
162
- const entry = process.argv[1];
163
- if (!entry)
164
- return false;
165
- try {
166
- return realpathSync(resolve(entry)) === realpathSync(fileURLToPath(import.meta.url));
167
- }
168
- catch {
169
- return false;
170
- }
171
- }
172
- if (isEntryPoint())
173
- main().then((code) => { process.exitCode = code; });
@@ -1,27 +0,0 @@
1
- import type { DreamResult } from "../../../src/dream/result.js";
2
- import { type AgentSession, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
- export type DreamerSession = Pick<AgentSession, "prompt" | "subscribe" | "dispose">;
4
- export type DreamerSessionFactory = (options: {
5
- cwd: string;
6
- modelPattern?: string;
7
- tools: string[];
8
- }) => Promise<DreamerSession>;
9
- export declare const DREAMER_TOOLS: string[];
10
- /** The dream session's custom definitions: jailed versions of the two write built-ins, plus the jailed delete below. */
11
- export declare function dreamerWriteToolDefinitions(notesHome: string): ToolDefinition<any, any, any>[];
12
- /**
13
- * The dreamer's physical delete, jailed like the writes and restricted to crumpled notes: the
14
- * playbook's wastebasket rule is the only legitimate target, so a live note refuses here even
15
- * before policy is consulted. The time window itself stays playbook policy, not tool law.
16
- */
17
- export declare function dreamerDeleteToolDefinition(notesHome: string): ToolDefinition<any, any, any>;
18
- export declare const defaultDreamerSessionFactory: DreamerSessionFactory;
19
- /**
20
- * Run one dream turn. A dreamer failure is returned as `error` together with the partial
21
- * writes observed so far, so the caller can record partial state instead of losing it;
22
- * only a failure to even start the session throws.
23
- */
24
- export declare function runDreamer(playbook: string, cwd: string, options?: {
25
- modelPattern?: string;
26
- sessionFactory?: DreamerSessionFactory;
27
- }): Promise<DreamResult>;
@@ -1,91 +0,0 @@
1
- import { jailWritePath, deleteCrumpledNote } from "../../../src/dream/jail.js";
2
- import { createAgentSession, createEditToolDefinition, createWriteToolDefinition, ModelRuntime, resolveModelScopeWithDiagnostics, SessionManager } from "@earendil-works/pi-coding-agent";
3
- import { Type } from "@earendil-works/pi-ai";
4
- import { contentText } from "../../../src/history/history.js";
5
- import { errorMessage } from "../../../src/error-message.js";
6
- export const DREAMER_TOOLS = ["read", "grep", "find", "ls", "write", "edit"];
7
- function jailToolDefinition(definition, notesHome) {
8
- const execute = definition.execute;
9
- return {
10
- ...definition,
11
- async execute(toolCallId, params, signal, onUpdate, ctx) {
12
- await jailWritePath(notesHome, params.path);
13
- return execute(toolCallId, params, signal, onUpdate, ctx);
14
- },
15
- };
16
- }
17
- /** The dream session's custom definitions: jailed versions of the two write built-ins, plus the jailed delete below. */
18
- export function dreamerWriteToolDefinitions(notesHome) {
19
- return [
20
- jailToolDefinition(createWriteToolDefinition(notesHome), notesHome),
21
- jailToolDefinition(createEditToolDefinition(notesHome), notesHome),
22
- ];
23
- }
24
- const DELETE_PARAMETERS = Type.Object({ path: Type.String({ description: "Path of the crumpled note file, relative to the notes home." }) }, { additionalProperties: false });
25
- /**
26
- * The dreamer's physical delete, jailed like the writes and restricted to crumpled notes: the
27
- * playbook's wastebasket rule is the only legitimate target, so a live note refuses here even
28
- * before policy is consulted. The time window itself stays playbook policy, not tool law.
29
- */
30
- export function dreamerDeleteToolDefinition(notesHome) {
31
- return {
32
- name: "delete",
33
- label: "delete",
34
- 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.",
35
- parameters: DELETE_PARAMETERS,
36
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
37
- return deleteCrumpledNote(notesHome, params.path);
38
- },
39
- };
40
- }
41
- export const defaultDreamerSessionFactory = async ({ cwd, modelPattern, tools }) => {
42
- let model;
43
- if (modelPattern) {
44
- const runtime = await ModelRuntime.create({ allowModelNetwork: false, refreshOnCreate: false });
45
- const result = await resolveModelScopeWithDiagnostics([modelPattern], runtime);
46
- model = result.scopedModels[0]?.model;
47
- if (!model)
48
- throw new Error(`dreamer model pattern "${modelPattern}" did not resolve to an available model`);
49
- }
50
- const { session } = await createAgentSession({ cwd, sessionManager: SessionManager.inMemory(cwd), tools, customTools: [...dreamerWriteToolDefinitions(cwd), dreamerDeleteToolDefinition(cwd)], noTools: "all", model, thinkingLevel: "off" });
51
- return session;
52
- };
53
- /**
54
- * Run one dream turn. A dreamer failure is returned as `error` together with the partial
55
- * writes observed so far, so the caller can record partial state instead of losing it;
56
- * only a failure to even start the session throws.
57
- */
58
- export async function runDreamer(playbook, cwd, options = {}) {
59
- const session = await (options.sessionFactory ?? defaultDreamerSessionFactory)({ cwd, modelPattern: options.modelPattern, tools: DREAMER_TOOLS });
60
- let answer = "";
61
- let providerError;
62
- const writes = [];
63
- const unsubscribe = session.subscribe((event) => {
64
- const tool = event.toolName ?? event.tool?.name;
65
- const args = event.args ?? event.arguments ?? event.tool?.arguments;
66
- if ((tool === "write" || tool === "edit" || tool === "delete") && args && typeof args === "object" && typeof args.path === "string")
67
- writes.push({ tool, path: args.path });
68
- if (event.type !== "message_end" || event.message?.role !== "assistant")
69
- return;
70
- if (event.message.stopReason === "error") {
71
- providerError = event.message.errorMessage ?? "unknown provider error";
72
- return;
73
- }
74
- answer = contentText(event.message.content);
75
- });
76
- try {
77
- try {
78
- await session.prompt(playbook);
79
- }
80
- catch (error) {
81
- return { report: answer, writes, error: errorMessage(error) };
82
- }
83
- if (providerError)
84
- return { report: answer, writes, error: `dreamer failed: ${providerError}` };
85
- return { report: answer, writes };
86
- }
87
- finally {
88
- unsubscribe?.();
89
- session.dispose();
90
- }
91
- }
@@ -1,7 +0,0 @@
1
- import { type DreamerSetting } from "../../../src/dream/settings.js";
2
- /**
3
- * Resolve the configurable dreamer model from Pi settings for a CLI invocation: global
4
- * `~/.pi/agent/settings.json` merged with the project's `.pi/settings.json`, project
5
- * values winning per key. A settings read failure degrades to no pattern with one warning.
6
- */
7
- export declare function readDreamerSettings(cwd?: string): DreamerSetting;
@@ -1,17 +0,0 @@
1
- import { deriveDreamer } from "../../../src/dream/settings.js";
2
- import { SettingsManager } from "@earendil-works/pi-coding-agent";
3
- import { mergeNotesoupSettings } from "../../../src/settings.js";
4
- /**
5
- * Resolve the configurable dreamer model from Pi settings for a CLI invocation: global
6
- * `~/.pi/agent/settings.json` merged with the project's `.pi/settings.json`, project
7
- * values winning per key. A settings read failure degrades to no pattern with one warning.
8
- */
9
- export function readDreamerSettings(cwd = process.cwd()) {
10
- try {
11
- const settingsManager = SettingsManager.create(cwd, undefined, { projectTrusted: true });
12
- return deriveDreamer(mergeNotesoupSettings(settingsManager.getGlobalSettings(), settingsManager.getProjectSettings()));
13
- }
14
- catch (error) {
15
- return { warnings: [`notesoup: could not read settings; using the automatic dreamer model (${String(error)}).`] };
16
- }
17
- }
@@ -1,2 +0,0 @@
1
- /** Read-only diagnostics. Never follows symlinks or acquires/removes a dream lock. */
2
- export declare function doctor(home: string): string[];
@@ -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;