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/README.md
CHANGED
|
@@ -62,17 +62,10 @@ The reminder threshold is Pi's compaction reserve plus a margin, configured unde
|
|
|
62
62
|
}
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
-
The dreamer model is configured under the same key; `--dreamer <model pattern>` on the `dream` CLI wins, then a non-empty `notesoup.dreamer` string, then the automatic model:
|
|
66
|
-
|
|
67
|
-
```json
|
|
68
|
-
{
|
|
69
|
-
"notesoup": { "reminderMarginTokens": 24576, "dreamer": "anthropic/claude-sonnet-4-5" }
|
|
70
|
-
}
|
|
71
|
-
```
|
|
72
|
-
|
|
73
65
|
Environment variables:
|
|
74
66
|
|
|
75
67
|
- `NOTESOUP_DISABLED` — presence-style kill switch: any value but an explicit no (`0`, `false`, `no`, `off`) turns notesoup off. On Pi the extension registers nothing at all; on Claude the mod passes every event through and native compaction behaves as if the mod were absent.
|
|
68
|
+
- `NOTESOUP_KEEP_MEMORY` — Claude only: keep Claude Code's auto-memory guidance, which notesoup omits by default (its summarization guidance is always omitted). Enabled by any non-empty value except `0`, `false`, `no`, or `off` (case-insensitive); read at session startup.
|
|
76
69
|
- `NOTESOUP_HOME` — overrides the notes root (default `~/.agents/notes`).
|
|
77
70
|
- `NOTESOUP_AGENT` — overrides the agent name on Pi (default `anonymous`).
|
|
78
71
|
|
|
@@ -83,7 +76,7 @@ Environment variables:
|
|
|
83
76
|
- [Standalone notes library](docs/notes-library.md) — use the notes store from Node, no Pi required
|
|
84
77
|
- [DeepSeek Harness](docs/dsh.md) — adapter and profile patch for dsh 0.2.1-alpha.2
|
|
85
78
|
- [Claude Code Mod](docs/claude-code-mod.md) — early-access notes and persisted-session history tools for Claude Code
|
|
86
|
-
- [Skills
|
|
79
|
+
- [Skills and dream](docs/skills.md) — `/skill:memory`, `/skill:dream`, the `dream_*` tools and the dream lock
|
|
87
80
|
|
|
88
81
|
## Development
|
|
89
82
|
|
|
@@ -100,7 +93,7 @@ The repository splits host-neutral code from host plugins:
|
|
|
100
93
|
| Path | What it is |
|
|
101
94
|
| --- | --- |
|
|
102
95
|
| `src/` | The core: notes library, boot snapshot/renderer, history projection, budget policy and the shared tool operations. It never imports an SDK or a plugin. |
|
|
103
|
-
| `plugins/pi/` | The Pi extension (`plugins/pi/index.ts` is what `pi.extensions` loads from source)
|
|
96
|
+
| `plugins/pi/` | The Pi extension (`plugins/pi/index.ts` is what `pi.extensions` loads from source). |
|
|
104
97
|
| `plugins/claude/` | The self-contained Claude Code plugin (`.claude-plugin/`, `hooks/`, bundled `dist/claude/helper.js`, skills and playbook), with its adapter sources in `plugins/claude/src/`. |
|
|
105
98
|
| `plugins/dsh/` | The Cordis rows published as `notesoup/dsh` and `notesoup/dsh/engine`. |
|
|
106
99
|
|
|
@@ -2,10 +2,6 @@
|
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { isDeepStrictEqual } from "node:util";
|
|
4
4
|
import { contentText, projectHistory } from "../../../src/history/history.js";
|
|
5
|
-
const METADATA = new Set([
|
|
6
|
-
"queue-operation", "last-prompt", "atis-latch", "mode", "permission-mode", "file-history-snapshot", "cost-state",
|
|
7
|
-
"summary", "custom-title", "agent-name", "agent-color", "tag", "session-title", "progress",
|
|
8
|
-
]);
|
|
9
5
|
const MESSAGE_TYPES = new Set(["user", "assistant", "system", "attachment"]);
|
|
10
6
|
const NON_TEXT_BLOCKS = new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
|
|
11
7
|
function object(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
|
|
@@ -135,10 +131,10 @@ export function claudeHistoryFromJsonl(text, source) {
|
|
|
135
131
|
const nodes = new Map();
|
|
136
132
|
let nextSeq = 1;
|
|
137
133
|
for (const row of rowsOf(text)) {
|
|
138
|
-
|
|
139
|
-
|
|
134
|
+
// Ignore non-message records, including future metadata. A skipped UUID that
|
|
135
|
+
// the selected branch actually requires still fails ancestry resolution below.
|
|
140
136
|
if (!MESSAGE_TYPES.has(row.type))
|
|
141
|
-
|
|
137
|
+
continue;
|
|
142
138
|
const uuid = requiredString(row.uuid, "uuid");
|
|
143
139
|
parent(row);
|
|
144
140
|
if (row.sessionId !== source.sessionId)
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
/** Register the five shared note operations
|
|
2
|
+
/** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
|
|
3
3
|
export declare function registerNotesTools(pi: ExtensionAPI): void;
|
|
@@ -1,16 +1,35 @@
|
|
|
1
1
|
import { generateDiffString } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { notesWrite, notesUpdate, notesRead, notesList, notesSearch } from "../../../src/tools/notes.js";
|
|
3
|
+
import { abandonDream, dreamBegin, dreamEnd, dreamForget, dreamingIdentity } from "../../../src/tools/dream.js";
|
|
3
4
|
import { notesIdentityFromPi } from "./adapter.js";
|
|
4
5
|
import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
|
|
5
|
-
import { NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
|
|
6
|
+
import { DREAM_NAMESPACE, NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
|
|
6
7
|
function renderDiff(change) {
|
|
7
8
|
return change.kind === "none" ? "" : generateDiffString(change.before, change.after, 1).diff;
|
|
8
9
|
}
|
|
9
|
-
/** Register the five shared note operations
|
|
10
|
+
/** Register the five shared note operations and the three hidden dream tools; an open dream widens the note identity. */
|
|
10
11
|
export function registerNotesTools(pi) {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
// One open dream per session, in memory: shutdown releases its lock without the end commit.
|
|
13
|
+
const dreams = new Map();
|
|
14
|
+
pi.on("session_shutdown", () => {
|
|
15
|
+
for (const state of dreams.values())
|
|
16
|
+
abandonDream(state);
|
|
17
|
+
dreams.clear();
|
|
18
|
+
});
|
|
19
|
+
const dreamOf = (ctx) => {
|
|
20
|
+
const id = ctx.sessionManager.getSessionId();
|
|
21
|
+
let state = dreams.get(id);
|
|
22
|
+
if (!state)
|
|
23
|
+
dreams.set(id, state = {});
|
|
24
|
+
return state;
|
|
25
|
+
};
|
|
26
|
+
const identity = (ctx) => dreamingIdentity(notesIdentityFromPi(ctx), dreamOf(ctx));
|
|
27
|
+
registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, identity(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
|
|
28
|
+
registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, identity(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
|
|
29
|
+
registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, identity(ctx)), NOTES_NAMESPACE, notesReadRenderers);
|
|
30
|
+
registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, identity(ctx)), NOTES_NAMESPACE);
|
|
31
|
+
registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, identity(ctx)), NOTES_NAMESPACE);
|
|
32
|
+
registerOperation(pi, dreamBegin, (params, ctx) => dreamBegin.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
|
|
33
|
+
registerOperation(pi, dreamForget, (params, ctx) => dreamForget.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
|
|
34
|
+
registerOperation(pi, dreamEnd, (params, ctx) => dreamEnd.execute(params, notesIdentityFromPi(ctx), dreamOf(ctx)), DREAM_NAMESPACE, undefined, "deferred");
|
|
16
35
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Pi transport for host-neutral operations. */
|
|
2
|
-
import { type ExtensionAPI, type ExtensionToolContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type ExtensionAPI, type ExtensionToolContext, type ToolDefinition, type ToolExposure } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import type { Static, TSchema } from "typebox";
|
|
4
4
|
import { type Operation, type Outcome } from "../../src/tools/result.js";
|
|
5
5
|
/** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
|
|
@@ -17,8 +17,9 @@ export type ToolNamespace = {
|
|
|
17
17
|
description: string;
|
|
18
18
|
};
|
|
19
19
|
export declare const NOTES_NAMESPACE: ToolNamespace;
|
|
20
|
+
export declare const DREAM_NAMESPACE: ToolNamespace;
|
|
20
21
|
export declare const HISTORY_NAMESPACE: ToolNamespace;
|
|
21
22
|
/** Optional TUI renderers; without them the host draws its default call line and receipt text. */
|
|
22
23
|
export type OperationRenderers<TParams extends TSchema> = Pick<ToolDefinition<TParams, undefined>, "renderCall" | "renderResult">;
|
|
23
24
|
/** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
|
|
24
|
-
export declare function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(pi: ExtensionAPI, operation: Operation<TParams, TData, TRest>, run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>, namespace?: ToolNamespace, renderers?: OperationRenderers<TParams
|
|
25
|
+
export declare function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(pi: ExtensionAPI, operation: Operation<TParams, TData, TRest>, run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>, namespace?: ToolNamespace, renderers?: OperationRenderers<TParams>, exposure?: ToolExposure): void;
|
|
@@ -17,9 +17,10 @@ function piOperationResult(render, outcome) {
|
|
|
17
17
|
};
|
|
18
18
|
}
|
|
19
19
|
export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
|
|
20
|
+
export const DREAM_NAMESPACE = { name: "dream", description: "Consolidate one project's notes: begin, edit with notes_*, forget crumpled notes, end." };
|
|
20
21
|
export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
|
|
21
22
|
/** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
|
|
22
|
-
export function registerOperation(pi, operation, run, namespace, renderers) {
|
|
23
|
+
export function registerOperation(pi, operation, run, namespace, renderers, exposure) {
|
|
23
24
|
pi.registerTool(defineTool({
|
|
24
25
|
name: operation.name,
|
|
25
26
|
label: operation.label,
|
|
@@ -28,6 +29,7 @@ export function registerOperation(pi, operation, run, namespace, renderers) {
|
|
|
28
29
|
outputSchema: operation.outputSchema,
|
|
29
30
|
executionMode: operation.executionMode,
|
|
30
31
|
...(namespace ? { namespace } : {}),
|
|
32
|
+
...(exposure ? { exposure } : {}),
|
|
31
33
|
...renderers,
|
|
32
34
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
33
35
|
return piOperationResult(operation.render, await run(params, ctx));
|
package/dist/src/dream/git.d.ts
CHANGED
|
@@ -12,9 +12,8 @@ export type AuditResult = {
|
|
|
12
12
|
error: string;
|
|
13
13
|
};
|
|
14
14
|
/**
|
|
15
|
-
* Git audit layer for a dream
|
|
16
|
-
* so the human
|
|
17
|
-
* `git revert`. The caller decides how loud a failure is; this function only reports it.
|
|
15
|
+
* Git audit layer for a dream: one commit at dream_begin (baseline) and one at dream_end,
|
|
16
|
+
* so the human reviews `git show` instead of trusting a report, and rollback is `git revert`. The caller decides how loud a failure is; this function only reports it.
|
|
18
17
|
* A clean tree on an established repository commits nothing; a repository with no HEAD
|
|
19
18
|
* gets an empty baseline commit, because an audit run with no snapshot is not a success.
|
|
20
19
|
*/
|
package/dist/src/dream/git.js
CHANGED
|
@@ -18,9 +18,8 @@ function ensureRuntimeIgnored(home) {
|
|
|
18
18
|
catch { /* best effort: an unignored lock only adds noise to the audit */ }
|
|
19
19
|
}
|
|
20
20
|
/**
|
|
21
|
-
* Git audit layer for a dream
|
|
22
|
-
* so the human
|
|
23
|
-
* `git revert`. The caller decides how loud a failure is; this function only reports it.
|
|
21
|
+
* Git audit layer for a dream: one commit at dream_begin (baseline) and one at dream_end,
|
|
22
|
+
* so the human reviews `git show` instead of trusting a report, and rollback is `git revert`. The caller decides how loud a failure is; this function only reports it.
|
|
24
23
|
* A clean tree on an established repository commits nothing; a repository with no HEAD
|
|
25
24
|
* gets an empty baseline commit, because an audit run with no snapshot is not a success.
|
|
26
25
|
*/
|
|
@@ -42,12 +41,10 @@ export function gitCommit(home, message) {
|
|
|
42
41
|
const before = headCommit(home);
|
|
43
42
|
if (!clean) {
|
|
44
43
|
execFileSync("git", ["commit", "-q", "-m", message], { cwd: home, stdio: "ignore" });
|
|
45
|
-
console.log(`git: committed "${message}"`);
|
|
46
44
|
}
|
|
47
45
|
else if (before === undefined) {
|
|
48
46
|
// A newly initialized repository has no snapshot at all; give the audit one.
|
|
49
47
|
execFileSync("git", ["commit", "-q", "--allow-empty", "-m", message], { cwd: home, stdio: "ignore" });
|
|
50
|
-
console.log(`git: committed "${message}"`);
|
|
51
48
|
}
|
|
52
49
|
const commit = headCommit(home);
|
|
53
50
|
if (commit === undefined)
|
|
@@ -55,9 +52,7 @@ export function gitCommit(home, message) {
|
|
|
55
52
|
return { ok: true, commit, empty: clean };
|
|
56
53
|
}
|
|
57
54
|
catch (error) {
|
|
58
|
-
|
|
59
|
-
console.log(`git audit layer failed: ${reason}`);
|
|
60
|
-
return { ok: false, error: reason };
|
|
55
|
+
return { ok: false, error: errorMessage(error) };
|
|
61
56
|
}
|
|
62
57
|
}
|
|
63
58
|
/** HEAD sha, or undefined when the repository has no commit yet. */
|
package/dist/src/dream/lock.d.ts
CHANGED
|
@@ -1,31 +1,14 @@
|
|
|
1
|
-
|
|
1
|
+
/** One held dream lock; only the holder that wrote the token removes it. */
|
|
2
|
+
export type DreamLock = {
|
|
2
3
|
path: string;
|
|
3
|
-
|
|
4
|
-
reason?: string;
|
|
5
|
-
startedAt: number;
|
|
6
|
-
/** mtime of the last-run sidecar before this run took the lock; failLock restores it. */
|
|
7
|
-
priorStampMtime?: number;
|
|
8
|
-
/** Random identity written into the lock file; cleanup only removes the lock it wrote. */
|
|
9
|
-
token?: string;
|
|
4
|
+
token: string;
|
|
10
5
|
};
|
|
6
|
+
/** The per-project lock file in the notes home; `.dream.lock*` is excluded from the Git audit. */
|
|
7
|
+
export declare function dreamLockPath(home: string, project: string): string;
|
|
11
8
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* marker, so lock lifecycle does not destroy the timestamp the time gate reads.
|
|
9
|
+
* Git-style exclusive existence lock: one O_CREAT|O_EXCL creation. An existing lock refuses,
|
|
10
|
+
* whatever its age; a crash-left lock is removed by hand after confirming no dream runs.
|
|
15
11
|
*/
|
|
16
|
-
export declare function
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
-
* creation. An existing path refuses acquisition regardless of its contents, PID, or age,
|
|
20
|
-
* and is never read for permission, replaced, or removed. There is no automatic stale
|
|
21
|
-
* recovery; a crash-left lock is human cleanup after confirming no dream is running.
|
|
22
|
-
*/
|
|
23
|
-
export declare function acquireLock(path: string): LockState;
|
|
24
|
-
/** Release only the lock this run acquired. Idempotent: repeated cleanup does nothing. */
|
|
25
|
-
export declare function releaseLock(lock: LockState): void;
|
|
26
|
-
/**
|
|
27
|
-
* A failed run must not advance the scheduler: restore the previous timestamp, or remove
|
|
28
|
-
* the one this run wrote when there was none. Only this run's own marker is removed, and
|
|
29
|
-
* the state is marked released so a later cleanup attempt is harmless.
|
|
30
|
-
*/
|
|
31
|
-
export declare function failLock(lock: LockState): void;
|
|
12
|
+
export declare function acquireDreamLock(path: string): DreamLock | undefined;
|
|
13
|
+
/** Release only a lock this holder wrote; repeated release is harmless. */
|
|
14
|
+
export declare function releaseDreamLock(lock: DreamLock): void;
|
package/dist/src/dream/lock.js
CHANGED
|
@@ -1,92 +1,29 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { readFileSync,
|
|
2
|
+
import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
/** The per-project lock file in the notes home; `.dream.lock*` is excluded from the Git audit. */
|
|
5
|
+
export function dreamLockPath(home, project) {
|
|
6
|
+
return join(home, `.dream.lock.${project}`);
|
|
7
|
+
}
|
|
3
8
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* marker, so lock lifecycle does not destroy the timestamp the time gate reads.
|
|
9
|
+
* Git-style exclusive existence lock: one O_CREAT|O_EXCL creation. An existing lock refuses,
|
|
10
|
+
* whatever its age; a crash-left lock is removed by hand after confirming no dream runs.
|
|
7
11
|
*/
|
|
8
|
-
export function
|
|
9
|
-
|
|
10
|
-
}
|
|
11
|
-
function readText(path) {
|
|
12
|
+
export function acquireDreamLock(path) {
|
|
13
|
+
const token = `${process.pid} ${randomUUID()}`;
|
|
12
14
|
try {
|
|
13
|
-
|
|
15
|
+
writeFileSync(path, token, { flag: "wx" });
|
|
14
16
|
}
|
|
15
17
|
catch {
|
|
16
18
|
return undefined;
|
|
17
19
|
}
|
|
20
|
+
return { path, token };
|
|
18
21
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return false;
|
|
22
|
-
return readText(lock.path)?.trim() === `${process.pid} ${lock.token}`;
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Acquire the dream lock with Git-style exclusive existence locking: one O_CREAT|O_EXCL
|
|
26
|
-
* creation. An existing path refuses acquisition regardless of its contents, PID, or age,
|
|
27
|
-
* and is never read for permission, replaced, or removed. There is no automatic stale
|
|
28
|
-
* recovery; a crash-left lock is human cleanup after confirming no dream is running.
|
|
29
|
-
*/
|
|
30
|
-
export function acquireLock(path) {
|
|
31
|
-
const now = Date.now();
|
|
32
|
-
// The sidecar's mtime is the scheduler's timestamp; a missing one means no prior dream.
|
|
33
|
-
let priorStampMtime;
|
|
34
|
-
try {
|
|
35
|
-
priorStampMtime = statSync(lastRunPath(path)).mtimeMs;
|
|
36
|
-
}
|
|
37
|
-
catch { /* no sidecar yet */ }
|
|
38
|
-
const token = randomUUID();
|
|
39
|
-
try {
|
|
40
|
-
writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
|
|
41
|
-
}
|
|
42
|
-
catch {
|
|
43
|
-
return { path, held: false, reason: "lock gate: lock already exists", startedAt: now };
|
|
44
|
-
}
|
|
45
|
-
// Only a held lock advances the scheduler timestamp.
|
|
22
|
+
/** Release only a lock this holder wrote; repeated release is harmless. */
|
|
23
|
+
export function releaseDreamLock(lock) {
|
|
46
24
|
try {
|
|
47
|
-
|
|
48
|
-
}
|
|
49
|
-
catch { /* advisory */ }
|
|
50
|
-
return { path, held: true, startedAt: now, priorStampMtime, token };
|
|
51
|
-
}
|
|
52
|
-
/** Release only the lock this run acquired. Idempotent: repeated cleanup does nothing. */
|
|
53
|
-
export function releaseLock(lock) {
|
|
54
|
-
if (!lock.held)
|
|
55
|
-
return;
|
|
56
|
-
if (ownsLock(lock)) {
|
|
57
|
-
try {
|
|
58
|
-
unlinkSync(lock.path);
|
|
59
|
-
}
|
|
60
|
-
catch { /* best effort */ }
|
|
61
|
-
}
|
|
62
|
-
lock.held = false;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* A failed run must not advance the scheduler: restore the previous timestamp, or remove
|
|
66
|
-
* the one this run wrote when there was none. Only this run's own marker is removed, and
|
|
67
|
-
* the state is marked released so a later cleanup attempt is harmless.
|
|
68
|
-
*/
|
|
69
|
-
export function failLock(lock) {
|
|
70
|
-
if (!lock.held)
|
|
71
|
-
return;
|
|
72
|
-
if (ownsLock(lock)) {
|
|
73
|
-
const stampPath = lastRunPath(lock.path);
|
|
74
|
-
if (lock.priorStampMtime === undefined) {
|
|
75
|
-
try {
|
|
76
|
-
unlinkSync(stampPath);
|
|
77
|
-
}
|
|
78
|
-
catch { /* best effort */ }
|
|
79
|
-
}
|
|
80
|
-
else {
|
|
81
|
-
try {
|
|
82
|
-
utimesSync(stampPath, new Date(), new Date(lock.priorStampMtime));
|
|
83
|
-
}
|
|
84
|
-
catch { /* best effort */ }
|
|
85
|
-
}
|
|
86
|
-
try {
|
|
25
|
+
if (readFileSync(lock.path, "utf8") === lock.token)
|
|
87
26
|
unlinkSync(lock.path);
|
|
88
|
-
}
|
|
89
|
-
catch { /* best effort */ }
|
|
90
27
|
}
|
|
91
|
-
|
|
28
|
+
catch { /* already gone */ }
|
|
92
29
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
|
|
1
|
+
export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "io_error" | "internal_error";
|
|
2
2
|
/** Typed store refusal. Edit locations are exposed in camelCase. */
|
|
3
3
|
export declare class NoteError extends Error {
|
|
4
4
|
readonly code: NoteErrorCode;
|
|
@@ -5,6 +5,8 @@ export type NotesIdentity = Readonly<{
|
|
|
5
5
|
projectKey: string;
|
|
6
6
|
agent: string;
|
|
7
7
|
model: string;
|
|
8
|
+
/** Project slug being dreamed over: its named project and session notes become writable, and reads leave no access stamp. */
|
|
9
|
+
dreaming?: string;
|
|
8
10
|
}>;
|
|
9
11
|
/** Validate and snapshot caller identity; no global or environment defaults are consulted. */
|
|
10
12
|
export declare function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity;
|
|
@@ -22,6 +22,8 @@ export function snapshotNotesIdentity(value) {
|
|
|
22
22
|
throw new TypeError("notes context agent must be a canonical lowercase slug");
|
|
23
23
|
if (!SLUG_PATTERN.test(model))
|
|
24
24
|
throw new TypeError("notes context model must be a canonical lowercase slug");
|
|
25
|
+
if (value.dreaming !== undefined && !SLUG_PATTERN.test(value.dreaming))
|
|
26
|
+
throw new TypeError("notes context dreaming must be a canonical lowercase slug");
|
|
25
27
|
const home = resolve(homeValue);
|
|
26
|
-
return Object.freeze({ home, sessionId, projectKey, agent, model });
|
|
28
|
+
return Object.freeze({ home, sessionId, projectKey, agent, model, ...(value.dreaming === undefined ? {} : { dreaming: value.dreaming }) });
|
|
27
29
|
}
|
|
@@ -93,6 +93,8 @@ export interface NotesStore {
|
|
|
93
93
|
read(address: string): Promise<NoteReadResult | undefined>;
|
|
94
94
|
update(address: string, edits?: EditOperation[], options?: EditOptions): Promise<NoteEditResult>;
|
|
95
95
|
rename(fromAddress: string, toAddress: string): Promise<NoteRenameResult>;
|
|
96
|
+
/** Physically delete one crumpled note; only a dreaming identity may call it. */
|
|
97
|
+
forget(address: string): Promise<NoteMeta>;
|
|
96
98
|
list(options?: NotesQuery): Promise<NoteRow[]>;
|
|
97
99
|
search(queries: string[], options?: NotesQuery): Promise<NoteSearchRow[]>;
|
|
98
100
|
listWithStatus(options?: NotesQuery): Promise<NoteQueryResult<NoteRow>>;
|
package/dist/src/notes/store.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { mkdir, readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { mkdir, readdir, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
5
5
|
import { assertAddress, assertGlobPattern, addressFor, canonicalAddressFor, globToRegExp, HOME_HEADS } from "./address.js";
|
|
@@ -218,10 +218,13 @@ function assertSerializedSize(content) {
|
|
|
218
218
|
function frontmatterOf(meta) {
|
|
219
219
|
return serializeNote(meta, "").slice(0, -2);
|
|
220
220
|
}
|
|
221
|
-
/** Explicit session/project homes are
|
|
221
|
+
/** Explicit session/project homes are read-only unless dreamed over; agent/model homes allow their owner. */
|
|
222
222
|
function assertWritableHome(scope, who, identity) {
|
|
223
223
|
if (who === undefined)
|
|
224
224
|
return;
|
|
225
|
+
// A dreamed project is writable whole; its other sessions are checked per note by assertDreamSessionNote.
|
|
226
|
+
if (identity.dreaming !== undefined && (scope === "session" || (scope === "project" && who === identity.dreaming)))
|
|
227
|
+
return;
|
|
225
228
|
if (scope === "session")
|
|
226
229
|
throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
|
|
227
230
|
if (scope === "project")
|
|
@@ -232,6 +235,16 @@ function assertWritableHome(scope, who, identity) {
|
|
|
232
235
|
const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
|
|
233
236
|
throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
|
|
234
237
|
}
|
|
238
|
+
/** A dream reaches another session's note only when that note was born in the dreamed project. */
|
|
239
|
+
function assertDreamSessionNote(scope, who, identity, raw, address) {
|
|
240
|
+
if (scope !== "session" || who === undefined || identity.dreaming === undefined)
|
|
241
|
+
return;
|
|
242
|
+
if (raw !== undefined && parseNote(raw).meta.project === identity.dreaming)
|
|
243
|
+
return;
|
|
244
|
+
throw new NoteError("invalid_scope", raw === undefined
|
|
245
|
+
? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.`
|
|
246
|
+
: `${address} belongs to another project, not the one being dreamed over (${identity.dreaming}).`);
|
|
247
|
+
}
|
|
235
248
|
/** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
|
|
236
249
|
export function createNotesStore(input) {
|
|
237
250
|
const identity = snapshotNotesIdentity(input);
|
|
@@ -249,6 +262,7 @@ export function createNotesStore(input) {
|
|
|
249
262
|
const now = writeStamp();
|
|
250
263
|
const cleanBody = stripLeadingFrontmatter(content);
|
|
251
264
|
const existingRaw = await readFileIfExists(path);
|
|
265
|
+
assertDreamSessionNote(scope, destination.who, identity, existingRaw, address);
|
|
252
266
|
const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
|
|
253
267
|
const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
|
|
254
268
|
const meta = existing ?? {
|
|
@@ -281,7 +295,8 @@ export function createNotesStore(input) {
|
|
|
281
295
|
return undefined;
|
|
282
296
|
const now = Date.now();
|
|
283
297
|
const parsed = parseNote(raw, now);
|
|
284
|
-
|
|
298
|
+
// Named homes, and every read during a dream, leave no access stamp.
|
|
299
|
+
if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined))
|
|
285
300
|
return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
|
|
286
301
|
// A read records its own access, exactly as a write records an edit.
|
|
287
302
|
const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
|
|
@@ -309,6 +324,9 @@ export function createNotesStore(input) {
|
|
|
309
324
|
if (raw === undefined)
|
|
310
325
|
throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
311
326
|
const targetRaw = differentPaths ? await readFileIfExists(path) : undefined;
|
|
327
|
+
assertDreamSessionNote(from.scope, from.who, identity, raw, address);
|
|
328
|
+
if (differentPaths)
|
|
329
|
+
assertDreamSessionNote(scope, destination.who, identity, targetRaw, stableOptions.renameTo);
|
|
312
330
|
// Case and symlink aliases must not turn write-then-remove into deleting the result.
|
|
313
331
|
const sourceReal = targetRaw === undefined ? undefined : await realpath(fromPath);
|
|
314
332
|
const sameFile = sourceReal !== undefined && sourceReal === await realpath(path);
|
|
@@ -388,6 +406,24 @@ export function createNotesStore(input) {
|
|
|
388
406
|
const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
|
|
389
407
|
return { meta, replacedCrumpledTarget };
|
|
390
408
|
}
|
|
409
|
+
async function forget(address) {
|
|
410
|
+
if (identity.dreaming === undefined)
|
|
411
|
+
throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
|
|
412
|
+
const target = assertAddress(address);
|
|
413
|
+
assertWritableHome(target.scope, target.who, identity);
|
|
414
|
+
const path = physicalPath(target.scope, target.path, identity, target.who);
|
|
415
|
+
return withPathQueue(path, async () => {
|
|
416
|
+
const raw = await readFileIfExists(path);
|
|
417
|
+
if (raw === undefined)
|
|
418
|
+
throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
419
|
+
assertDreamSessionNote(target.scope, target.who, identity, raw, address);
|
|
420
|
+
const { meta } = parseNote(raw);
|
|
421
|
+
if (meta.crumpledAt === undefined)
|
|
422
|
+
throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
|
|
423
|
+
await unlink(path);
|
|
424
|
+
return { ...meta, scope: target.scope };
|
|
425
|
+
});
|
|
426
|
+
}
|
|
391
427
|
async function* scan(options, status) {
|
|
392
428
|
const glob = assertGlobPattern(options.glob);
|
|
393
429
|
const pattern = glob === "@default" ? undefined : glob;
|
|
@@ -480,5 +516,5 @@ export function createNotesStore(input) {
|
|
|
480
516
|
function searchWithStatus(queries, options = {}) {
|
|
481
517
|
return searchRows(queries, options, { homesUnavailable: [] });
|
|
482
518
|
}
|
|
483
|
-
return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
|
|
519
|
+
return { write, read, update, rename, forget, list, search, listWithStatus, searchWithStatus };
|
|
484
520
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
import { type NotesIdentity } from "../notes/index.js";
|
|
4
|
+
import { type DreamLock } from "../dream/lock.js";
|
|
5
|
+
import { type Outcome } from "./result.js";
|
|
6
|
+
/** The one open dream per session; the host owns where it lives. */
|
|
7
|
+
export type DreamState = {
|
|
8
|
+
project?: string;
|
|
9
|
+
lock?: DreamLock;
|
|
10
|
+
};
|
|
11
|
+
/** Drop an open dream without an end commit, e.g. when its session shuts down. */
|
|
12
|
+
export declare function abandonDream(state: DreamState): void;
|
|
13
|
+
/** The identity a store uses while `state` holds an open dream. */
|
|
14
|
+
export declare function dreamingIdentity(identity: NotesIdentity, state: DreamState): NotesIdentity;
|
|
15
|
+
export declare const dreamBeginParameters: Type.TObject<{
|
|
16
|
+
project: Type.TOptional<Type.TString>;
|
|
17
|
+
}>;
|
|
18
|
+
export declare const DreamBeginDataSchema: Type.TObject<{
|
|
19
|
+
more: Type.TInteger;
|
|
20
|
+
homes_unavailable: Type.TArray<Type.TString>;
|
|
21
|
+
files: Type.TArray<Type.TObject<{
|
|
22
|
+
updated_at: Type.TString;
|
|
23
|
+
crumpled_at: Type.TOptional<Type.TString>;
|
|
24
|
+
project_root: Type.TOptional<Type.TString>;
|
|
25
|
+
project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
|
|
26
|
+
name: Type.TString;
|
|
27
|
+
path: Type.TString;
|
|
28
|
+
}>>>;
|
|
29
|
+
address: Type.TString;
|
|
30
|
+
project_key: Type.TOptional<Type.TString>;
|
|
31
|
+
}>>;
|
|
32
|
+
project: Type.TString;
|
|
33
|
+
baseline: Type.TString;
|
|
34
|
+
}>;
|
|
35
|
+
export type DreamBeginData = Static<typeof DreamBeginDataSchema>;
|
|
36
|
+
export declare const dreamBegin: {
|
|
37
|
+
readonly name: "dream_begin";
|
|
38
|
+
readonly label: "Dream begin";
|
|
39
|
+
readonly 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.";
|
|
40
|
+
readonly parameters: Type.TObject<{
|
|
41
|
+
project: Type.TOptional<Type.TString>;
|
|
42
|
+
}>;
|
|
43
|
+
readonly outputSchema: Type.TUnion<[Type.TObject<{
|
|
44
|
+
more: Type.TInteger;
|
|
45
|
+
homes_unavailable: Type.TArray<Type.TString>;
|
|
46
|
+
files: Type.TArray<Type.TObject<{
|
|
47
|
+
updated_at: Type.TString;
|
|
48
|
+
crumpled_at: Type.TOptional<Type.TString>;
|
|
49
|
+
project_root: Type.TOptional<Type.TString>;
|
|
50
|
+
project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
|
|
51
|
+
name: Type.TString;
|
|
52
|
+
path: Type.TString;
|
|
53
|
+
}>>>;
|
|
54
|
+
address: Type.TString;
|
|
55
|
+
project_key: Type.TOptional<Type.TString>;
|
|
56
|
+
}>>;
|
|
57
|
+
project: Type.TString;
|
|
58
|
+
baseline: Type.TString;
|
|
59
|
+
}>, Type.TObject<{
|
|
60
|
+
error: Type.TString;
|
|
61
|
+
code: Type.TString;
|
|
62
|
+
}>]>;
|
|
63
|
+
readonly execute: (params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState) => Promise<Outcome<DreamBeginData>>;
|
|
64
|
+
readonly render: (result: Outcome<DreamBeginData>) => string;
|
|
65
|
+
};
|
|
66
|
+
export declare const dreamForgetParameters: Type.TObject<{
|
|
67
|
+
address: Type.TString;
|
|
68
|
+
}>;
|
|
69
|
+
export declare const DreamForgetDataSchema: Type.TObject<{
|
|
70
|
+
address: Type.TString;
|
|
71
|
+
project_key: Type.TOptional<Type.TString>;
|
|
72
|
+
}>;
|
|
73
|
+
export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
|
|
74
|
+
export declare const dreamForget: {
|
|
75
|
+
readonly name: "dream_forget";
|
|
76
|
+
readonly label: "Dream forget";
|
|
77
|
+
readonly description: "Dream: permanently delete one crumpled note in the project being dreamed over, or in @human/, @self/, @model/. Crumple it first; live notes refuse.";
|
|
78
|
+
readonly parameters: Type.TObject<{
|
|
79
|
+
address: Type.TString;
|
|
80
|
+
}>;
|
|
81
|
+
readonly outputSchema: Type.TUnion<[Type.TObject<{
|
|
82
|
+
address: Type.TString;
|
|
83
|
+
project_key: Type.TOptional<Type.TString>;
|
|
84
|
+
}>, Type.TObject<{
|
|
85
|
+
error: Type.TString;
|
|
86
|
+
code: Type.TString;
|
|
87
|
+
}>]>;
|
|
88
|
+
readonly execute: (params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState) => Promise<Outcome<DreamForgetData>>;
|
|
89
|
+
readonly render: (result: Outcome<DreamForgetData>) => string;
|
|
90
|
+
};
|
|
91
|
+
export declare const dreamEndParameters: Type.TObject<{}>;
|
|
92
|
+
export declare const DreamEndDataSchema: Type.TObject<{
|
|
93
|
+
project: Type.TString;
|
|
94
|
+
commit: Type.TOptional<Type.TString>;
|
|
95
|
+
audit_error: Type.TOptional<Type.TString>;
|
|
96
|
+
}>;
|
|
97
|
+
export type DreamEndData = Static<typeof DreamEndDataSchema>;
|
|
98
|
+
export declare const dreamEnd: {
|
|
99
|
+
readonly name: "dream_end";
|
|
100
|
+
readonly label: "Dream end";
|
|
101
|
+
readonly 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.";
|
|
102
|
+
readonly parameters: Type.TObject<{}>;
|
|
103
|
+
readonly outputSchema: Type.TUnion<[Type.TObject<{
|
|
104
|
+
project: Type.TString;
|
|
105
|
+
commit: Type.TOptional<Type.TString>;
|
|
106
|
+
audit_error: Type.TOptional<Type.TString>;
|
|
107
|
+
}>, Type.TObject<{
|
|
108
|
+
error: Type.TString;
|
|
109
|
+
code: Type.TString;
|
|
110
|
+
}>]>;
|
|
111
|
+
readonly execute: (_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState) => Promise<Outcome<DreamEndData>>;
|
|
112
|
+
readonly render: (result: Outcome<DreamEndData>) => string;
|
|
113
|
+
};
|