notesoup 0.51.9 → 0.52.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -10
- package/dist/plugins/claude/src/history.js +3 -7
- 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/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/notes.d.ts +15 -1
- package/dist/src/tools/notes.js +4 -4
- package/dist/test/claude-history.test.js +18 -2
- package/dist/test/claude-mod.test.js +115 -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 +1 -1
- 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 +30 -22
- package/plugins/claude/hooks/register.ts +52 -33
- package/plugins/claude/src/history.ts +3 -6
- 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/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/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
package/src/notes/identity.ts
CHANGED
|
@@ -8,6 +8,8 @@ export type NotesIdentity = Readonly<{
|
|
|
8
8
|
projectKey: string;
|
|
9
9
|
agent: string;
|
|
10
10
|
model: string;
|
|
11
|
+
/** Project slug being dreamed over: its named project and session notes become writable, and reads leave no access stamp. */
|
|
12
|
+
dreaming?: string;
|
|
11
13
|
}>;
|
|
12
14
|
|
|
13
15
|
function requireString(field: string, value: unknown): string {
|
|
@@ -27,6 +29,7 @@ export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
|
|
|
27
29
|
if (!SLUG_PATTERN.test(projectKey)) throw new TypeError("notes context projectKey must be a canonical lowercase slug");
|
|
28
30
|
if (!SLUG_PATTERN.test(agent)) throw new TypeError("notes context agent must be a canonical lowercase slug");
|
|
29
31
|
if (!SLUG_PATTERN.test(model)) throw new TypeError("notes context model must be a canonical lowercase slug");
|
|
32
|
+
if (value.dreaming !== undefined && !SLUG_PATTERN.test(value.dreaming)) throw new TypeError("notes context dreaming must be a canonical lowercase slug");
|
|
30
33
|
const home = resolve(homeValue);
|
|
31
|
-
return Object.freeze({ home, sessionId, projectKey, agent, model });
|
|
34
|
+
return Object.freeze({ home, sessionId, projectKey, agent, model, ...(value.dreaming === undefined ? {} : { dreaming: value.dreaming }) });
|
|
32
35
|
}
|
package/src/notes/store.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import type { Dirent } from "node:fs";
|
|
3
|
-
import { mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { mkdir, readdir, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
5
5
|
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
6
6
|
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
|
|
@@ -59,6 +59,8 @@ export interface NotesStore {
|
|
|
59
59
|
read(address: string): Promise<NoteReadResult | undefined>;
|
|
60
60
|
update(address: string, edits?: EditOperation[], options?: EditOptions): Promise<NoteEditResult>;
|
|
61
61
|
rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult>;
|
|
62
|
+
/** Physically delete one crumpled note; only a dreaming identity may call it. */
|
|
63
|
+
forget(address: string): Promise<NoteMeta>;
|
|
62
64
|
list(options?: NotesQuery): Promise<NoteRow[]>;
|
|
63
65
|
search(queries: string[], options?: NotesQuery): Promise<NoteSearchRow[]>;
|
|
64
66
|
listWithStatus(options?: NotesQuery): Promise<NoteQueryResult<NoteRow>>;
|
|
@@ -253,9 +255,11 @@ function frontmatterOf(meta: NoteMeta): string {
|
|
|
253
255
|
return serializeNote(meta, "").slice(0, -2);
|
|
254
256
|
}
|
|
255
257
|
|
|
256
|
-
/** Explicit session/project homes are
|
|
258
|
+
/** Explicit session/project homes are read-only unless dreamed over; agent/model homes allow their owner. */
|
|
257
259
|
function assertWritableHome(scope: Scope, who: string | undefined, identity: NotesIdentity): void {
|
|
258
260
|
if (who === undefined) return;
|
|
261
|
+
// A dreamed project is writable whole; its other sessions are checked per note by assertDreamSessionNote.
|
|
262
|
+
if (identity.dreaming !== undefined && (scope === "session" || (scope === "project" && who === identity.dreaming))) return;
|
|
259
263
|
if (scope === "session") throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
|
|
260
264
|
if (scope === "project") throw new NoteError("invalid_scope", `@projects/${who}/ is read-only; use @project/ to write to your own project.`);
|
|
261
265
|
const current = scope === "agent" ? identity.agent : identity.model;
|
|
@@ -264,6 +268,15 @@ function assertWritableHome(scope: Scope, who: string | undefined, identity: Not
|
|
|
264
268
|
throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
|
|
265
269
|
}
|
|
266
270
|
|
|
271
|
+
/** A dream reaches another session's note only when that note was born in the dreamed project. */
|
|
272
|
+
function assertDreamSessionNote(scope: Scope, who: string | undefined, identity: NotesIdentity, raw: string | undefined, address: string): void {
|
|
273
|
+
if (scope !== "session" || who === undefined || identity.dreaming === undefined) return;
|
|
274
|
+
if (raw !== undefined && parseNote(raw).meta.project === identity.dreaming) return;
|
|
275
|
+
throw new NoteError("invalid_scope", raw === undefined
|
|
276
|
+
? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.`
|
|
277
|
+
: `${address} belongs to another project, not the one being dreamed over (${identity.dreaming}).`);
|
|
278
|
+
}
|
|
279
|
+
|
|
267
280
|
/** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
|
|
268
281
|
export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
269
282
|
const identity = snapshotNotesIdentity(input);
|
|
@@ -282,6 +295,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
282
295
|
const now = writeStamp();
|
|
283
296
|
const cleanBody = stripLeadingFrontmatter(content);
|
|
284
297
|
const existingRaw = await readFileIfExists(path);
|
|
298
|
+
assertDreamSessionNote(scope, destination.who, identity, existingRaw, address);
|
|
285
299
|
const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
|
|
286
300
|
const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
|
|
287
301
|
const meta: NoteMeta = existing ?? {
|
|
@@ -313,7 +327,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
313
327
|
if (raw === undefined) return undefined;
|
|
314
328
|
const now = Date.now();
|
|
315
329
|
const parsed = parseNote(raw, now);
|
|
316
|
-
|
|
330
|
+
// Named homes, and every read during a dream, leave no access stamp.
|
|
331
|
+
if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined)) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
|
|
317
332
|
// A read records its own access, exactly as a write records an edit.
|
|
318
333
|
const meta: NoteMeta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
|
|
319
334
|
await atomicWrite(path, serializeNote(meta, parsed.body));
|
|
@@ -340,6 +355,8 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
340
355
|
const raw = await readFileIfExists(fromPath);
|
|
341
356
|
if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
342
357
|
const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
|
|
358
|
+
assertDreamSessionNote(from.scope, from.who, identity, raw, address);
|
|
359
|
+
if (differentPaths) assertDreamSessionNote(scope, destination.who, identity, targetRaw, stableOptions.renameTo!);
|
|
343
360
|
// Case and symlink aliases must not turn write-then-remove into deleting the result.
|
|
344
361
|
const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
|
|
345
362
|
const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
|
|
@@ -404,6 +421,22 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
404
421
|
return { meta, replacedCrumpledTarget };
|
|
405
422
|
}
|
|
406
423
|
|
|
424
|
+
async function forget(address: string): Promise<NoteMeta> {
|
|
425
|
+
if (identity.dreaming === undefined) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
|
|
426
|
+
const target = assertAddress(address);
|
|
427
|
+
assertWritableHome(target.scope, target.who, identity);
|
|
428
|
+
const path = physicalPath(target.scope, target.path, identity, target.who);
|
|
429
|
+
return withPathQueue(path, async () => {
|
|
430
|
+
const raw = await readFileIfExists(path);
|
|
431
|
+
if (raw === undefined) throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
432
|
+
assertDreamSessionNote(target.scope, target.who, identity, raw, address);
|
|
433
|
+
const { meta } = parseNote(raw);
|
|
434
|
+
if (meta.crumpledAt === undefined) throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
|
|
435
|
+
await unlink(path);
|
|
436
|
+
return { ...meta, scope: target.scope };
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
407
440
|
async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
|
|
408
441
|
const glob = assertGlobPattern(options.glob);
|
|
409
442
|
const pattern = glob === "@default" ? undefined : glob;
|
|
@@ -496,5 +529,5 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
496
529
|
return searchRows(queries, options, { homesUnavailable: [] });
|
|
497
530
|
}
|
|
498
531
|
|
|
499
|
-
return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
|
|
532
|
+
return { write, read, update, rename, forget, list, search, listWithStatus, searchWithStatus };
|
|
500
533
|
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
import { createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
|
|
4
|
+
import { projectHomes } from "../notes/project-home.js";
|
|
5
|
+
import { gitCommit } from "../dream/git.js";
|
|
6
|
+
import { acquireDreamLock, dreamLockPath, releaseDreamLock, type DreamLock } from "../dream/lock.js";
|
|
7
|
+
import { failure, renderOutcome, resultSchema, success, type Outcome } from "./result.js";
|
|
8
|
+
import { failureOf, listedFile, NotesListDataSchema, renderListData, snapshot } from "./notes.js";
|
|
9
|
+
|
|
10
|
+
/** The one open dream per session; the host owns where it lives. */
|
|
11
|
+
export type DreamState = { project?: string; lock?: DreamLock };
|
|
12
|
+
|
|
13
|
+
/** Drop an open dream without an end commit, e.g. when its session shuts down. */
|
|
14
|
+
export function abandonDream(state: DreamState): void {
|
|
15
|
+
if (state.lock) releaseDreamLock(state.lock);
|
|
16
|
+
delete state.project;
|
|
17
|
+
delete state.lock;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The identity a store uses while `state` holds an open dream. */
|
|
21
|
+
export function dreamingIdentity(identity: NotesIdentity, state: DreamState): NotesIdentity {
|
|
22
|
+
return state.project === undefined ? identity : { ...identity, dreaming: state.project };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const NOT_DREAMING = "No dream is open; call dream_begin first.";
|
|
26
|
+
|
|
27
|
+
export const dreamBeginParameters = Type.Object({
|
|
28
|
+
project: Type.Optional(Type.String({ description: "(optional, default this project) Project name, as in @projects/<name>/." })),
|
|
29
|
+
}, { additionalProperties: false });
|
|
30
|
+
|
|
31
|
+
export const DreamBeginDataSchema = Type.Object({ project: Type.String(), baseline: Type.String(), ...NotesListDataSchema.properties }, { additionalProperties: false });
|
|
32
|
+
export type DreamBeginData = Static<typeof DreamBeginDataSchema>;
|
|
33
|
+
|
|
34
|
+
function renderBeginData(data: DreamBeginData): string {
|
|
35
|
+
return `dreaming over ${data.project} (baseline ${data.baseline})\n${renderListData(data)}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const dreamBegin = {
|
|
39
|
+
name: "dream_begin", label: "Dream begin",
|
|
40
|
+
description: "Dream: open one project's notes for consolidation, one project at a time. Lists its @projects/<name>/ notes and every session note born in it, crumpled ones included. Until dream_end, notes_write/notes_update can edit those addresses and reads leave no access stamp. Takes the project's dream lock and commits a Git baseline of the notes home.",
|
|
41
|
+
parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
|
|
42
|
+
async execute(params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamBeginData>> {
|
|
43
|
+
if (state.project !== undefined) return failure("already_dreaming", `Already dreaming over ${state.project}; call dream_end before opening another project.`);
|
|
44
|
+
const project = params.project ?? identity.projectKey;
|
|
45
|
+
if (project !== identity.projectKey && !projectHomes(identity.home).some(home => home.name === project)) {
|
|
46
|
+
return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
|
|
47
|
+
}
|
|
48
|
+
const lock = acquireDreamLock(dreamLockPath(identity.home, project));
|
|
49
|
+
if (!lock) return failure("already_dreaming", `Another dream holds ${dreamLockPath(identity.home, project)}. If none is running, delete that file by hand.`);
|
|
50
|
+
try {
|
|
51
|
+
const store = createNotesStore({ ...identity, dreaming: project });
|
|
52
|
+
const rows: NoteRow[] = [];
|
|
53
|
+
const unavailable: string[] = [];
|
|
54
|
+
for (const crumpled of [false, true]) {
|
|
55
|
+
for (const glob of [`@projects/${project}/**`, "@sessions/*/**"]) {
|
|
56
|
+
const result = await store.listWithStatus({ glob, crumpled });
|
|
57
|
+
rows.push(...result.rows.filter(row => row.scope === "project" || row.meta.project === project));
|
|
58
|
+
unavailable.push(...result.status.homesUnavailable);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
|
|
62
|
+
const listed = snapshot(rows.map(row => listedFile(row, identity)), undefined, { homesUnavailable: unavailable }, renderListData);
|
|
63
|
+
if (!listed.ok) { releaseDreamLock(lock); return listed; }
|
|
64
|
+
const baseline = gitCommit(identity.home, `dream baseline ${project}`);
|
|
65
|
+
if (!baseline.ok) { releaseDreamLock(lock); return failure("audit_failed", `Couldn't commit the Git baseline, so nothing could be rolled back; no dream was opened: ${baseline.error}`); }
|
|
66
|
+
Object.assign(state, { project, lock });
|
|
67
|
+
return success({ project, baseline: baseline.commit, ...listed.data });
|
|
68
|
+
} catch (error) { releaseDreamLock(lock); return failureOf(error); }
|
|
69
|
+
},
|
|
70
|
+
render: (result: Outcome<DreamBeginData>): string => renderOutcome(result, renderBeginData),
|
|
71
|
+
} as const;
|
|
72
|
+
|
|
73
|
+
export const dreamForgetParameters = Type.Object({ address: Type.String() }, { additionalProperties: false });
|
|
74
|
+
export const DreamForgetDataSchema = Type.Object({ address: Type.String(), project_key: Type.Optional(Type.String()) }, { additionalProperties: false });
|
|
75
|
+
export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
|
|
76
|
+
|
|
77
|
+
export const dreamForget = {
|
|
78
|
+
name: "dream_forget", label: "Dream forget",
|
|
79
|
+
description: "Dream: permanently delete one crumpled note in the project being dreamed over, or in @human/, @self/, @model/. Crumple it first; live notes refuse.",
|
|
80
|
+
parameters: dreamForgetParameters, outputSchema: resultSchema(DreamForgetDataSchema),
|
|
81
|
+
async execute(params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamForgetData>> {
|
|
82
|
+
if (state.project === undefined) return failure("not_dreaming", NOT_DREAMING);
|
|
83
|
+
try {
|
|
84
|
+
const dreaming = dreamingIdentity(identity, state);
|
|
85
|
+
await createNotesStore(dreaming).forget(params.address);
|
|
86
|
+
return success(noteIdentity(dreaming, params.address));
|
|
87
|
+
} catch (error) { return failureOf(error); }
|
|
88
|
+
},
|
|
89
|
+
render: (result: Outcome<DreamForgetData>): string => renderOutcome(result, data => `forgot ${data.address}`),
|
|
90
|
+
} as const;
|
|
91
|
+
|
|
92
|
+
export const dreamEndParameters = Type.Object({}, { additionalProperties: false });
|
|
93
|
+
export const DreamEndDataSchema = Type.Object({ project: Type.String(), commit: Type.Optional(Type.String()), audit_error: Type.Optional(Type.String()) }, { additionalProperties: false });
|
|
94
|
+
export type DreamEndData = Static<typeof DreamEndDataSchema>;
|
|
95
|
+
|
|
96
|
+
export const dreamEnd = {
|
|
97
|
+
name: "dream_end", label: "Dream end",
|
|
98
|
+
description: "Dream: close the open dream. Commits the dream's changes to the notes home's Git and releases the lock; the project's notes are read-only again and reads stamp access again.",
|
|
99
|
+
parameters: dreamEndParameters, outputSchema: resultSchema(DreamEndDataSchema),
|
|
100
|
+
async execute(_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamEndData>> {
|
|
101
|
+
const project = state.project;
|
|
102
|
+
if (project === undefined) return failure("not_dreaming", NOT_DREAMING);
|
|
103
|
+
// The dream closes even when the audit commit fails; the uncommitted changes stay in the work tree.
|
|
104
|
+
const audit = gitCommit(identity.home, `dream ${project}`);
|
|
105
|
+
abandonDream(state);
|
|
106
|
+
return success(audit.ok ? { project, commit: audit.commit } : { project, audit_error: audit.error });
|
|
107
|
+
},
|
|
108
|
+
render: (result: Outcome<DreamEndData>): string => renderOutcome(result, data => data.commit !== undefined
|
|
109
|
+
? `woke from ${data.project} (commit ${data.commit})`
|
|
110
|
+
: `woke from ${data.project}; the Git commit failed, changes are uncommitted: ${data.audit_error}`),
|
|
111
|
+
} as const;
|
|
112
|
+
|
package/src/tools/notes.ts
CHANGED
|
@@ -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
|
-
}
|