notesoup 0.42.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.js +1 -1
- 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 +2 -0
- package/dist/src/budget/text.js +2 -0
- package/dist/src/claude/helper.js +1 -2
- package/dist/src/claude/thresholds.js +45 -66
- package/dist/src/dream/lock.js +6 -13
- package/dist/src/dream/report.js +5 -15
- package/dist/src/history/history.js +4 -2
- package/dist/src/history/query.js +10 -22
- package/dist/src/notes/address.d.ts +0 -1
- package/dist/src/notes/address.js +5 -17
- 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 +38 -37
- 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 +8 -5
- 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 +1 -1
- package/dist/src/pi/window.d.ts +5 -0
- package/dist/src/pi/window.js +7 -0
- package/dist/src/settings.d.ts +2 -0
- package/dist/src/settings.js +4 -3
- package/dist/src/tools/history.js +4 -7
- package/dist/src/tools/notes.d.ts +0 -4
- package/dist/src/tools/notes.js +6 -16
- package/dist/src/tools/output.d.ts +0 -3
- package/dist/src/tools/output.js +1 -9
- package/dist/src/tools/result.d.ts +1 -0
- package/dist/src/tools/result.js +14 -20
- package/dist/src/tools/schema.d.ts +0 -1
- package/dist/src/tools/schema.js +0 -1
- 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 +221 -9
- 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 +14 -0
- package/dist/test/helpers/extension.js +1 -1
- package/dist/test/history.integration.test.js +2 -1
- package/dist/test/host-neutral.test.js +15 -0
- package/dist/test/notes-library.test.js +30 -1
- package/dist/test/notes.integration.test.js +7 -7
- package/dist/test/notes.test.js +24 -5
- package/dist/test/reset-lifecycle.test.js +1 -1
- package/docs/claude-code-mod.md +5 -3
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +147 -173
- package/mods/notesoup/hooks/register.ts +158 -67
- 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/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 +1 -1
- package/src/budget/parse.ts +39 -0
- package/src/budget/policy.ts +2 -6
- package/src/budget/text.ts +3 -0
- package/src/claude/helper.ts +2 -2
- package/src/claude/thresholds.ts +45 -62
- package/src/dream/lock.ts +3 -9
- package/src/dream/report.ts +5 -10
- package/src/history/history.ts +4 -2
- package/src/history/query.ts +10 -23
- package/src/notes/address.ts +4 -16
- 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 +33 -36
- 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 +7 -6
- package/src/pi/thresholds.ts +5 -11
- package/src/pi/tool-result.ts +1 -1
- package/src/pi/window.ts +8 -0
- package/src/settings.ts +4 -3
- package/src/tools/history.ts +4 -8
- package/src/tools/notes.ts +7 -20
- package/src/tools/output.ts +1 -12
- package/src/tools/result.ts +14 -19
- package/src/tools/schema.ts +0 -1
- 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 -4
- package/dist/src/pi/reset/text.js +0 -7
- package/src/dream/playbook.ts +0 -3
- package/src/pi/reset/text.ts +0 -9
package/src/boot/render.ts
CHANGED
|
@@ -1,17 +1,6 @@
|
|
|
1
1
|
import type { NotesHome, NotesSnapshot } from "./snapshot.js";
|
|
2
2
|
import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_CLOSE_TAG, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock, type BootToolNames } from "./text.js";
|
|
3
3
|
|
|
4
|
-
/** Codex-style <context_window> identity block: the resolved agent and model names plus first/current/previous window ids. */
|
|
5
|
-
function identityBlock(agentName: string, modelName: string, firstWindowId: string, currentWindowId: string, previousWindowId?: string): string {
|
|
6
|
-
const lines = [
|
|
7
|
-
`Agent name: ${agentName} (brain: ${modelName})`,
|
|
8
|
-
`First context window id: ${firstWindowId}`,
|
|
9
|
-
`Current context window id: ${currentWindowId}`,
|
|
10
|
-
];
|
|
11
|
-
if (previousWindowId) lines.push(`Previous context window id: ${previousWindowId}`);
|
|
12
|
-
return `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
4
|
function relativeTime(timestamp: number, now: number): string {
|
|
16
5
|
const seconds = Math.trunc((timestamp - now) / 1000);
|
|
17
6
|
if (seconds === 0) return "just now";
|
|
@@ -21,10 +10,6 @@ function relativeTime(timestamp: number, now: number): string {
|
|
|
21
10
|
return seconds > 0 ? `in ${amount}` : `${amount} ago`;
|
|
22
11
|
}
|
|
23
12
|
|
|
24
|
-
function rowsFor(snapshot: NotesSnapshot, scope: NotesHome["scope"]) {
|
|
25
|
-
return snapshot.homes.get(scope) ?? [];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
13
|
/** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
|
|
29
14
|
const FEED_TITLE_MAX_CHARS = 40;
|
|
30
15
|
|
|
@@ -63,7 +48,7 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
|
|
|
63
48
|
shelves.push(section(home.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
|
|
64
49
|
continue;
|
|
65
50
|
}
|
|
66
|
-
const rows =
|
|
51
|
+
const rows = (snapshot.homes.get(home.scope) ?? []).filter((row) => row.meta.crumpledAt === undefined);
|
|
67
52
|
const map = rows.find((row) => row.path === "MAP.md");
|
|
68
53
|
const fresh = rows
|
|
69
54
|
.filter((row) => row.path !== "MAP.md")
|
|
@@ -107,9 +92,14 @@ export type BootRenderData = {
|
|
|
107
92
|
};
|
|
108
93
|
|
|
109
94
|
export function renderBootBlock(data: BootRenderData): string {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
95
|
+
// Codex-style <context_window> identity block: the resolved agent and model names plus
|
|
96
|
+
// first/current/previous window ids.
|
|
97
|
+
const lines = [
|
|
98
|
+
`Agent name: ${data.agentName} (brain: ${data.modelName})`,
|
|
99
|
+
`First context window id: ${data.firstWindowId}`,
|
|
100
|
+
`Current context window id: ${data.currentWindowId}`,
|
|
101
|
+
...(data.previousWindowId ? [`Previous context window id: ${data.previousWindowId}`] : []),
|
|
102
|
+
];
|
|
103
|
+
const identity = `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
|
|
104
|
+
return [identity, renderProtocolBlock(data.tools), notesIndex(data.notes, data.tools)].join("\n\n");
|
|
115
105
|
}
|
package/src/boot/snapshot.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { NotesIdentity } from "../notes/identity.js";
|
|
2
2
|
import { isFilesystemError } from "../notes/fs-error.js";
|
|
3
|
-
import { createNotesStore, type NoteRow, type
|
|
3
|
+
import { createNotesStore, type NoteRow, type Scope } from "../notes/index.js";
|
|
4
4
|
|
|
5
5
|
const NOTES_HOMES = [
|
|
6
6
|
{ scope: "session", label: "this session" },
|
|
@@ -19,18 +19,13 @@ export type NotesSnapshot = {
|
|
|
19
19
|
readonly unavailable: readonly NotesHome[];
|
|
20
20
|
};
|
|
21
21
|
|
|
22
|
-
function queryForScope(scope: Scope): NotesQuery {
|
|
23
|
-
if (scope === "agent" || scope === "model") return { scope };
|
|
24
|
-
return { scope };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
22
|
/**
|
|
28
23
|
* Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
|
|
29
24
|
* malformed note data and unrelated construction errors remain visible to the caller.
|
|
30
25
|
*/
|
|
31
26
|
export async function loadNotesSnapshot(identity: NotesIdentity, openedAt: number, loadHome?: NotesLoader): Promise<NotesSnapshot> {
|
|
32
27
|
const store = createNotesStore(identity);
|
|
33
|
-
const load = loadHome ?? ((scope: Scope) => store.list(
|
|
28
|
+
const load = loadHome ?? ((scope: Scope) => store.list({ scope }));
|
|
34
29
|
const homes = new Map<Scope, readonly NoteRow[]>();
|
|
35
30
|
const unavailable: NotesHome[] = [];
|
|
36
31
|
for (const home of NOTES_HOMES) {
|
package/src/boot/text.ts
CHANGED
|
@@ -51,7 +51,7 @@ Still a tie? *shrugs* You've got a brain. Use it.
|
|
|
51
51
|
|
|
52
52
|
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\`.
|
|
53
53
|
|
|
54
|
-
\`@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
|
|
54
|
+
\`@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.
|
|
55
55
|
${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
|
|
56
56
|
|
|
57
57
|
/** Logical tool names are supplied by the composing host, not discovered here. */
|
|
@@ -0,0 +1,39 @@
|
|
|
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
|
+
|
|
7
|
+
/** A finite number, from a typed value or an environment string; anything else is unknown. */
|
|
8
|
+
export function numberOf(value: unknown): number | undefined {
|
|
9
|
+
if (typeof value === "number") 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
|
+
|
|
17
|
+
export function positiveNumber(value: unknown): number | undefined {
|
|
18
|
+
const parsed = numberOf(value);
|
|
19
|
+
return parsed !== undefined && parsed > 0 ? parsed : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A margin or window is usable only as a positive safe integer. */
|
|
23
|
+
export function positiveInteger(value: unknown): number | undefined {
|
|
24
|
+
const parsed = numberOf(value);
|
|
25
|
+
return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A percentage override is usable only in (0, 100]. */
|
|
29
|
+
export function percent(value: unknown): number | undefined {
|
|
30
|
+
const parsed = numberOf(value);
|
|
31
|
+
return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Presence-style flags (DISABLE_*): any value but an explicit no counts as on. */
|
|
35
|
+
export function presenceFlag(value: unknown): boolean {
|
|
36
|
+
if (typeof value !== "string") return false;
|
|
37
|
+
const text = value.trim().toLowerCase();
|
|
38
|
+
return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
|
|
39
|
+
}
|
package/src/budget/policy.ts
CHANGED
|
@@ -1,12 +1,8 @@
|
|
|
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, type NotesoupSettings } from "../settings.js";
|
|
3
4
|
|
|
4
5
|
export type ResolvedThresholds = { reminder: number; reserve: number; warning: number };
|
|
5
|
-
/** A margin is usable only as a positive integer; anything else is ignored. */
|
|
6
|
-
function validMargin(raw: unknown): number | undefined {
|
|
7
|
-
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0) return undefined;
|
|
8
|
-
return raw;
|
|
9
|
-
}
|
|
10
6
|
|
|
11
7
|
/**
|
|
12
8
|
* Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
|
|
@@ -21,7 +17,7 @@ export function deriveThresholds(reserveTokens: number, margins: NotesoupSetting
|
|
|
21
17
|
let reminderMargin: number;
|
|
22
18
|
if (margins.reminderMarginTokens === undefined) reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
23
19
|
else {
|
|
24
|
-
const parsed =
|
|
20
|
+
const parsed = positiveInteger(margins.reminderMarginTokens);
|
|
25
21
|
if (parsed === undefined) {
|
|
26
22
|
warnings.push(`🥣 ${reminderKey} must be a positive integer · using the default`);
|
|
27
23
|
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
package/src/budget/text.ts
CHANGED
|
@@ -15,6 +15,9 @@ export const WARNING_BODY =
|
|
|
15
15
|
|
|
16
16
|
export const WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, call \`clear_memory\` to reset now instead of being cut off mid-task.`;
|
|
17
17
|
|
|
18
|
+
/** The shared hidden checkpoint text: one manual/budget-triggered request, both hosts. */
|
|
19
|
+
export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
|
|
20
|
+
|
|
18
21
|
/** Claude's variant: the mod resets after the turn, so the model only has to stop. */
|
|
19
22
|
export const CLAUDE_WARNING_PROMPT = `${WARNING_BODY}\nWhen the notes are ready, end your turn; the reset runs after it.`;
|
|
20
23
|
|
package/src/claude/helper.ts
CHANGED
|
@@ -30,6 +30,7 @@ function identity(input: ClaudeIdentityInput): NotesIdentity {
|
|
|
30
30
|
if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
|
|
31
31
|
return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
|
|
32
32
|
}
|
|
33
|
+
|
|
33
34
|
/** The first schema violation, named by parameter so the model can fix that one field. */
|
|
34
35
|
function paramProblem(schema: TSchema, params: unknown): string {
|
|
35
36
|
// A false subschema reports "schema is false"; its parent's additionalProperties error names the field instead.
|
|
@@ -39,7 +40,6 @@ function paramProblem(schema: TSchema, params: unknown): string {
|
|
|
39
40
|
const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
|
|
40
41
|
return `${field ? `${field} ` : ""}${first.message}${extra}`;
|
|
41
42
|
}
|
|
42
|
-
function jsonValue(value: unknown): unknown { return JSON.parse(JSON.stringify(value)); }
|
|
43
43
|
|
|
44
44
|
/** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
|
|
45
45
|
function boundOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
|
|
@@ -75,7 +75,7 @@ const OPERATIONS: Record<ClaudeToolName, BoundOperation> = {
|
|
|
75
75
|
export async function dispatch(request: unknown): Promise<unknown> {
|
|
76
76
|
if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
|
|
77
77
|
const value = request as Record<string, unknown>;
|
|
78
|
-
if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema:
|
|
78
|
+
if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
|
|
79
79
|
// The shared reset prose lives here, not in the sandboxed hooks module, so Pi and Claude
|
|
80
80
|
// cannot drift apart. The hooks module caches one copy per session.
|
|
81
81
|
if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
|
package/src/claude/thresholds.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
|
|
2
|
-
import {
|
|
2
|
+
import { percent, positiveInteger, positiveNumber, presenceFlag } from "../budget/parse.js";
|
|
3
|
+
import { isPlainObject, mergeNotesoupSettings } from "../settings.js";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Claude's auto-compact point, derived the way Claude derives it — never a hardcoded percent.
|
|
@@ -16,6 +17,14 @@ export const CLAUDE_AUTOCOMPACT_BUFFER_TOKENS = 13_000;
|
|
|
16
17
|
export const CLAUDE_OUTPUT_RESERVE_TOKENS = 20_000;
|
|
17
18
|
/** Default slack between Claude's auto-compact point and notesoup's notes-only reset. */
|
|
18
19
|
export const DEFAULT_CLAUDE_RESET_MARGIN_TOKENS = 8_192;
|
|
20
|
+
/**
|
|
21
|
+
* A point is never expressed as zero: the mod reads `measured >= reset` as due, so a zero point
|
|
22
|
+
* would clear memory on every turn, including a fresh window. A window smaller than Claude's own
|
|
23
|
+
* reserves therefore resets at the smallest expressible point instead.
|
|
24
|
+
*/
|
|
25
|
+
const MIN_POINT_TOKENS = 1;
|
|
26
|
+
/** The same floor in percent units, for the no-window fallback. */
|
|
27
|
+
const MIN_POINT_PERCENT = 0.1;
|
|
19
28
|
/**
|
|
20
29
|
* The percent fallback assumes the classic 200K model window: it is reached only when
|
|
21
30
|
* `usage()` reports no window and no breakdown, and it reproduces the token maths below
|
|
@@ -41,42 +50,12 @@ export type ClaudeLimits = {
|
|
|
41
50
|
readonly warningRunway: number;
|
|
42
51
|
};
|
|
43
52
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
function
|
|
49
|
-
|
|
50
|
-
if (typeof value === "string" && value.trim() !== "") {
|
|
51
|
-
const parsed = Number(value);
|
|
52
|
-
return Number.isFinite(parsed) ? parsed : undefined;
|
|
53
|
-
}
|
|
54
|
-
return undefined;
|
|
55
|
-
}
|
|
56
|
-
function positiveNumberOf(value: unknown): number | undefined {
|
|
57
|
-
const parsed = numberOf(value);
|
|
58
|
-
return parsed !== undefined && parsed > 0 ? parsed : undefined;
|
|
59
|
-
}
|
|
60
|
-
/** A margin is usable only as a positive integer, matching Pi's budget policy. */
|
|
61
|
-
function positiveIntegerOf(value: unknown): number | undefined {
|
|
62
|
-
const parsed = numberOf(value);
|
|
63
|
-
return parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
|
|
64
|
-
}
|
|
65
|
-
/** Claude accepts a percent override only in (0, 100]. */
|
|
66
|
-
function percentOf(value: unknown): number | undefined {
|
|
67
|
-
const parsed = numberOf(value);
|
|
68
|
-
return parsed !== undefined && parsed > 0 && parsed <= 100 ? parsed : undefined;
|
|
69
|
-
}
|
|
70
|
-
/** Presence-style flags (DISABLE_AUTO_COMPACT): any value but an explicit no counts as on. */
|
|
71
|
-
function flagOn(value: unknown): boolean {
|
|
72
|
-
if (typeof value !== "string") return false;
|
|
73
|
-
const text = value.trim().toLowerCase();
|
|
74
|
-
return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off";
|
|
75
|
-
}
|
|
76
|
-
function settingFlag(settings: unknown, key: string): boolean | undefined {
|
|
77
|
-
if (!isObject(settings)) return undefined;
|
|
78
|
-
const value = settings[key];
|
|
79
|
-
return typeof value === "boolean" ? value : undefined;
|
|
53
|
+
/**
|
|
54
|
+
* The active auto-compact flag: absent means Claude's default (on), and only an explicit
|
|
55
|
+
* boolean counts. Settings are read from one host-supplied scope, so the flag is top-level.
|
|
56
|
+
*/
|
|
57
|
+
function settingFlag(settings: unknown): boolean | undefined {
|
|
58
|
+
return isPlainObject(settings) && typeof settings.autoCompactEnabled === "boolean" ? settings.autoCompactEnabled : undefined;
|
|
80
59
|
}
|
|
81
60
|
|
|
82
61
|
/**
|
|
@@ -86,18 +65,18 @@ function settingFlag(settings: unknown, key: string): boolean | undefined {
|
|
|
86
65
|
*/
|
|
87
66
|
function configuredWindow(settings: unknown, env: Record<string, unknown>, model: unknown): number | undefined {
|
|
88
67
|
const windows: number[] = [];
|
|
89
|
-
const fromEnv =
|
|
68
|
+
const fromEnv = positiveNumber(env.autoCompactWindow);
|
|
90
69
|
if (fromEnv !== undefined) windows.push(fromEnv);
|
|
91
|
-
if (typeof model === "string" && model.length > 0 &&
|
|
92
|
-
const modelSettings =
|
|
70
|
+
if (typeof model === "string" && model.length > 0 && isPlainObject(settings)) {
|
|
71
|
+
const modelSettings = isPlainObject(settings.modelSettings) ? settings.modelSettings : {};
|
|
93
72
|
const perModel = modelSettings[model];
|
|
94
|
-
if (
|
|
95
|
-
const value =
|
|
73
|
+
if (isPlainObject(perModel)) {
|
|
74
|
+
const value = positiveNumber(perModel.autoCompactWindow);
|
|
96
75
|
if (value !== undefined) windows.push(value);
|
|
97
76
|
}
|
|
98
77
|
}
|
|
99
|
-
if (
|
|
100
|
-
const value =
|
|
78
|
+
if (isPlainObject(settings)) {
|
|
79
|
+
const value = positiveNumber(settings.autoCompactWindow);
|
|
101
80
|
if (value !== undefined) windows.push(value);
|
|
102
81
|
}
|
|
103
82
|
return windows.length === 0 ? undefined : Math.min(...windows);
|
|
@@ -105,10 +84,10 @@ function configuredWindow(settings: unknown, env: Record<string, unknown>, model
|
|
|
105
84
|
|
|
106
85
|
function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: number, resetMargin: number, warningRunway: number): ClaudeLimits {
|
|
107
86
|
const tokens = Math.max(0, Math.floor(native));
|
|
108
|
-
const reset = Math.max(
|
|
87
|
+
const reset = Math.max(MIN_POINT_TOKENS, tokens - resetMargin);
|
|
109
88
|
return {
|
|
110
89
|
source, autoCompact, unit: "tokens",
|
|
111
|
-
native: tokens, reset, warn: Math.max(
|
|
90
|
+
native: tokens, reset, warn: Math.max(MIN_POINT_TOKENS, reset - warningRunway), resetMargin, warningRunway,
|
|
112
91
|
};
|
|
113
92
|
}
|
|
114
93
|
|
|
@@ -116,10 +95,10 @@ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: nu
|
|
|
116
95
|
function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargin: number, warningRunway: number): ClaudeLimits {
|
|
117
96
|
const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
|
|
118
97
|
const native = pct === undefined ? base : Math.min(pct, base);
|
|
119
|
-
const reset = Math.max(
|
|
98
|
+
const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
|
|
120
99
|
return {
|
|
121
100
|
source: "percent", autoCompact, unit: "percent",
|
|
122
|
-
native, reset, warn: Math.max(
|
|
101
|
+
native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
|
|
123
102
|
};
|
|
124
103
|
}
|
|
125
104
|
|
|
@@ -130,39 +109,43 @@ function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargi
|
|
|
130
109
|
* helper boundary, where nothing is typed.
|
|
131
110
|
*/
|
|
132
111
|
export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
|
|
133
|
-
const root =
|
|
134
|
-
const usage =
|
|
135
|
-
const breakdown =
|
|
136
|
-
const env =
|
|
112
|
+
const root = isPlainObject(facts) ? facts : {};
|
|
113
|
+
const usage = isPlainObject(root.usage) ? root.usage : {};
|
|
114
|
+
const breakdown = isPlainObject(root.breakdown) ? root.breakdown : {};
|
|
115
|
+
const env = isPlainObject(root.env) ? root.env : {};
|
|
137
116
|
const settings = root.settings;
|
|
138
117
|
|
|
118
|
+
// The host hands over its merged settings, so there is no separate project scope to name.
|
|
139
119
|
const margins = mergeNotesoupSettings(settings, undefined);
|
|
140
|
-
const resetMargin =
|
|
141
|
-
const warningRunway =
|
|
120
|
+
const resetMargin = positiveInteger(margins.resetMarginTokens) ?? DEFAULT_CLAUDE_RESET_MARGIN_TOKENS;
|
|
121
|
+
const warningRunway = positiveInteger(margins.warningRunwayTokens) ?? WARNING_RUNWAY_TOKENS;
|
|
142
122
|
|
|
143
|
-
const autoCompact = settingFlag(settings
|
|
144
|
-
&& !
|
|
123
|
+
const autoCompact = settingFlag(settings) !== false
|
|
124
|
+
&& !presenceFlag(env.disableAutoCompact)
|
|
145
125
|
&& breakdown.isAutoCompactEnabled !== false;
|
|
146
|
-
const pct =
|
|
126
|
+
const pct = percent(env.pctOverride);
|
|
147
127
|
|
|
148
128
|
// (a) Claude's own point. It already includes the window, model settings and CLI flag; only
|
|
149
129
|
// the percent override is applied separately, on the window-after-output-reserve it is
|
|
150
|
-
// minted from (threshold + summary buffer).
|
|
151
|
-
|
|
130
|
+
// minted from (threshold + summary buffer). A malformed override that floors the point to
|
|
131
|
+
// zero is not a point at all, so it degrades to the next source instead of resetting always.
|
|
132
|
+
const threshold = positiveNumber(breakdown.autoCompactThreshold);
|
|
152
133
|
if (autoCompact && threshold !== undefined) {
|
|
153
134
|
const native = pct === undefined ? threshold : Math.min(Math.floor((threshold + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) * (pct / 100)), threshold);
|
|
154
135
|
if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
|
|
155
136
|
}
|
|
156
137
|
|
|
157
|
-
// (b) The same point computed from the reported window plus settings and environment.
|
|
158
|
-
|
|
138
|
+
// (b) The same point computed from the reported window plus settings and environment. A real
|
|
139
|
+
// window always answers here: falling through to the percent fallback would express the
|
|
140
|
+
// points on an assumed 200K window, which is later than the window notesoup can see.
|
|
141
|
+
const window = positiveNumber(usage.window);
|
|
159
142
|
if (window !== undefined) {
|
|
160
143
|
const configured = configuredWindow(settings, env, breakdown.model);
|
|
161
144
|
const effective = Math.min(configured ?? window, window);
|
|
162
145
|
const native = autoCompact
|
|
163
146
|
? effective - CLAUDE_OUTPUT_RESERVE_TOKENS - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS
|
|
164
147
|
: effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
|
|
165
|
-
|
|
148
|
+
return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
|
|
166
149
|
}
|
|
167
150
|
|
|
168
151
|
// (c) Nothing usable but percentages.
|
package/src/dream/lock.ts
CHANGED
|
@@ -25,14 +25,6 @@ function readText(path: string): string | undefined {
|
|
|
25
25
|
try { return readFileSync(path, "utf8"); } catch { return undefined; }
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
function stampMtime(stampPath: string): number | undefined {
|
|
29
|
-
try { return statSync(stampPath).mtimeMs; } catch { return undefined; }
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Cleanup ownership: only the exact marker this run wrote may be removed. The token is
|
|
34
|
-
* diagnostic and guards cleanup; it never grants permission to take an existing lock.
|
|
35
|
-
*/
|
|
36
28
|
function ownsLock(lock: LockState): boolean {
|
|
37
29
|
if (!lock.held || !lock.token) return false;
|
|
38
30
|
return readText(lock.path)?.trim() === `${process.pid} ${lock.token}`;
|
|
@@ -46,7 +38,9 @@ function ownsLock(lock: LockState): boolean {
|
|
|
46
38
|
*/
|
|
47
39
|
export function acquireLock(path: string): LockState {
|
|
48
40
|
const now = Date.now();
|
|
49
|
-
|
|
41
|
+
// The sidecar's mtime is the scheduler's timestamp; a missing one means no prior dream.
|
|
42
|
+
let priorStampMtime: number | undefined;
|
|
43
|
+
try { priorStampMtime = statSync(lastRunPath(path)).mtimeMs; } catch { /* no sidecar yet */ }
|
|
50
44
|
const token = randomUUID();
|
|
51
45
|
try {
|
|
52
46
|
writeFileSync(path, `${process.pid} ${token}`, { flag: "wx" });
|
package/src/dream/report.ts
CHANGED
|
@@ -8,14 +8,9 @@ function writeList(writes: DreamWrite[]): string {
|
|
|
8
8
|
return writes.length ? writes.map((w) => `- ${w.tool}: ${w.path}`).join("\n") : "- no changes";
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
-
/** Best-effort
|
|
12
|
-
function
|
|
13
|
-
try {
|
|
14
|
-
catch (error) { return errorMessage(error); }
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function appendText(path: string, content: string): string | undefined {
|
|
18
|
-
try { appendFileSync(path, content); return undefined; }
|
|
11
|
+
/** Best-effort filesystem step; returns the failure message instead of throwing. */
|
|
12
|
+
function attempt(action: () => void): string | undefined {
|
|
13
|
+
try { action(); return undefined; }
|
|
19
14
|
catch (error) { return errorMessage(error); }
|
|
20
15
|
}
|
|
21
16
|
|
|
@@ -26,11 +21,11 @@ function appendText(path: string, content: string): string | undefined {
|
|
|
26
21
|
*/
|
|
27
22
|
export function finishDream(home: string, stamp: string, reportPath: string, failed: boolean, body: string, writes: DreamWrite[]): number {
|
|
28
23
|
const header = failed ? `# Dream ${stamp} (failed)` : `# Dream ${stamp}`;
|
|
29
|
-
let reportError =
|
|
24
|
+
let reportError = attempt(() => { mkdirSync(dirname(reportPath), { recursive: true }); writeFileSync(reportPath, `${header}\n\n${body}\n\n${writeList(writes)}\n`); });
|
|
30
25
|
const audit = gitCommit(home, `dream ${stamp}${failed ? " (failed)" : ""}`);
|
|
31
26
|
if (!audit.ok) {
|
|
32
27
|
console.error(`dream: final audit failed: ${audit.error}`);
|
|
33
|
-
reportError ??=
|
|
28
|
+
reportError ??= attempt(() => appendFileSync(reportPath, `\n## Final audit failed\n\n${audit.error}\n`));
|
|
34
29
|
}
|
|
35
30
|
if (reportError) console.error(`dream: could not write report at ${reportPath}: ${reportError}`);
|
|
36
31
|
return failed || !audit.ok || reportError !== undefined ? 1 : 0;
|
package/src/history/history.ts
CHANGED
|
@@ -239,14 +239,16 @@ export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?:
|
|
|
239
239
|
const document = eventDocument(event);
|
|
240
240
|
const chars = Array.from(document);
|
|
241
241
|
const start = matchOffset ?? 0;
|
|
242
|
-
|
|
242
|
+
// A negative budget would cut the tail and still call the result a prefix.
|
|
243
|
+
const limit = Math.max(0, maxChars);
|
|
244
|
+
const truncated = start > 0 || start + limit < chars.length;
|
|
243
245
|
return {
|
|
244
246
|
seq: event.seq,
|
|
245
247
|
window_id: event.windowId,
|
|
246
248
|
role: event.role,
|
|
247
249
|
created_at: event.createdAt ?? null,
|
|
248
250
|
...toolSummary(event),
|
|
249
|
-
content: truncated ? chars.slice(start, start +
|
|
251
|
+
content: truncated ? chars.slice(start, start + limit).join("") : document,
|
|
250
252
|
truncated,
|
|
251
253
|
...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
|
|
252
254
|
};
|
package/src/history/query.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
3
|
import { failure, success, type Outcome } from "../tools/result.js";
|
|
4
|
-
import {
|
|
4
|
+
import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
|
|
5
|
+
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
5
6
|
import { InvalidQueryError, searchQueries } from "../tools/schema.js";
|
|
6
7
|
import { allItems, eventDocument, filteredItems, inSelection, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
|
|
7
8
|
|
|
@@ -28,19 +29,12 @@ export type HistorySelection = HistoryFilter & {
|
|
|
28
29
|
/** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
|
|
29
30
|
const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
30
31
|
|
|
31
|
-
/** Epoch ms for one ISO 8601 value, with a missing offset read as UTC. */
|
|
32
|
-
function isoUtcMs(value: string): number | undefined {
|
|
33
|
-
const match = ISO_8601.exec(value);
|
|
34
|
-
if (match === null) return undefined;
|
|
35
|
-
const at = Date.parse(match[1] === undefined ? `${value}Z` : value);
|
|
36
|
-
return Number.isNaN(at) ? undefined : at;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
32
|
/** Epoch ms for one optional time param, or a refusal naming it. */
|
|
40
33
|
function timeBound(name: "since" | "until", value: string | undefined): Outcome<number | undefined> {
|
|
41
34
|
if (value === undefined) return success(undefined);
|
|
42
|
-
const
|
|
43
|
-
|
|
35
|
+
const match = ISO_8601.exec(value);
|
|
36
|
+
const at = match === null ? undefined : Date.parse(match[1] === undefined ? `${value}Z` : value);
|
|
37
|
+
return at === undefined || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
|
|
44
38
|
}
|
|
45
39
|
|
|
46
40
|
/** Parse `since`/`until`; a malformed or inverted pair refuses here. */
|
|
@@ -180,16 +174,6 @@ function selectionCandidates(projection: HistoryProjection, params: HistorySelec
|
|
|
180
174
|
.filter((candidate) => candidate.matchOffset >= 0));
|
|
181
175
|
}
|
|
182
176
|
|
|
183
|
-
/**
|
|
184
|
-
* Take the limit from the end `from` names, starting there so a budget for one row keeps the most
|
|
185
|
-
* important row. The selection is already filtered to its range; `from` never states a direction.
|
|
186
|
-
*/
|
|
187
|
-
function orderedCandidates(vis: Candidate[], params: HistorySelection, limit: number): Candidate[] {
|
|
188
|
-
const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
|
|
189
|
-
const selected = params.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit);
|
|
190
|
-
return params.from === "oldest" ? selected : selected.reverse();
|
|
191
|
-
}
|
|
192
|
-
|
|
193
177
|
/**
|
|
194
178
|
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
195
179
|
* Grow the page in selection order; shorten the first preview only when no full row fits.
|
|
@@ -201,9 +185,12 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
|
|
|
201
185
|
const candidates = selectionCandidates(projection, scoped);
|
|
202
186
|
if (!candidates.ok) return candidates;
|
|
203
187
|
const vis = candidates.data;
|
|
204
|
-
|
|
188
|
+
// Take the limit from the end `from` names, so a budget for one row keeps the most important one.
|
|
189
|
+
// At least one: `slice(-0)` would otherwise return the whole selection.
|
|
190
|
+
const limit = Math.max(1, scoped.limit ?? 20);
|
|
205
191
|
const folds = foldsRuns(scoped);
|
|
206
|
-
const
|
|
192
|
+
const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
|
|
193
|
+
const ordered = scoped.from === "oldest" ? ascending.slice(0, limit) : ascending.slice(-limit).reverse();
|
|
207
194
|
const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
|
|
208
195
|
const kept: Candidate[] = [];
|
|
209
196
|
for (const candidate of ordered) {
|
package/src/notes/address.ts
CHANGED
|
@@ -1,25 +1,11 @@
|
|
|
1
|
-
import { NoteError } from "./errors.js";
|
|
1
|
+
import { NoteError, shown } from "./errors.js";
|
|
2
2
|
import type { NotesIdentity } from "./identity.js";
|
|
3
|
-
import { SLUG_PATTERN, type Scope } from "./paths.js";
|
|
3
|
+
import { assertVirtualPath, SLUG_PATTERN, type Scope } from "./paths.js";
|
|
4
4
|
|
|
5
5
|
export type NoteAddress = { scope: Scope; path: string; who?: string };
|
|
6
6
|
|
|
7
7
|
export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
|
|
8
8
|
|
|
9
|
-
/** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
|
|
10
|
-
function shown(value: unknown): string {
|
|
11
|
-
const json = JSON.stringify(value);
|
|
12
|
-
return json === undefined ? String(value) : json;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function assertVirtualPath(value: unknown): string {
|
|
16
|
-
if (typeof value !== "string" || value.length === 0) throw new NoteError("invalid_address", "The address is empty; give the note a path.");
|
|
17
|
-
if (value.includes("\0") || value.includes("\\") || value.startsWith("/")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't start with "/" or contain "\\" or NUL.`);
|
|
18
|
-
const parts = value.split("/");
|
|
19
|
-
if (parts.some((part) => part.length === 0 || part === "." || part === "..")) throw new NoteError("invalid_address", `${shown(value)}: a note path can't have empty, ".", or ".." folder names.`);
|
|
20
|
-
return value;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
9
|
/**
|
|
24
10
|
* Minimal glob over virtual note paths: `*` matches any run within a segment (never
|
|
25
11
|
* `/`), `**` matches any run across segments (a leading double-star followed by a
|
|
@@ -39,6 +25,8 @@ export function globToRegExp(pattern: string): RegExp {
|
|
|
39
25
|
} else {
|
|
40
26
|
source += "[^/]*";
|
|
41
27
|
}
|
|
28
|
+
} else if (char === "?") {
|
|
29
|
+
source += "[^/]";
|
|
42
30
|
} else {
|
|
43
31
|
source += char.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
|
|
44
32
|
}
|
package/src/notes/errors.ts
CHANGED
|
@@ -13,3 +13,9 @@ export class NoteError extends Error {
|
|
|
13
13
|
this.editIndex = extra.editIndex;
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
+
|
|
17
|
+
/** A refusal names the offending input; JSON quoting keeps control chars visible, and stringify misses get String(). */
|
|
18
|
+
export function shown(value: unknown): string {
|
|
19
|
+
const json = JSON.stringify(value);
|
|
20
|
+
return json === undefined ? String(value) : json;
|
|
21
|
+
}
|
package/src/notes/frontmatter.ts
CHANGED
|
@@ -132,15 +132,25 @@ export function parseNote(raw: string, now = Date.now()): { meta: NoteMeta; body
|
|
|
132
132
|
return { meta: meta as NoteMeta, body };
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
-
/**
|
|
135
|
+
/**
|
|
136
|
+
* Emit a YAML scalar: bare for safe strings and JSON literals, JSON-quoted otherwise.
|
|
137
|
+
* A quoted string must not come back as another type: a value that `JSON.parse` reads as a
|
|
138
|
+
* non-string (`"1"`, `"1e5"`) is always emitted quoted, so an unknown key survives a rewrite
|
|
139
|
+
* with its type intact.
|
|
140
|
+
*/
|
|
136
141
|
function yamlScalar(value: unknown): string {
|
|
137
142
|
if (typeof value === "string") {
|
|
138
143
|
const reserved = new Set(["true", "false", "null", "yes", "no", "on", "off", "~"]);
|
|
139
|
-
if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase())) return value;
|
|
144
|
+
if (/^[A-Za-z0-9_.+\-:/]+$/.test(value) && !reserved.has(value.toLowerCase()) && !parsesAsNonString(value)) return value;
|
|
140
145
|
}
|
|
141
146
|
return JSON.stringify(value);
|
|
142
147
|
}
|
|
143
148
|
|
|
149
|
+
/** True when a bare scalar would be read back as a number, boolean or null instead of text. */
|
|
150
|
+
function parsesAsNonString(text: string): boolean {
|
|
151
|
+
try { return typeof JSON.parse(text) !== "string"; } catch { return false; }
|
|
152
|
+
}
|
|
153
|
+
|
|
144
154
|
/** Serialize frontmatter + blank line + body. Known keys emit in Design order, extras after. */
|
|
145
155
|
export function serializeNote(meta: NoteMeta, body: string): string {
|
|
146
156
|
const lines: string[] = [];
|
package/src/notes/identity.ts
CHANGED
|
@@ -24,8 +24,6 @@ function assertDirectoryComponent(field: string, value: string): void {
|
|
|
24
24
|
/** Validate and snapshot caller identity; no global or environment defaults are consulted. */
|
|
25
25
|
export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
|
|
26
26
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("notes context must be a plain object");
|
|
27
|
-
const prototype = Object.getPrototypeOf(value);
|
|
28
|
-
if (prototype !== Object.prototype && prototype !== null) throw new TypeError("notes context must be a plain object");
|
|
29
27
|
const homeValue = requireString("home", value.home);
|
|
30
28
|
const sessionId = requireString("sessionId", value.sessionId);
|
|
31
29
|
const projectKey = requireString("projectKey", value.projectKey);
|