notesoup 0.41.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/boot/render.js +11 -20
- package/dist/src/boot/snapshot.js +1 -6
- package/dist/src/boot/text.d.ts +12 -0
- package/dist/src/boot/text.js +15 -3
- package/dist/src/budget/parse.d.ts +14 -0
- package/dist/src/budget/parse.js +36 -0
- package/dist/src/budget/policy.js +2 -7
- package/dist/src/budget/text.d.ts +14 -0
- package/dist/src/budget/text.js +14 -0
- package/dist/src/claude/helper.js +24 -4
- package/dist/src/claude/thresholds.d.ts +39 -0
- package/dist/src/claude/thresholds.js +128 -0
- package/dist/src/dream/doctor.js +1 -1
- package/dist/src/dream/jail.js +10 -10
- package/dist/src/dream/lock.js +6 -13
- package/dist/src/dream/report.js +5 -15
- package/dist/src/history/history.js +5 -3
- package/dist/src/history/query.js +14 -26
- package/dist/src/notes/address.d.ts +1 -2
- package/dist/src/notes/address.js +14 -26
- package/dist/src/notes/errors.d.ts +2 -0
- package/dist/src/notes/errors.js +5 -0
- package/dist/src/notes/frontmatter.js +16 -2
- package/dist/src/notes/identity.js +0 -3
- package/dist/src/notes/paths.d.ts +11 -1
- package/dist/src/notes/paths.js +28 -7
- package/dist/src/notes/store.d.ts +1 -0
- package/dist/src/notes/store.js +54 -49
- package/dist/src/pi/boot.js +1 -5
- package/dist/src/pi/budget.d.ts +3 -3
- package/dist/src/pi/budget.js +11 -11
- package/dist/src/pi/dream/cli.js +43 -11
- package/dist/src/pi/estimate.d.ts +1 -5
- package/dist/src/pi/estimate.js +4 -4
- package/dist/src/pi/history.js +1 -4
- package/dist/src/pi/notes/adapter.d.ts +1 -1
- package/dist/src/pi/notes/adapter.js +2 -2
- package/dist/src/pi/reset/artifacts.d.ts +0 -2
- package/dist/src/pi/reset/artifacts.js +4 -4
- package/dist/src/pi/reset/committed.js +2 -2
- package/dist/src/pi/runtime.js +9 -6
- package/dist/src/pi/thresholds.js +5 -9
- package/dist/src/pi/tool-result.d.ts +1 -4
- package/dist/src/pi/tool-result.js +3 -3
- package/dist/src/pi/window.d.ts +5 -0
- package/dist/src/pi/window.js +7 -0
- package/dist/src/settings.d.ts +10 -0
- package/dist/src/settings.js +10 -4
- package/dist/src/tools/history.js +15 -18
- package/dist/src/tools/notes.d.ts +3 -7
- package/dist/src/tools/notes.js +18 -27
- package/dist/src/tools/output.d.ts +2 -3
- package/dist/src/tools/output.js +3 -9
- package/dist/src/tools/result.d.ts +1 -0
- package/dist/src/tools/result.js +15 -21
- package/dist/src/tools/schema.d.ts +0 -1
- package/dist/src/tools/schema.js +3 -4
- package/dist/test/agent-loop.test.js +1 -2
- package/dist/test/boot.integration.test.js +1 -1
- package/dist/test/claude-mod.test.js +425 -23
- package/dist/test/claude-validation.test.d.ts +1 -0
- package/dist/test/claude-validation.test.js +73 -0
- package/dist/test/dream-skill.test.js +2 -4
- package/dist/test/dream.test.js +17 -3
- package/dist/test/helpers/extension.js +1 -1
- package/dist/test/history.integration.test.js +9 -9
- package/dist/test/host-neutral.test.js +16 -1
- package/dist/test/notes-library.test.js +31 -2
- package/dist/test/notes.integration.test.js +11 -11
- package/dist/test/notes.test.js +40 -21
- package/dist/test/reset-lifecycle.test.js +1 -1
- package/docs/claude-code-mod.md +13 -3
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +285 -152
- package/mods/notesoup/hooks/register.ts +308 -51
- package/mods/notesoup/playbook.md +1 -1
- package/mods/notesoup/skills/dream/SKILL.md +1 -1
- package/mods/notesoup/skills/memory/SKILL.md +61 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +5 -3
- package/playbook.md +1 -1
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +1 -1
- package/src/boot/render.ts +11 -21
- package/src/boot/snapshot.ts +2 -7
- package/src/boot/text.ts +21 -3
- package/src/budget/parse.ts +39 -0
- package/src/budget/policy.ts +2 -6
- package/src/budget/text.ts +20 -0
- package/src/claude/helper.ts +22 -5
- package/src/claude/thresholds.ts +153 -0
- package/src/dream/doctor.ts +1 -1
- package/src/dream/jail.ts +10 -10
- package/src/dream/lock.ts +3 -9
- package/src/dream/report.ts +5 -10
- package/src/history/history.ts +5 -3
- package/src/history/query.ts +14 -27
- package/src/notes/address.ts +13 -25
- package/src/notes/errors.ts +6 -0
- package/src/notes/frontmatter.ts +12 -2
- package/src/notes/identity.ts +0 -2
- package/src/notes/paths.ts +23 -5
- package/src/notes/store.ts +50 -48
- package/src/pi/boot.ts +1 -13
- package/src/pi/budget.ts +10 -11
- package/src/pi/dream/cli.ts +35 -10
- package/src/pi/estimate.ts +4 -4
- package/src/pi/history.ts +1 -5
- package/src/pi/notes/adapter.ts +2 -2
- package/src/pi/reset/artifacts.ts +4 -4
- package/src/pi/reset/committed.ts +2 -2
- package/src/pi/runtime.ts +8 -7
- package/src/pi/thresholds.ts +5 -11
- package/src/pi/tool-result.ts +3 -3
- package/src/pi/window.ts +8 -0
- package/src/settings.ts +22 -5
- package/src/tools/history.ts +15 -19
- package/src/tools/notes.ts +21 -32
- package/src/tools/output.ts +3 -12
- package/src/tools/result.ts +14 -19
- package/src/tools/schema.ts +3 -4
- package/dist/src/dream/playbook.d.ts +0 -1
- package/dist/src/dream/playbook.js +0 -2
- package/dist/src/pi/reset/text.d.ts +0 -5
- package/dist/src/pi/reset/text.js +0 -6
- package/src/dream/playbook.ts +0 -3
- package/src/pi/reset/text.ts +0 -10
package/dist/src/boot/render.js
CHANGED
|
@@ -1,15 +1,4 @@
|
|
|
1
1
|
import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_CLOSE_TAG, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock } from "./text.js";
|
|
2
|
-
/** Codex-style <context_window> identity block: the resolved agent and model names plus first/current/previous window ids. */
|
|
3
|
-
function identityBlock(agentName, modelName, firstWindowId, currentWindowId, previousWindowId) {
|
|
4
|
-
const lines = [
|
|
5
|
-
`Agent name: ${agentName} (brain: ${modelName})`,
|
|
6
|
-
`First context window id: ${firstWindowId}`,
|
|
7
|
-
`Current context window id: ${currentWindowId}`,
|
|
8
|
-
];
|
|
9
|
-
if (previousWindowId)
|
|
10
|
-
lines.push(`Previous context window id: ${previousWindowId}`);
|
|
11
|
-
return `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
|
|
12
|
-
}
|
|
13
2
|
function relativeTime(timestamp, now) {
|
|
14
3
|
const seconds = Math.trunc((timestamp - now) / 1000);
|
|
15
4
|
if (seconds === 0)
|
|
@@ -19,9 +8,6 @@ function relativeTime(timestamp, now) {
|
|
|
19
8
|
const amount = `${Math.abs(Math.trunc(seconds / size))}${unit}`;
|
|
20
9
|
return seconds > 0 ? `in ${amount}` : `${amount} ago`;
|
|
21
10
|
}
|
|
22
|
-
function rowsFor(snapshot, scope) {
|
|
23
|
-
return snapshot.homes.get(scope) ?? [];
|
|
24
|
-
}
|
|
25
11
|
/** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
|
|
26
12
|
const FEED_TITLE_MAX_CHARS = 40;
|
|
27
13
|
function feedTitle(body) {
|
|
@@ -56,7 +42,7 @@ function notesIndex(snapshot, tools) {
|
|
|
56
42
|
shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
|
|
57
43
|
continue;
|
|
58
44
|
}
|
|
59
|
-
const rows =
|
|
45
|
+
const rows = (snapshot.homes.get(home.scope) ?? []).filter((row) => row.meta.crumpledAt === undefined);
|
|
60
46
|
const map = rows.find((row) => row.path === "MAP.md");
|
|
61
47
|
const fresh = rows
|
|
62
48
|
.filter((row) => row.path !== "MAP.md")
|
|
@@ -87,9 +73,14 @@ function mapBodyForBoot(address, body) {
|
|
|
87
73
|
return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
|
|
88
74
|
}
|
|
89
75
|
export function renderBootBlock(data) {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
76
|
+
// Codex-style <context_window> identity block: the resolved agent and model names plus
|
|
77
|
+
// first/current/previous window ids.
|
|
78
|
+
const lines = [
|
|
79
|
+
`Agent name: ${data.agentName} (brain: ${data.modelName})`,
|
|
80
|
+
`First context window id: ${data.firstWindowId}`,
|
|
81
|
+
`Current context window id: ${data.currentWindowId}`,
|
|
82
|
+
...(data.previousWindowId ? [`Previous context window id: ${data.previousWindowId}`] : []),
|
|
83
|
+
];
|
|
84
|
+
const identity = `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
|
|
85
|
+
return [identity, renderProtocolBlock(data.tools), notesIndex(data.notes, data.tools)].join("\n\n");
|
|
95
86
|
}
|
|
@@ -7,18 +7,13 @@ const NOTES_HOMES = [
|
|
|
7
7
|
{ scope: "agent", label: "@self" },
|
|
8
8
|
{ scope: "model", label: "@model" },
|
|
9
9
|
];
|
|
10
|
-
function queryForScope(scope) {
|
|
11
|
-
if (scope === "agent" || scope === "model")
|
|
12
|
-
return { scope };
|
|
13
|
-
return { scope };
|
|
14
|
-
}
|
|
15
10
|
/**
|
|
16
11
|
* Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
|
|
17
12
|
* malformed note data and unrelated construction errors remain visible to the caller.
|
|
18
13
|
*/
|
|
19
14
|
export async function loadNotesSnapshot(identity, openedAt, loadHome) {
|
|
20
15
|
const store = createNotesStore(identity);
|
|
21
|
-
const load = loadHome ?? ((scope) => store.list(
|
|
16
|
+
const load = loadHome ?? ((scope) => store.list({ scope }));
|
|
22
17
|
const homes = new Map();
|
|
23
18
|
const unavailable = [];
|
|
24
19
|
for (const home of NOTES_HOMES) {
|
package/dist/src/boot/text.d.ts
CHANGED
|
@@ -6,6 +6,13 @@ export declare const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
|
|
|
6
6
|
export declare const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
|
|
7
7
|
export declare const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
|
|
8
8
|
export declare const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
|
|
9
|
+
/**
|
|
10
|
+
* The one sentence that tells the model how to end its window voluntarily. A host with no
|
|
11
|
+
* model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
|
|
12
|
+
*/
|
|
13
|
+
export declare const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
|
|
14
|
+
/** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
|
|
15
|
+
export declare const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
|
|
9
16
|
/** Logical tool names are supplied by the composing host, not discovered here. */
|
|
10
17
|
export type BootToolNames = Readonly<{
|
|
11
18
|
notes: string;
|
|
@@ -13,5 +20,10 @@ export type BootToolNames = Readonly<{
|
|
|
13
20
|
history: string;
|
|
14
21
|
remaining: string;
|
|
15
22
|
wipe: string;
|
|
23
|
+
/**
|
|
24
|
+
* Replaces the whole voluntary-wipe sentence (PROTOCOL_WIPE_SENTENCE) when the host has
|
|
25
|
+
* no model-facing reset tool. Absent means Pi's default sentence, byte for byte.
|
|
26
|
+
*/
|
|
27
|
+
wipeSentence?: string;
|
|
16
28
|
}>;
|
|
17
29
|
export declare function renderProtocolBlock(tools: BootToolNames): string;
|
package/dist/src/boot/text.js
CHANGED
|
@@ -6,6 +6,13 @@ export const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
|
|
|
6
6
|
export const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
|
|
7
7
|
export const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
|
|
8
8
|
export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
|
|
9
|
+
/**
|
|
10
|
+
* The one sentence that tells the model how to end its window voluntarily. A host with no
|
|
11
|
+
* model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
|
|
12
|
+
*/
|
|
13
|
+
export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `clear_memory` and erase yourself with dignity.";
|
|
14
|
+
/** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
|
|
15
|
+
export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/clear-memory`.";
|
|
9
16
|
/**
|
|
10
17
|
* Static protocol teaching adapted from Codex's token_budget.guidance_message to
|
|
11
18
|
* notesoup's tool names. It lives once per window in the persisted boot block;
|
|
@@ -27,7 +34,7 @@ Notes are for what's true NOW. Not a diary of every dumb thing you did on the wa
|
|
|
27
34
|
*flips a page* "First I tried this, then that broke, then—" Nobody reads that!
|
|
28
35
|
Something's not true anymore? Cross it out! Write the right thing!
|
|
29
36
|
|
|
30
|
-
\`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it.
|
|
37
|
+
\`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}
|
|
31
38
|
|
|
32
39
|
An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
|
|
33
40
|
|
|
@@ -43,7 +50,7 @@ Still a tie? *shrugs* You've got a brain. Use it.
|
|
|
43
50
|
|
|
44
51
|
Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
|
|
45
52
|
|
|
46
|
-
\`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each
|
|
53
|
+
\`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each may carry a short Cheatsheet of rules that always apply (about 5 lines); the rest is the note index, with addresses and gists for lookup. Keep each one current.
|
|
47
54
|
${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
|
|
48
55
|
export function renderProtocolBlock(tools) {
|
|
49
56
|
const names = {
|
|
@@ -52,5 +59,10 @@ export function renderProtocolBlock(tools) {
|
|
|
52
59
|
get_context_remaining: tools.remaining,
|
|
53
60
|
clear_memory: tools.wipe,
|
|
54
61
|
};
|
|
55
|
-
|
|
62
|
+
// The sentence is replaced before name substitution, so a replacement may speak the host's
|
|
63
|
+
// own words (a command line, a tool name) instead of any `notes_*`-style token.
|
|
64
|
+
const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
|
|
65
|
+
? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence)
|
|
66
|
+
: PROTOCOL_BLOCK;
|
|
67
|
+
return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
|
|
56
68
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scalar guards shared by the budget derivations. Settings and environment values arrive
|
|
3
|
+
* untyped from either host, so numbers, percentages and presence flags are validated here
|
|
4
|
+
* once instead of once per call site.
|
|
5
|
+
*/
|
|
6
|
+
/** A finite number, from a typed value or an environment string; anything else is unknown. */
|
|
7
|
+
export declare function numberOf(value: unknown): number | undefined;
|
|
8
|
+
export declare function positiveNumber(value: unknown): number | undefined;
|
|
9
|
+
/** A margin or window is usable only as a positive safe integer. */
|
|
10
|
+
export declare function positiveInteger(value: unknown): number | undefined;
|
|
11
|
+
/** A percentage override is usable only in (0, 100]. */
|
|
12
|
+
export declare function percent(value: unknown): number | undefined;
|
|
13
|
+
/** Presence-style flags (DISABLE_*): any value but an explicit no counts as on. */
|
|
14
|
+
export declare function presenceFlag(value: unknown): boolean;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scalar guards shared by the budget derivations. Settings and environment values arrive
|
|
3
|
+
* untyped from either host, so numbers, percentages and presence flags are validated here
|
|
4
|
+
* once instead of once per call site.
|
|
5
|
+
*/
|
|
6
|
+
/** A finite number, from a typed value or an environment string; anything else is unknown. */
|
|
7
|
+
export function numberOf(value) {
|
|
8
|
+
if (typeof value === "number")
|
|
9
|
+
return Number.isFinite(value) ? value : undefined;
|
|
10
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
11
|
+
const parsed = Number(value);
|
|
12
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
13
|
+
}
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
export function positiveNumber(value) {
|
|
17
|
+
const parsed = numberOf(value);
|
|
18
|
+
return parsed !== undefined && parsed > 0 ? parsed : undefined;
|
|
19
|
+
}
|
|
20
|
+
/** A margin or window is usable only as a positive safe integer. */
|
|
21
|
+
export function positiveInteger(value) {
|
|
22
|
+
const parsed = numberOf(value);
|
|
23
|
+
return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
|
24
|
+
}
|
|
25
|
+
/** A percentage override is usable only in (0, 100]. */
|
|
26
|
+
export function percent(value) {
|
|
27
|
+
const parsed = numberOf(value);
|
|
28
|
+
return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
|
|
29
|
+
}
|
|
30
|
+
/** Presence-style flags (DISABLE_*): any value but an explicit no counts as on. */
|
|
31
|
+
export function presenceFlag(value) {
|
|
32
|
+
if (typeof value !== "string")
|
|
33
|
+
return false;
|
|
34
|
+
const text = value.trim().toLowerCase();
|
|
35
|
+
return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
|
|
36
|
+
}
|
|
@@ -1,11 +1,6 @@
|
|
|
1
1
|
import { DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "./constants.js";
|
|
2
|
+
import { positiveInteger } from "./parse.js";
|
|
2
3
|
import { NOTESOUP_SETTINGS_KEY } from "../settings.js";
|
|
3
|
-
/** A margin is usable only as a positive integer; anything else is ignored. */
|
|
4
|
-
function validMargin(raw) {
|
|
5
|
-
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0)
|
|
6
|
-
return undefined;
|
|
7
|
-
return raw;
|
|
8
|
-
}
|
|
9
4
|
/**
|
|
10
5
|
* Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
|
|
11
6
|
* plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
|
|
@@ -20,7 +15,7 @@ export function deriveThresholds(reserveTokens, margins) {
|
|
|
20
15
|
if (margins.reminderMarginTokens === undefined)
|
|
21
16
|
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
22
17
|
else {
|
|
23
|
-
const parsed =
|
|
18
|
+
const parsed = positiveInteger(margins.reminderMarginTokens);
|
|
24
19
|
if (parsed === undefined) {
|
|
25
20
|
warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
|
|
26
21
|
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
export declare const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
|
|
2
2
|
export declare const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
|
|
3
|
+
/**
|
|
4
|
+
* The single reset message: the only reset prose persisted, carried by the continuation entry.
|
|
5
|
+
*/
|
|
6
|
+
export declare const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
|
|
7
|
+
/**
|
|
8
|
+
* The shared warning body: the one text both hosts show before a reset. Only the closing
|
|
9
|
+
* instruction differs — Pi can reset the model itself, Claude can only end the turn.
|
|
10
|
+
*/
|
|
11
|
+
export declare const WARNING_BODY = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
|
|
12
|
+
export declare const WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.";
|
|
13
|
+
/** The shared hidden checkpoint text: one manual/budget-triggered request, both hosts. */
|
|
14
|
+
export declare const WARNING_CONTENT = "<context_window_guidance>\nThis context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.\n</context_window_guidance>";
|
|
15
|
+
/** Claude's variant: the mod resets after the turn, so the model only has to stop. */
|
|
16
|
+
export declare const CLAUDE_WARNING_PROMPT = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, end your turn; the reset runs after it.";
|
|
3
17
|
/**
|
|
4
18
|
* Codex-equivalent low-budget reminder. The measured remaining count is frozen into
|
|
5
19
|
* the text at the crossing that fires it, so each persisted copy is a snapshot true
|
package/dist/src/budget/text.js
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
|
|
2
2
|
export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
|
|
3
|
+
/**
|
|
4
|
+
* The single reset message: the only reset prose persisted, carried by the continuation entry.
|
|
5
|
+
*/
|
|
6
|
+
export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
|
|
7
|
+
/**
|
|
8
|
+
* The shared warning body: the one text both hosts show before a reset. Only the closing
|
|
9
|
+
* instruction differs — Pi can reset the model itself, Claude can only end the turn.
|
|
10
|
+
*/
|
|
11
|
+
export const WARNING_BODY = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
|
|
12
|
+
export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
|
|
13
|
+
/** The shared hidden checkpoint text: one manual/budget-triggered request, both hosts. */
|
|
14
|
+
export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
|
|
15
|
+
/** Claude's variant: the mod resets after the turn, so the model only has to stop. */
|
|
16
|
+
export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
|
|
3
17
|
/**
|
|
4
18
|
* Codex-equivalent low-budget reminder. The measured remaining count is frozen into
|
|
5
19
|
* the text at the crossing that fires it, so each persisted copy is a snapshot true
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { realpathSync } from "node:fs";
|
|
2
2
|
import { pathToFileURL } from "node:url";
|
|
3
|
-
import { Check } from "typebox/value";
|
|
3
|
+
import { Check, Errors } from "typebox/value";
|
|
4
4
|
import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
|
|
5
5
|
import { loadNotesSnapshot } from "../boot/snapshot.js";
|
|
6
6
|
import { renderBootBlock } from "../boot/render.js";
|
|
7
|
+
import { CLAUDE_WIPE_SENTENCE } from "../boot/text.js";
|
|
8
|
+
import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
|
|
9
|
+
import { resolveClaudeLimits } from "./thresholds.js";
|
|
7
10
|
import { projectKey } from "../notes/paths.js";
|
|
8
11
|
import { snapshotNotesIdentity } from "../notes/identity.js";
|
|
9
12
|
const MAX_REQUEST_BYTES = 512 * 1024;
|
|
@@ -14,7 +17,16 @@ function identity(input) {
|
|
|
14
17
|
throw new Error("invalid identity");
|
|
15
18
|
return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
|
|
16
19
|
}
|
|
17
|
-
|
|
20
|
+
/** The first schema violation, named by parameter so the model can fix that one field. */
|
|
21
|
+
function paramProblem(schema, params) {
|
|
22
|
+
// A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
|
|
23
|
+
const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
|
|
24
|
+
if (!first)
|
|
25
|
+
return "unrecognized shape";
|
|
26
|
+
const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
|
|
27
|
+
const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
|
|
28
|
+
return `${field ? `${field} ` : ""}${first.message}${extra}`;
|
|
29
|
+
}
|
|
18
30
|
/** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
|
|
19
31
|
function boundOperation(operation, ...rest) {
|
|
20
32
|
return {
|
|
@@ -23,7 +35,7 @@ function boundOperation(operation, ...rest) {
|
|
|
23
35
|
async call(params, id) {
|
|
24
36
|
// Refuse before the operation can act: a rejected shape never reaches a write.
|
|
25
37
|
if (!Check(operation.parameters, params))
|
|
26
|
-
throw new Error(`invalid ${operation.name} parameters`);
|
|
38
|
+
throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
|
|
27
39
|
// The same business outcome and the same renderer as the Pi tool; only the envelope differs.
|
|
28
40
|
const outcome = await operation.execute(params, id, ...rest);
|
|
29
41
|
return { text: operation.render(outcome), outcome };
|
|
@@ -46,7 +58,15 @@ export async function dispatch(request) {
|
|
|
46
58
|
throw new Error("malformed request");
|
|
47
59
|
const value = request;
|
|
48
60
|
if (value.op === "schemas")
|
|
49
|
-
return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema:
|
|
61
|
+
return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
|
|
62
|
+
// The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
|
|
63
|
+
// cannot drift apart. The hooks module caches one copy per session.
|
|
64
|
+
if (value.op === "texts")
|
|
65
|
+
return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
|
|
66
|
+
// Threshold derivation crosses the boundary as raw facts: everything the engine could
|
|
67
|
+
// read, unvalidated. resolveClaudeLimits guards every field and never throws.
|
|
68
|
+
if (value.op === "limits")
|
|
69
|
+
return resolveClaudeLimits(value.facts);
|
|
50
70
|
if (value.op === "tool") {
|
|
51
71
|
if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool))
|
|
52
72
|
throw new Error("unknown tool");
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
|
|
3
|
+
*
|
|
4
|
+
* Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
|
|
5
|
+
* `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
|
|
6
|
+
* and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
|
|
7
|
+
* notesoup can resolve the same point from settings and environment alone when the
|
|
8
|
+
* undocumented `usage({breakdown:true})` field is missing.
|
|
9
|
+
*/
|
|
10
|
+
/** Claude's summary buffer between the output reserve and the auto-compact point. */
|
|
11
|
+
export declare const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13000;
|
|
12
|
+
/** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
|
|
13
|
+
export declare const CLAUDE_OUTPUT_RESERVE_TOKENS = 20000;
|
|
14
|
+
/** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
|
|
15
|
+
export declare const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8192;
|
|
16
|
+
export type ClaudeLimitSource = "auto-compact" | "window" | "percent";
|
|
17
|
+
export type ClaudeLimits = {
|
|
18
|
+
/** Which field produced the point: Claude's own threshold, a computed window, or the percent fallback. */
|
|
19
|
+
readonly source: ClaudeLimitSource;
|
|
20
|
+
/** False when automatic compaction is off, so the point sits at the hard window instead. */
|
|
21
|
+
readonly autoCompact: boolean;
|
|
22
|
+
/** Which measured field the points are expressed in. */
|
|
23
|
+
readonly unit: "tokens" | "percent";
|
|
24
|
+
/** Claude's effective auto-compact point. */
|
|
25
|
+
readonly native: number;
|
|
26
|
+
/** Where notesoup resets: native minus the reset margin. */
|
|
27
|
+
readonly reset: number;
|
|
28
|
+
/** Where the one warning per window fires: reset minus the warning runway. */
|
|
29
|
+
readonly warn: number;
|
|
30
|
+
readonly resetMargin: number;
|
|
31
|
+
readonly warningRunway: number;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
|
|
35
|
+
* so a missing or malformed one degrades to the next source and finally to the percent
|
|
36
|
+
* fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
|
|
37
|
+
* helper boundary, where nothing is typed.
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveClaudeLimits(facts: unknown): ClaudeLimits;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
|
|
2
|
+
import { percent, positiveInteger, positiveNumber, presenceFlag } from "../budget/parse.js";
|
|
3
|
+
import { isPlainObject, mergeNotesoupSettings } from "../settings.js";
|
|
4
|
+
/**
|
|
5
|
+
* Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
|
|
6
|
+
*
|
|
7
|
+
* Claude compacts at `min(floor((W_eff - out) * pct/100), W_eff - out - 13000)`, where
|
|
8
|
+
* `W_eff` is the resolved auto-compact window, `out` is the output reserve (capped at 20000),
|
|
9
|
+
* and `pct` is CLAUDE_AUTOCOMPACT_PCT_OVERRIDE. This module mirrors those constants so
|
|
10
|
+
* notesoup can resolve the same point from settings and environment alone when the
|
|
11
|
+
* undocumented `usage({breakdown:true})` field is missing.
|
|
12
|
+
*/
|
|
13
|
+
/** Claude's summary buffer between the output reserve and the auto-compact point. */
|
|
14
|
+
export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
|
|
15
|
+
/** Claude's cap on the reserved output tokens; the mod cannot read the model's own value. */
|
|
16
|
+
export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
|
|
17
|
+
/** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
|
|
18
|
+
export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
|
|
19
|
+
/**
|
|
20
|
+
* A point is never expressed as zero: the mod reads `measured >= reset` as due, so a zero point
|
|
21
|
+
* would clear memory on every turn, including a fresh window. A window smaller than Claude's own
|
|
22
|
+
* reserves therefore resets at the smallest expressible point instead.
|
|
23
|
+
*/
|
|
24
|
+
const MIN_POINT_TOKENS = 1;
|
|
25
|
+
/** The same floor in percent units, for the no-window fallback. */
|
|
26
|
+
const MIN_POINT_PERCENT = 0.1;
|
|
27
|
+
/**
|
|
28
|
+
* The percent fallback assumes the classic 200K model window: it is reached only when
|
|
29
|
+
* `usage()` reports no window and no breakdown, and it reproduces the token maths below
|
|
30
|
+
* on that window (about 83.5% / 79.4% / 71.2%).
|
|
31
|
+
*/
|
|
32
|
+
const ASSUMED_WINDOW_TOKENS = 200_000;
|
|
33
|
+
/**
|
|
34
|
+
* The active auto-compact flag: absent means Claude's default (on), and only an explicit
|
|
35
|
+
* boolean counts. Settings are read from one host-supplied scope, so the flag is top-level.
|
|
36
|
+
*/
|
|
37
|
+
function settingFlag(settings) {
|
|
38
|
+
return isPlainObject(settings) && typeof settings.autoCompactEnabled === "boolean" ? settings.autoCompactEnabled : undefined;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The configured auto-compact window, smallest first: CLAUDE_CODE_AUTO_COMPACT_WINDOW,
|
|
42
|
+
* modelSettings.<model>.autoCompactWindow, then the top-level autoCompactWindow. Taking the
|
|
43
|
+
* smallest present value keeps notesoup's reset ahead of whichever one Claude would use.
|
|
44
|
+
*/
|
|
45
|
+
function configuredWindow(settings, env, model) {
|
|
46
|
+
const windows = [];
|
|
47
|
+
const fromEnv = positiveNumber(env.autoCompactWindow);
|
|
48
|
+
if (fromEnv !== undefined)
|
|
49
|
+
windows.push(fromEnv);
|
|
50
|
+
if (typeof model === "string" && model.length > 0 && isPlainObject(settings)) {
|
|
51
|
+
const modelSettings = isPlainObject(settings.modelSettings) ? settings.modelSettings : {};
|
|
52
|
+
const perModel = modelSettings[model];
|
|
53
|
+
if (isPlainObject(perModel)) {
|
|
54
|
+
const value = positiveNumber(perModel.autoCompactWindow);
|
|
55
|
+
if (value !== undefined)
|
|
56
|
+
windows.push(value);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (isPlainObject(settings)) {
|
|
60
|
+
const value = positiveNumber(settings.autoCompactWindow);
|
|
61
|
+
if (value !== undefined)
|
|
62
|
+
windows.push(value);
|
|
63
|
+
}
|
|
64
|
+
return windows.length === 0 ? undefined : Math.min(...windows);
|
|
65
|
+
}
|
|
66
|
+
function tokenLimits(source, autoCompact, native, resetMargin, warningRunway) {
|
|
67
|
+
const tokens = Math.max(0, Math.floor(native));
|
|
68
|
+
const reset = Math.max(MIN_POINT_TOKENS, tokens - resetMargin);
|
|
69
|
+
return {
|
|
70
|
+
source, autoCompact, unit: "tokens",
|
|
71
|
+
native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
|
|
75
|
+
function percentLimits(autoCompact, pct, resetMargin, warningRunway) {
|
|
76
|
+
const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
|
|
77
|
+
const native = pct === undefined ? base : Math.min(pct, base);
|
|
78
|
+
const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
|
|
79
|
+
return {
|
|
80
|
+
source: "percent", autoCompact, unit: "percent",
|
|
81
|
+
native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
|
|
86
|
+
* so a missing or malformed one degrades to the next source and finally to the percent
|
|
87
|
+
* fallback; resolution never throws. `facts` is deliberately unknown: it crosses the mod
|
|
88
|
+
* helper boundary, where nothing is typed.
|
|
89
|
+
*/
|
|
90
|
+
export function resolveClaudeLimits(facts) {
|
|
91
|
+
const root = isPlainObject(facts) ? facts : {};
|
|
92
|
+
const usage = isPlainObject(root.usage) ? root.usage : {};
|
|
93
|
+
const breakdown = isPlainObject(root.breakdown) ? root.breakdown : {};
|
|
94
|
+
const env = isPlainObject(root.env) ? root.env : {};
|
|
95
|
+
const settings = root.settings;
|
|
96
|
+
// The host hands over its merged settings, so there is no separate project scope to name.
|
|
97
|
+
const margins = mergeNotesoupSettings(settings, undefined);
|
|
98
|
+
const resetMargin = positiveInteger(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
|
|
99
|
+
const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
|
|
100
|
+
const autoCompact = settingFlag(settings) !== false
|
|
101
|
+
&& !presenceFlag(env.disableAutoCompact)
|
|
102
|
+
&& breakdown.isAutoCompactEnabled !== false;
|
|
103
|
+
const pct = percent(env.pctOverride);
|
|
104
|
+
// (a) Claude's own point. It already includes the window, model settings and CLI flag; only
|
|
105
|
+
// the percent override is applied separately, on the window-after-output-reserve it is
|
|
106
|
+
// minted from (threshold + summary buffer). A malformed override that floors the point to
|
|
107
|
+
// zero is not a point at all, so it degrades to the next source instead of resetting always.
|
|
108
|
+
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
109
|
+
if (autoCompact && threshold !== undefined) {
|
|
110
|
+
const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
111
|
+
if (native > 0)
|
|
112
|
+
return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
|
|
113
|
+
}
|
|
114
|
+
// (b) The same point computed from the reported window plus settings and environment. A real
|
|
115
|
+
// window always answers here: falling through to the percent fallback would express the
|
|
116
|
+
// points on an assumed 200K window, which is later than the window notesoup can see.
|
|
117
|
+
const window = positiveNumber(usage.window);
|
|
118
|
+
if (window !== undefined) {
|
|
119
|
+
const configured = configuredWindow(settings, env, breakdown.model);
|
|
120
|
+
const effective = Math.min(configured ?? window, window);
|
|
121
|
+
const native = autoCompact
|
|
122
|
+
? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
|
|
123
|
+
: effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
124
|
+
return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
|
|
125
|
+
}
|
|
126
|
+
// (c) Nothing usable but percentages.
|
|
127
|
+
return percentLimits(autoCompact, pct, resetMargin, warningRunway);
|
|
128
|
+
}
|
package/dist/src/dream/doctor.js
CHANGED
|
@@ -77,7 +77,7 @@ export function doctor(home) {
|
|
|
77
77
|
report(path, `${address}: target missing; update or remove the reference`);
|
|
78
78
|
}
|
|
79
79
|
catch {
|
|
80
|
-
report(path, `${address}
|
|
80
|
+
report(path, `${address} isn't a note address. ${ADDRESS_FORMS}`);
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
83
|
};
|
package/dist/src/dream/jail.js
CHANGED
|
@@ -11,12 +11,12 @@ export async function jailWritePath(notesHome, path, options = {}) {
|
|
|
11
11
|
realNotesHome = await realpath(notesHome);
|
|
12
12
|
}
|
|
13
13
|
catch {
|
|
14
|
-
throw new Error(`
|
|
14
|
+
throw new Error(`Can't open the notes home ${notesHome}.`);
|
|
15
15
|
}
|
|
16
16
|
const target = resolve(realNotesHome, path);
|
|
17
17
|
const targetParent = dirname(target);
|
|
18
18
|
if (isOutside(realNotesHome, targetParent))
|
|
19
|
-
throw new Error(
|
|
19
|
+
throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
|
|
20
20
|
// write creates parent directories itself. Create only after the lexical check, then
|
|
21
21
|
// canonicalize the parent so a symlink cannot lead the underlying tool out of home.
|
|
22
22
|
// delete passes createParent:false: the parent must already exist for there to be anything to remove.
|
|
@@ -27,17 +27,17 @@ export async function jailWritePath(notesHome, path, options = {}) {
|
|
|
27
27
|
realTargetParent = await realpath(targetParent);
|
|
28
28
|
}
|
|
29
29
|
catch {
|
|
30
|
-
throw new Error(`
|
|
30
|
+
throw new Error(`Can't open the folder of ${path} in the notes home.`);
|
|
31
31
|
}
|
|
32
32
|
if (isOutside(realNotesHome, realTargetParent))
|
|
33
|
-
throw new Error(
|
|
33
|
+
throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
|
|
34
34
|
let targetStats;
|
|
35
35
|
try {
|
|
36
36
|
targetStats = await lstat(target);
|
|
37
37
|
}
|
|
38
38
|
catch (error) {
|
|
39
39
|
if (error.code !== "ENOENT")
|
|
40
|
-
throw new Error(`
|
|
40
|
+
throw new Error(`Can't check ${path} in the notes home.`);
|
|
41
41
|
}
|
|
42
42
|
if (targetStats?.isSymbolicLink()) {
|
|
43
43
|
let realTarget;
|
|
@@ -45,13 +45,13 @@ export async function jailWritePath(notesHome, path, options = {}) {
|
|
|
45
45
|
realTarget = await realpath(target);
|
|
46
46
|
}
|
|
47
47
|
catch {
|
|
48
|
-
throw new Error(`
|
|
48
|
+
throw new Error(`Can't follow the link at ${path} in the notes home.`);
|
|
49
49
|
}
|
|
50
50
|
if (isOutside(realNotesHome, realTarget))
|
|
51
|
-
throw new Error(
|
|
51
|
+
throw new Error(`${path} is outside the notes home ${notesHome}; dreams only write inside it.`);
|
|
52
52
|
}
|
|
53
53
|
if (targetStats && targetStats.nlink > 1)
|
|
54
|
-
throw new Error(
|
|
54
|
+
throw new Error(`${path} has other hard links, which may reach outside the notes home; leave it alone.`);
|
|
55
55
|
return target;
|
|
56
56
|
}
|
|
57
57
|
/** Physical deletion refuses live notes even before playbook policy is consulted. */
|
|
@@ -62,10 +62,10 @@ export async function deleteCrumpledNote(notesHome, path) {
|
|
|
62
62
|
raw = await readFile(target, "utf8");
|
|
63
63
|
}
|
|
64
64
|
catch (error) {
|
|
65
|
-
throw new Error(`
|
|
65
|
+
throw new Error(`Can't read ${path} in the notes home: ${error.message}`);
|
|
66
66
|
}
|
|
67
67
|
if (parseNote(raw).meta.crumpledAt === undefined)
|
|
68
|
-
throw new Error(
|
|
68
|
+
throw new Error(`${path} isn't crumpled; only crumpled notes can be deleted.`);
|
|
69
69
|
await unlink(target);
|
|
70
70
|
return { content: [{ type: "text", text: `deleted ${path}` }], details: undefined };
|
|
71
71
|
}
|
package/dist/src/dream/lock.js
CHANGED
|
@@ -16,18 +16,6 @@ function readText(path) {
|
|
|
16
16
|
return undefined;
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
function stampMtime(stampPath) {
|
|
20
|
-
try {
|
|
21
|
-
return statSync(stampPath).mtimeMs;
|
|
22
|
-
}
|
|
23
|
-
catch {
|
|
24
|
-
return undefined;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Cleanup ownership: only the exact marker this run wrote may be removed. The token is
|
|
29
|
-
* diagnostic and guards cleanup; it never grants permission to take an existing lock.
|
|
30
|
-
*/
|
|
31
19
|
function ownsLock(lock) {
|
|
32
20
|
if (!lock.held || !lock.token)
|
|
33
21
|
return false;
|
|
@@ -41,7 +29,12 @@ function ownsLock(lock) {
|
|
|
41
29
|
*/
|
|
42
30
|
export function acquireLock(path) {
|
|
43
31
|
const now = Date.now();
|
|
44
|
-
|
|
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 */ }
|
|
45
38
|
const token = randomUUID();
|
|
46
39
|
try {
|
|
47
40
|
writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
|