notesoup 0.61.0 → 0.62.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/.agents/plugins/marketplace.json +15 -0
- package/README.md +14 -11
- package/dist/plugins/antigravity/src/cli.d.ts +1 -0
- package/dist/plugins/antigravity/src/cli.js +23 -0
- package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
- package/dist/plugins/antigravity/src/hooks.js +53 -0
- package/dist/plugins/antigravity/src/identity.d.ts +26 -0
- package/dist/plugins/antigravity/src/identity.js +129 -0
- package/dist/plugins/claude/src/helper.js +2 -1
- package/dist/plugins/codex/src/hooks.js +1 -0
- package/dist/plugins/codex/src/identity.d.ts +6 -1
- package/dist/plugins/codex/src/identity.js +13 -1
- package/dist/plugins/codex/src/mcp.d.ts +35 -7
- package/dist/plugins/codex/src/mcp.js +26 -88
- package/dist/plugins/codex/src/text.js +3 -3
- package/dist/plugins/dsh/tools.js +8 -4
- package/dist/plugins/mcp/operations.d.ts +15 -0
- package/dist/plugins/mcp/operations.js +43 -0
- package/dist/plugins/mcp/server.d.ts +14 -0
- package/dist/plugins/mcp/server.js +13 -0
- package/dist/plugins/pi/budget.d.ts +1 -1
- package/dist/plugins/pi/budget.js +3 -2
- package/dist/plugins/pi/entries.d.ts +1 -0
- package/dist/plugins/pi/entries.js +1 -0
- package/dist/plugins/pi/history-tools.js +2 -1
- package/dist/plugins/pi/history.js +18 -1
- package/dist/plugins/pi/notes/tools.js +7 -3
- package/dist/plugins/pi/render.d.ts +7 -1
- package/dist/plugins/pi/render.js +2 -2
- package/dist/plugins/pi/reset/lifecycle.d.ts +1 -1
- package/dist/plugins/pi/reset/lifecycle.js +8 -9
- package/dist/plugins/pi/runtime.js +102 -61
- package/dist/plugins/pi/tool-result.js +7 -7
- package/dist/plugins/pi/window.d.ts +33 -3
- package/dist/plugins/pi/window.js +209 -9
- package/dist/src/boot/render.js +18 -15
- package/dist/src/boot/text.d.ts +3 -1
- package/dist/src/boot/text.js +22 -20
- package/dist/src/budget/text.d.ts +2 -2
- package/dist/src/budget/text.js +13 -13
- package/dist/src/history/claude.d.ts +2 -0
- package/dist/src/history/claude.js +46 -0
- package/dist/src/history/codex-transcript.js +7 -5
- package/dist/src/history/codex.js +3 -0
- package/dist/src/history/corpus.d.ts +28 -1
- package/dist/src/history/corpus.js +40 -0
- package/dist/src/history/history.d.ts +37 -46
- package/dist/src/history/history.js +21 -40
- package/dist/src/history/local.js +67 -32
- package/dist/src/history/pi.d.ts +2 -1
- package/dist/src/history/pi.js +122 -48
- package/dist/src/history/prefilter.js +76 -19
- package/dist/src/history/query.d.ts +28 -49
- package/dist/src/history/query.js +83 -68
- package/dist/src/history/summary-cache.d.ts +8 -1
- package/dist/src/history/summary-cache.js +138 -12
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/frontmatter.d.ts +0 -2
- package/dist/src/notes/frontmatter.js +0 -2
- package/dist/src/notes/index.d.ts +1 -1
- package/dist/src/notes/index.js +1 -1
- package/dist/src/notes/policy.d.ts +15 -1
- package/dist/src/notes/policy.js +46 -5
- package/dist/src/notes/store.d.ts +12 -0
- package/dist/src/notes/store.js +16 -20
- package/dist/src/text-match.d.ts +10 -1
- package/dist/src/text-match.js +42 -3
- package/dist/src/tools/dream.d.ts +22 -93
- package/dist/src/tools/dream.js +30 -27
- package/dist/src/tools/history.d.ts +33 -26
- package/dist/src/tools/history.js +257 -163
- package/dist/src/tools/notes.d.ts +51 -163
- package/dist/src/tools/notes.js +146 -100
- package/dist/src/tools/output.d.ts +2 -1
- package/dist/src/tools/output.js +2 -1
- package/dist/src/tools/result.d.ts +4 -7
- package/dist/src/tools/result.js +8 -9
- package/dist/src/tools/schema.d.ts +4 -1
- package/dist/src/tools/schema.js +25 -1
- package/dist/test/agent-loop.test.js +198 -16
- package/dist/test/antigravity-live.test.d.ts +1 -0
- package/dist/test/antigravity-live.test.js +142 -0
- package/dist/test/antigravity-plugin.test.d.ts +1 -0
- package/dist/test/antigravity-plugin.test.js +101 -0
- package/dist/test/boot.integration.test.js +133 -14
- package/dist/test/claude-history.test.js +14 -13
- package/dist/test/claude-mod.test.js +9 -6
- package/dist/test/codex-history.test.js +15 -3
- package/dist/test/codex-plugin.test.js +76 -38
- package/dist/test/dependencies.test.js +7 -3
- package/dist/test/dream-skill.test.js +3 -3
- package/dist/test/dream-tools.test.js +101 -56
- package/dist/test/dsh.test.js +34 -19
- package/dist/test/helpers/dependency-graph.js +2 -2
- package/dist/test/helpers/extension.d.ts +65 -2
- package/dist/test/helpers/extension.js +72 -3
- package/dist/test/history-corpus.test.js +79 -77
- package/dist/test/history-summary-cache.test.js +97 -9
- package/dist/test/history.integration.test.js +234 -168
- package/dist/test/host-neutral.test.js +69 -19
- package/dist/test/marker.test.js +1 -1
- package/dist/test/note-policy.test.js +96 -77
- package/dist/test/notes.integration.test.js +212 -94
- package/dist/test/notes.test.js +184 -113
- package/dist/test/pi-render.test.js +20 -12
- package/dist/test/project-namespace.test.js +3 -2
- package/dist/test/reset-lifecycle.test.js +2 -2
- package/docs/antigravity.md +44 -0
- package/docs/architecture.md +6 -4
- package/docs/claude-code-mod.md +2 -2
- package/docs/codex.md +36 -38
- package/docs/dsh.md +3 -3
- package/docs/history-sessions.md +28 -50
- package/docs/notes-library.md +4 -4
- package/docs/skills.md +3 -3
- package/docs/tool-results.md +47 -28
- package/package.json +3 -2
- package/playbook.md +1 -1
- package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
- package/plugins/antigravity/hooks.json +7 -0
- package/plugins/antigravity/mcp_config.json +8 -0
- package/plugins/antigravity/plugin.json +6 -0
- package/plugins/antigravity/src/cli.ts +22 -0
- package/plugins/antigravity/src/hooks.ts +51 -0
- package/plugins/antigravity/src/identity.ts +127 -0
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +1059 -534
- package/plugins/claude/hooks/register.ts +2 -2
- package/plugins/claude/playbook.md +1 -1
- package/plugins/claude/skills/dream/SKILL.md +1 -1
- package/plugins/claude/skills/notesoup/SKILL.md +92 -0
- package/plugins/claude/src/helper.ts +2 -1
- package/plugins/codex/.codex-plugin/plugin.json +8 -0
- package/plugins/codex/.mcp.json +11 -0
- package/plugins/codex/README.md +5 -21
- package/plugins/codex/dist/codex/notesoup.js +18480 -17946
- package/plugins/codex/src/hooks.ts +1 -0
- package/plugins/codex/src/identity.ts +14 -1
- package/plugins/codex/src/mcp.ts +28 -98
- package/plugins/codex/src/text.ts +3 -3
- package/plugins/dsh/tools.ts +8 -4
- package/plugins/mcp/operations.ts +50 -0
- package/plugins/mcp/server.ts +23 -0
- package/plugins/paseo/README.md +5 -10
- package/plugins/paseo/client/brain-empty-card.tsx +3 -3
- package/plugins/paseo/client/markdown.tsx +50 -38
- package/plugins/paseo/client/notes-op-card.tsx +12 -9
- package/plugins/paseo/client/paper-card.tsx +6 -5
- package/plugins/paseo/client/paper-palette.ts +2 -9
- package/plugins/paseo/client/sticky-card.tsx +2 -2
- package/plugins/paseo/client/tool-result.ts +7 -14
- package/plugins/paseo/package-lock.json +3406 -0
- package/plugins/paseo/package.json +1 -0
- package/plugins/paseo/test/markdown-core.test.ts +73 -66
- package/plugins/pi/budget.ts +3 -3
- package/plugins/pi/entries.ts +1 -0
- package/plugins/pi/history-tools.ts +2 -1
- package/plugins/pi/history.ts +30 -1
- package/plugins/pi/notes/tools.ts +7 -3
- package/plugins/pi/render.ts +6 -6
- package/plugins/pi/reset/lifecycle.ts +9 -10
- package/plugins/pi/runtime.ts +96 -60
- package/plugins/pi/tool-result.ts +8 -8
- package/plugins/pi/window.ts +198 -9
- package/skills/dream/SKILL.md +1 -1
- package/skills/notesoup/SKILL.md +92 -0
- package/src/boot/render.ts +18 -15
- package/src/boot/text.ts +23 -19
- package/src/budget/text.ts +13 -13
- package/src/history/claude.ts +41 -0
- package/src/history/codex-transcript.ts +6 -4
- package/src/history/codex.ts +2 -0
- package/src/history/corpus.ts +51 -2
- package/src/history/history.ts +35 -44
- package/src/history/local.ts +67 -27
- package/src/history/pi.ts +113 -35
- package/src/history/prefilter.ts +73 -15
- package/src/history/query.ts +93 -73
- package/src/history/summary-cache.ts +142 -17
- package/src/index.ts +1 -1
- package/src/notes/errors.ts +1 -1
- package/src/notes/frontmatter.ts +0 -3
- package/src/notes/index.ts +1 -1
- package/src/notes/policy.ts +44 -5
- package/src/notes/store.ts +17 -20
- package/src/text-match.ts +46 -4
- package/src/tools/dream.ts +29 -31
- package/src/tools/history.ts +249 -142
- package/src/tools/notes.ts +145 -113
- package/src/tools/output.ts +2 -1
- package/src/tools/result.ts +12 -11
- package/src/tools/schema.ts +24 -1
- package/plugins/claude/skills/memory/SKILL.md +0 -69
- package/plugins/codex/mcp.json +0 -10
- package/plugins/codex/plugin.json +0 -6
- package/plugins/paseo/client/markdown-core.tsx +0 -189
- package/plugins/paseo/client/typography.ts +0 -24
- package/skills/memory/SKILL.md +0 -69
package/src/history/query.ts
CHANGED
|
@@ -1,32 +1,17 @@
|
|
|
1
1
|
/** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
|
|
2
|
-
import { Type, type Static } from "typebox";
|
|
3
2
|
import { success, type Outcome } from "../result.js";
|
|
4
|
-
import { earliestMatchOffsetChars, prefixFit } from "../text-match.js";
|
|
5
|
-
import { eventDocument, filteredItems, matchesFilter, visibleItem,
|
|
3
|
+
import { compileSearchQueries, earliestMatchOffsetChars, prefixFit } from "../text-match.js";
|
|
4
|
+
import { eventDocument, eventTimestampMs, filteredItems, matchesFilter, visibleItem, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, type HistoryRole } from "./history.js";
|
|
6
5
|
|
|
7
6
|
type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow; neighbors?: { events: HistoryEvent[]; index: number } };
|
|
8
|
-
type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow;
|
|
9
|
-
|
|
10
|
-
export
|
|
11
|
-
export function markMultiPage(page: HistoryPage): HistoryPage {
|
|
12
|
-
multiPages.add(page);
|
|
13
|
-
return page;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export type HistorySelection = HistoryFilter & { session?: string; limit?: number; query?: string[]; context?: number };
|
|
17
|
-
|
|
18
|
-
export const HistoryPageSchema = Type.Object({
|
|
19
|
-
notice: Type.Optional(Type.String()),
|
|
20
|
-
items: Type.Array(HistoryPageItemSchema),
|
|
21
|
-
folded_after: Type.Optional(HistoryFoldedRowSchema),
|
|
22
|
-
has_older: Type.Boolean(),
|
|
23
|
-
has_newer: Type.Boolean(),
|
|
24
|
-
}, { additionalProperties: false });
|
|
7
|
+
type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; discarded?: boolean; forward?: boolean };
|
|
8
|
+
type TimelineSelection = HistoryFilter & { limit?: number };
|
|
9
|
+
export type HistorySelection = TimelineSelection & { query?: string[]; context?: number };
|
|
25
10
|
|
|
26
11
|
/** One whole page payload, before it becomes an outcome. */
|
|
27
|
-
export type HistoryPage =
|
|
12
|
+
export type HistoryPage = { notice?: string; items: HistoryPageItem[]; folded_after?: HistoryFoldedRow; has_older: boolean; has_newer: boolean };
|
|
28
13
|
/** A caller's budget rejected even the shortest page; tool limits and refusal copy belong to the caller. */
|
|
29
|
-
export type HistoryPageResult = Outcome<HistoryPage> | { ok: false; pageTooLarge:
|
|
14
|
+
export type HistoryPageResult = Outcome<HistoryPage> | { ok: false; pageTooLarge: true };
|
|
30
15
|
|
|
31
16
|
/** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
|
|
32
17
|
function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPageItem) => boolean): HistoryPageItem {
|
|
@@ -44,7 +29,7 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
|
|
|
44
29
|
}
|
|
45
30
|
|
|
46
31
|
/** Summarize one already ordered gap; omitted tool names never change its exact count. */
|
|
47
|
-
function foldedRun(events: HistoryEvent[]
|
|
32
|
+
function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
|
|
48
33
|
if (events.length === 0) return undefined;
|
|
49
34
|
const counts = new Map<string, number>();
|
|
50
35
|
for (const event of events) {
|
|
@@ -55,35 +40,34 @@ function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow |
|
|
|
55
40
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
56
41
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
57
42
|
const tools = Object.fromEntries(entries);
|
|
58
|
-
return {
|
|
43
|
+
return { first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
|
|
59
44
|
}
|
|
60
45
|
|
|
61
46
|
// Tool/thinking-only envelopes are not dialogue, even with explicit roles.
|
|
62
47
|
const visible = (event: HistoryEvent) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "";
|
|
63
48
|
|
|
64
|
-
function* queryHits(projection: HistoryProjection, params: HistorySelection, session?: string): Generator<Candidate> {
|
|
65
|
-
const {
|
|
49
|
+
function* queryHits(projection: HistoryProjection, params: HistorySelection, patterns: readonly RegExp[], session?: string): Generator<Candidate> {
|
|
50
|
+
const { context } = params;
|
|
66
51
|
const events = filteredItems(projection, context ? {} : params).filter(visible);
|
|
67
52
|
for (const [index, event] of events.entries()) {
|
|
68
53
|
if (context && !matchesFilter(event, params)) continue;
|
|
69
|
-
const matchOffset = earliestMatchOffsetChars(eventDocument(event),
|
|
54
|
+
const matchOffset = earliestMatchOffsetChars(eventDocument(event), patterns);
|
|
70
55
|
if (matchOffset >= 0) yield { event, session, matchOffset, neighbors: context ? { events, index } : undefined };
|
|
71
56
|
}
|
|
72
57
|
}
|
|
73
58
|
|
|
74
|
-
function prepareSelection(projection: HistoryProjection, params:
|
|
75
|
-
const {
|
|
76
|
-
if (query) return { candidates: [...queryHits(projection, params, session)] };
|
|
59
|
+
function prepareSelection(projection: HistoryProjection, params: TimelineSelection): PreparedSelection {
|
|
60
|
+
const { roles } = params;
|
|
77
61
|
const candidates: Candidate[] = [];
|
|
78
62
|
let run: HistoryEvent[] = [];
|
|
79
63
|
for (const event of filteredItems(projection, params).filter(visible)) {
|
|
80
64
|
if (!roles && (event.role === "tool" || event.role === "context")) run.push(event);
|
|
81
65
|
else {
|
|
82
|
-
candidates.push({ event,
|
|
66
|
+
candidates.push({ event, before: foldedRun(run) });
|
|
83
67
|
run = [];
|
|
84
68
|
}
|
|
85
69
|
}
|
|
86
|
-
return { candidates, tail: foldedRun(run
|
|
70
|
+
return { candidates, tail: foldedRun(run) };
|
|
87
71
|
}
|
|
88
72
|
|
|
89
73
|
/** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
|
|
@@ -95,19 +79,55 @@ function pageData(prepared: PreparedSelection, start: number, end: number, maxCh
|
|
|
95
79
|
const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) });
|
|
96
80
|
items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
|
|
97
81
|
}
|
|
98
|
-
|
|
82
|
+
return {
|
|
99
83
|
items,
|
|
100
84
|
...(end === candidates.length && tail ? { folded_after: tail } : {}),
|
|
101
85
|
has_older: (start > 0 && start < end) || (!!prepared.discarded && !prepared.forward),
|
|
102
86
|
has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && !!prepared.forward),
|
|
103
87
|
};
|
|
104
|
-
return prepared.multi ? markMultiPage(page) : page;
|
|
105
88
|
}
|
|
106
89
|
|
|
107
|
-
export function selectPage(projection: HistoryProjection, params:
|
|
90
|
+
export function selectPage(projection: HistoryProjection, params: TimelineSelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
|
|
108
91
|
return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
|
|
109
92
|
}
|
|
110
93
|
|
|
94
|
+
/** Strict single-pass overview summary: default representative, latest per role, and exact time span. */
|
|
95
|
+
export type ProjectionSummary = {
|
|
96
|
+
event: HistoryEvent | undefined;
|
|
97
|
+
latestByRole: Partial<Record<HistoryRole, HistoryEvent>>;
|
|
98
|
+
minCreatedAt: number | null;
|
|
99
|
+
maxCreatedAt: number | null;
|
|
100
|
+
hasUntimed: boolean;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export function summarizeProjection(projection: HistoryProjection): ProjectionSummary {
|
|
104
|
+
const events = filteredItems(projection, {}).filter(visible);
|
|
105
|
+
let firstUser: HistoryEvent | undefined;
|
|
106
|
+
let lastAssistant: HistoryEvent | undefined;
|
|
107
|
+
const latestByRole: Partial<Record<HistoryRole, HistoryEvent>> = {};
|
|
108
|
+
let minCreatedAt = Infinity;
|
|
109
|
+
let maxCreatedAt = -Infinity;
|
|
110
|
+
let hasUntimed = false;
|
|
111
|
+
for (const event of events) {
|
|
112
|
+
if (firstUser === undefined && event.role === "user") firstUser = event;
|
|
113
|
+
if (event.role === "assistant") lastAssistant = event;
|
|
114
|
+
latestByRole[event.role] = event;
|
|
115
|
+
const at = eventTimestampMs(event);
|
|
116
|
+
if (Number.isNaN(at)) hasUntimed = true;
|
|
117
|
+
else {
|
|
118
|
+
if (at < minCreatedAt) minCreatedAt = at;
|
|
119
|
+
if (at > maxCreatedAt) maxCreatedAt = at;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
event: firstUser ?? lastAssistant ?? events.at(-1),
|
|
124
|
+
latestByRole,
|
|
125
|
+
minCreatedAt: Number.isFinite(minCreatedAt) ? minCreatedAt : null,
|
|
126
|
+
maxCreatedAt: Number.isFinite(maxCreatedAt) ? maxCreatedAt : null,
|
|
127
|
+
hasUntimed,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
111
131
|
/** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
|
|
112
132
|
export function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined {
|
|
113
133
|
const events = filteredItems(projection, scoped).filter(visible);
|
|
@@ -117,17 +137,14 @@ export function sessionRepresentative(projection: HistoryProjection, scoped: His
|
|
|
117
137
|
?? events.at(-1);
|
|
118
138
|
}
|
|
119
139
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
return Number.isNaN(at) ? -Infinity : at;
|
|
123
|
-
}
|
|
124
|
-
const compareCorpus = (a: Candidate, b: Candidate) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq;
|
|
140
|
+
const earliestIfUntimed = (at: number) => Number.isNaN(at) ? -Infinity : at;
|
|
141
|
+
const compareCorpus = (a: Candidate, b: Candidate) => earliestIfUntimed(eventTimestampMs(a.event)) - earliestIfUntimed(eventTimestampMs(b.event)) || (a.session ?? "").localeCompare(b.session ?? "") || a.event.seq - b.event.seq;
|
|
125
142
|
|
|
126
143
|
/** Fill the remaining budget nearest first. Shared session/seq keys merge overlapping windows. */
|
|
127
144
|
function addContext(page: HistoryPage, hits: Candidate[], radius: number, fits: (page: HistoryPage) => boolean, maxChars: number): void {
|
|
128
145
|
const key = (session: string | undefined, seq: number) => `${session ?? ""}\0${seq}`;
|
|
129
146
|
const seen = new Set(page.items.map(item => key(item.session, item.seq)));
|
|
130
|
-
const compare = (a: HistoryPageItem, b: HistoryPageItem) => (
|
|
147
|
+
const compare = (a: HistoryPageItem, b: HistoryPageItem) => earliestIfUntimed(Date.parse(a.created_at ?? "")) - earliestIfUntimed(Date.parse(b.created_at ?? "")) || (a.session ?? "").localeCompare(b.session ?? "") || a.seq - b.seq;
|
|
131
148
|
for (let distance = 1; distance <= radius; distance++) {
|
|
132
149
|
let found = false;
|
|
133
150
|
for (const { neighbors, session } of hits) {
|
|
@@ -153,9 +170,11 @@ function addContext(page: HistoryPage, hits: Candidate[], radius: number, fits:
|
|
|
153
170
|
export class CorpusCollector {
|
|
154
171
|
private readonly candidates: Candidate[] = [];
|
|
155
172
|
private readonly limit: number;
|
|
173
|
+
private readonly compiledQuery: readonly RegExp[];
|
|
156
174
|
private discarded = false;
|
|
157
175
|
constructor(private readonly scoped: HistorySelection) {
|
|
158
176
|
this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
|
|
177
|
+
this.compiledQuery = scoped.query?.length ? compileSearchQueries(scoped.query) : [];
|
|
159
178
|
}
|
|
160
179
|
|
|
161
180
|
private admit(candidate: Candidate): void {
|
|
@@ -180,50 +199,51 @@ export class CorpusCollector {
|
|
|
180
199
|
this.candidates.splice(low, 0, candidate);
|
|
181
200
|
}
|
|
182
201
|
|
|
183
|
-
/** Admit
|
|
184
|
-
addRepresentative(session: string,
|
|
202
|
+
/** Admit a session's overview representative (pre-selected or picked from a projection). */
|
|
203
|
+
addRepresentative(session: string, source: HistoryEvent | HistoryProjection | undefined): boolean {
|
|
204
|
+
const event = source && "windows" in source ? sessionRepresentative(source, this.scoped) : source;
|
|
185
205
|
if (!event) return false;
|
|
186
|
-
this.admit({ session, event });
|
|
206
|
+
this.admit({ session: session || undefined, event });
|
|
187
207
|
return true;
|
|
188
208
|
}
|
|
189
209
|
|
|
190
|
-
/**
|
|
191
|
-
|
|
192
|
-
if (this.
|
|
193
|
-
for (const hit of queryHits(projection, this.scoped, session)) this.admit(hit);
|
|
194
|
-
return true;
|
|
210
|
+
/** Admit every query match from one session; an empty query matches nothing. */
|
|
211
|
+
addMatches(session: string, projection: HistoryProjection): void {
|
|
212
|
+
if (this.compiledQuery.length === 0) return;
|
|
213
|
+
for (const hit of queryHits(projection, this.scoped, this.compiledQuery, session || undefined)) this.admit(hit);
|
|
195
214
|
}
|
|
196
215
|
|
|
197
216
|
page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited = false): HistoryPageResult {
|
|
198
|
-
|
|
217
|
+
const result = selectPrepared({ candidates: this.candidates, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
|
|
218
|
+
if (result.ok && this.compiledQuery.length > 0 && this.scoped.context) {
|
|
219
|
+
const count = result.data.items.length;
|
|
220
|
+
const hits = this.scoped.after ? this.candidates.slice(0, count) : this.candidates.slice(this.candidates.length - count);
|
|
221
|
+
addContext(result.data, hits, this.scoped.context, fits, maxChars);
|
|
222
|
+
}
|
|
223
|
+
return result;
|
|
199
224
|
}
|
|
200
225
|
}
|
|
201
226
|
|
|
202
|
-
function selectPrepared(prepared: PreparedSelection, scoped:
|
|
227
|
+
function selectPrepared(prepared: PreparedSelection, scoped: TimelineSelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
|
|
203
228
|
const { candidates } = prepared;
|
|
204
|
-
//
|
|
205
|
-
const newest = scoped.after === undefined;
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
continue;
|
|
229
|
+
// Keep a contiguous interval from the requested end, always presented oldest first.
|
|
230
|
+
const newest = scoped.after === undefined && (scoped.before !== undefined || scoped.since === undefined);
|
|
231
|
+
const start = (count: number) => newest ? candidates.length - count : 0;
|
|
232
|
+
const pageFor = (count: number, preview?: HistoryPageItem) => pageData(prepared, start(count), start(count) + count, maxChars, preview);
|
|
233
|
+
let count = Math.min(Math.max(1, scoped.limit ?? 20), candidates.length);
|
|
234
|
+
if (count > 0 && !fits(pageFor(count))) {
|
|
235
|
+
let low = 0, high = count - 1;
|
|
236
|
+
while (low < high) {
|
|
237
|
+
const mid = Math.ceil((low + high) / 2);
|
|
238
|
+
if (fits(pageFor(mid))) low = mid;
|
|
239
|
+
else high = mid - 1;
|
|
216
240
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
candidate.preview = truncateHistoryItem(candidate.preview!, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
|
|
241
|
+
count = Math.max(1, low);
|
|
242
|
+
if (low === 0) {
|
|
243
|
+
const candidate = candidates[start(1)]!;
|
|
244
|
+
candidate.preview = truncateHistoryItem(candidate.preview!, preview => fits(pageFor(1, preview)));
|
|
222
245
|
}
|
|
223
|
-
break;
|
|
224
246
|
}
|
|
225
|
-
const page =
|
|
226
|
-
|
|
227
|
-
if (scoped.context) addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
|
|
228
|
-
return success(page);
|
|
247
|
+
const page = pageFor(count);
|
|
248
|
+
return fits(page) ? success(page) : { ok: false, pageTooLarge: true };
|
|
229
249
|
}
|
|
@@ -1,18 +1,23 @@
|
|
|
1
1
|
/** Strict offline overview summaries, never projections or search indexes. Cache failures are misses. */
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { mkdir, open, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { mkdir, open, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { Type, type Static } from "typebox";
|
|
7
7
|
import { Check } from "typebox/value";
|
|
8
|
-
import { sessionIdentity, type HistorySession, type HistorySessionData, type HistorySessionRepresentative } from "./corpus.js";
|
|
9
|
-
import { HistoryRoleSchema, ToolCallStatusSchema } from "./history.js";
|
|
10
|
-
import {
|
|
8
|
+
import { sessionIdentity, type HistorySession, type HistorySessionData, type HistorySessionRepresentative, type HistorySessionSummary } from "./corpus.js";
|
|
9
|
+
import { HistoryRoleSchema, ToolCallStatusSchema, type HistoryEvent, type HistoryRole } from "./history.js";
|
|
10
|
+
import { summarizeProjection } from "./query.js";
|
|
11
11
|
import { validateCodexLineageSources, type CodexLineageSource } from "./codex-transcript.js";
|
|
12
12
|
|
|
13
13
|
// Bump whenever strict decoding, representative selection, or cached event presentation changes.
|
|
14
|
-
const VERSION = "strict-
|
|
14
|
+
const VERSION = "strict-summary-v3";
|
|
15
|
+
const VERSION_PREFIX = `{"version":${JSON.stringify(VERSION)}`;
|
|
15
16
|
const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
|
|
17
|
+
export const HISTORY_SUMMARY_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
|
|
18
|
+
const SWEEP_INTERVAL_MS = 10 * 60 * 1000;
|
|
19
|
+
const TMP_TTL_MS = 60 * 60 * 1000;
|
|
20
|
+
const lastSweep = new Map<string, number>();
|
|
16
21
|
const FingerprintSchema = Type.Object({
|
|
17
22
|
path: Type.String(), dev: Type.String(), ino: Type.String(), size: Type.String(), mtimeNs: Type.String(), ctimeNs: Type.String(),
|
|
18
23
|
}, { additionalProperties: false });
|
|
@@ -31,9 +36,20 @@ const EventSchema = Type.Object({
|
|
|
31
36
|
}, { additionalProperties: false })) }, { additionalProperties: false })),
|
|
32
37
|
}, { additionalProperties: false })),
|
|
33
38
|
}, { additionalProperties: false });
|
|
39
|
+
const LatestByRoleSchema = Type.Object({
|
|
40
|
+
user: Type.Optional(EventSchema),
|
|
41
|
+
assistant: Type.Optional(EventSchema),
|
|
42
|
+
tool: Type.Optional(EventSchema),
|
|
43
|
+
context: Type.Optional(EventSchema),
|
|
44
|
+
}, { additionalProperties: false });
|
|
34
45
|
const EntrySchema = Type.Object({
|
|
35
46
|
version: Type.Literal(VERSION), path: Type.String(), session: Type.String(),
|
|
36
|
-
event: Type.Union([EventSchema, Type.Null()]),
|
|
47
|
+
event: Type.Union([EventSchema, Type.Null()]),
|
|
48
|
+
latestByRole: LatestByRoleSchema,
|
|
49
|
+
minCreatedAt: Type.Union([Type.Number(), Type.Null()]),
|
|
50
|
+
maxCreatedAt: Type.Union([Type.Number(), Type.Null()]),
|
|
51
|
+
hasUntimed: Type.Boolean(),
|
|
52
|
+
notice: Type.Optional(Type.String()),
|
|
37
53
|
fingerprints: Type.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
|
|
38
54
|
lineageSources: Type.Array(Type.Object({ home: Type.String(), rolloutId: Type.String(), path: Type.String() }, { additionalProperties: false }), { maxItems: 63 }),
|
|
39
55
|
}, { additionalProperties: false });
|
|
@@ -60,24 +76,84 @@ function completeDependencies(path: string, harness: HistorySession["harness"],
|
|
|
60
76
|
return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
|
|
61
77
|
}
|
|
62
78
|
|
|
63
|
-
async function readEntry(path: string): Promise<unknown> {
|
|
79
|
+
async function readEntry(path: string, now = Date.now()): Promise<unknown> {
|
|
64
80
|
const file = await open(path, "r");
|
|
81
|
+
let expired = false;
|
|
65
82
|
try {
|
|
66
83
|
const info = await file.stat();
|
|
67
84
|
if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return undefined;
|
|
85
|
+
if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS) {
|
|
86
|
+
expired = true;
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
68
89
|
const buffer = Buffer.alloc(info.size + 1);
|
|
69
90
|
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
70
91
|
if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return undefined;
|
|
71
92
|
return JSON.parse(buffer.toString("utf8", 0, bytesRead));
|
|
72
|
-
} finally {
|
|
93
|
+
} finally {
|
|
94
|
+
await file.close();
|
|
95
|
+
if (expired) await unlink(path).catch(() => {});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function hasCurrentVersionPrefix(path: string): Promise<boolean> {
|
|
100
|
+
const file = await open(path, "r");
|
|
101
|
+
try {
|
|
102
|
+
const buffer = Buffer.alloc(VERSION_PREFIX.length);
|
|
103
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
104
|
+
return bytesRead === VERSION_PREFIX.length && buffer.toString("utf8") === VERSION_PREFIX;
|
|
105
|
+
} catch { return false; }
|
|
106
|
+
finally { await file.close(); }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Remove expired (>3 days), obsolete-version (e.g. v1), and stale temporary cache files. */
|
|
110
|
+
export async function pruneHistorySummaryCache(cacheRoot: string, now = Date.now()): Promise<void> {
|
|
111
|
+
let entries;
|
|
112
|
+
try { entries = await readdir(cacheRoot, { withFileTypes: true }); }
|
|
113
|
+
catch { return; }
|
|
114
|
+
for (const entry of entries) {
|
|
115
|
+
if (!entry.isFile()) continue;
|
|
116
|
+
const full = join(cacheRoot, entry.name);
|
|
117
|
+
try {
|
|
118
|
+
const info = await stat(full);
|
|
119
|
+
if (entry.name.endsWith(".tmp")) {
|
|
120
|
+
if (now - info.mtimeMs > TMP_TTL_MS) await unlink(full).catch(() => {});
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (!entry.name.endsWith(".json")) continue;
|
|
124
|
+
if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS || !await hasCurrentVersionPrefix(full)) {
|
|
125
|
+
await unlink(full).catch(() => {});
|
|
126
|
+
}
|
|
127
|
+
} catch { /* Concurrent unlink or unreadable file: ignore. */ }
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function maybeSweepCacheRoot(cacheRoot: string): void {
|
|
132
|
+
const now = Date.now();
|
|
133
|
+
const previous = lastSweep.get(cacheRoot);
|
|
134
|
+
if (previous !== undefined && now - previous < SWEEP_INTERVAL_MS) return;
|
|
135
|
+
lastSweep.set(cacheRoot, now);
|
|
136
|
+
void pruneHistorySummaryCache(cacheRoot, now).catch(() => {});
|
|
73
137
|
}
|
|
74
138
|
|
|
75
139
|
export type RepresentativeLoad = (track: (path: string) => Promise<void>) => Promise<{ data: HistorySessionData; lineageSources?: CodexLineageSource[] }>;
|
|
76
140
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
141
|
+
function hydrateEvent(event: Static<typeof EventSchema>): HistoryEvent {
|
|
142
|
+
return { ...event, createdAt: event.createdAt };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function hydrateLatestByRole(raw: Static<typeof LatestByRoleSchema>): Partial<Record<HistoryRole, HistoryEvent>> {
|
|
146
|
+
const out: Partial<Record<HistoryRole, HistoryEvent>> = {};
|
|
147
|
+
for (const role of ["user", "assistant", "tool", "context"] as const) {
|
|
148
|
+
const ev = raw[role];
|
|
149
|
+
if (ev) out[role] = hydrateEvent(ev);
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function lookupCachedSummary(
|
|
155
|
+
session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string,
|
|
156
|
+
): Promise<{ summary?: HistorySessionSummary; canonical?: string; cachePath?: string }> {
|
|
81
157
|
let canonical: string | undefined, cachePath: string | undefined;
|
|
82
158
|
const identity = sessionIdentity(session);
|
|
83
159
|
try {
|
|
@@ -88,9 +164,37 @@ export async function cachedSessionRepresentative(
|
|
|
88
164
|
&& completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources)
|
|
89
165
|
&& await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints)
|
|
90
166
|
&& await realpath(transcriptPath) === canonical) {
|
|
91
|
-
return {
|
|
167
|
+
return {
|
|
168
|
+
canonical,
|
|
169
|
+
cachePath,
|
|
170
|
+
summary: {
|
|
171
|
+
event: entry.event === null ? undefined : hydrateEvent(entry.event),
|
|
172
|
+
latestByRole: hydrateLatestByRole(entry.latestByRole),
|
|
173
|
+
minCreatedAt: entry.minCreatedAt,
|
|
174
|
+
maxCreatedAt: entry.maxCreatedAt,
|
|
175
|
+
hasUntimed: entry.hasUntimed,
|
|
176
|
+
notice: entry.notice,
|
|
177
|
+
},
|
|
178
|
+
};
|
|
92
179
|
}
|
|
93
|
-
} catch { /* Absent/corrupt/unwritable cache or changed source:
|
|
180
|
+
} catch { /* Absent/corrupt/unwritable cache or changed source: miss. */ }
|
|
181
|
+
return { canonical, cachePath };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Read-only check of a warm, validated summary; never decodes on miss. */
|
|
185
|
+
export async function peekCachedSessionSummary(
|
|
186
|
+
session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string,
|
|
187
|
+
): Promise<HistorySessionSummary | undefined> {
|
|
188
|
+
return (await lookupCachedSummary(session, transcriptPath, cacheRoot)).summary;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
|
|
192
|
+
export async function cachedSessionSummary(
|
|
193
|
+
session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad,
|
|
194
|
+
): Promise<HistorySessionSummary> {
|
|
195
|
+
const identity = sessionIdentity(session);
|
|
196
|
+
const { summary, canonical, cachePath } = await lookupCachedSummary(session, transcriptPath, cacheRoot);
|
|
197
|
+
if (summary) return summary;
|
|
94
198
|
|
|
95
199
|
const fingerprints = new Map<string, Fingerprint>();
|
|
96
200
|
let stable = canonical !== undefined;
|
|
@@ -100,20 +204,41 @@ export async function cachedSessionRepresentative(
|
|
|
100
204
|
};
|
|
101
205
|
if (canonical) await track(canonical);
|
|
102
206
|
const { data, lineageSources = [] } = await load(track);
|
|
103
|
-
const
|
|
104
|
-
const result = {
|
|
207
|
+
const computed = summarizeProjection(data.projection);
|
|
208
|
+
const result: HistorySessionSummary = { ...computed, notice: data.notice, loaded: data };
|
|
105
209
|
try {
|
|
106
210
|
const sources = [...fingerprints.values()];
|
|
107
211
|
if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources)
|
|
108
212
|
|| !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath(transcriptPath) !== canonical) return result;
|
|
109
|
-
const entry = JSON.stringify({
|
|
213
|
+
const entry = JSON.stringify({
|
|
214
|
+
version: VERSION,
|
|
215
|
+
path: canonical,
|
|
216
|
+
session: identity,
|
|
217
|
+
event: computed.event ?? null,
|
|
218
|
+
latestByRole: computed.latestByRole,
|
|
219
|
+
minCreatedAt: computed.minCreatedAt,
|
|
220
|
+
maxCreatedAt: computed.maxCreatedAt,
|
|
221
|
+
hasUntimed: computed.hasUntimed,
|
|
222
|
+
notice: data.notice,
|
|
223
|
+
fingerprints: sources,
|
|
224
|
+
lineageSources,
|
|
225
|
+
});
|
|
110
226
|
if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
|
|
111
227
|
await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
|
|
112
228
|
const temporary = `${cachePath}.${randomUUID()}.tmp`;
|
|
113
229
|
try {
|
|
114
230
|
await writeFile(temporary, entry, { flag: "wx", mode: 0o600 });
|
|
115
231
|
await rename(temporary, cachePath);
|
|
232
|
+
maybeSweepCacheRoot(cacheRoot);
|
|
116
233
|
} finally { await unlink(temporary).catch(() => {}); }
|
|
117
234
|
} catch { /* The cache cannot turn readable history into a refusal. */ }
|
|
118
235
|
return result;
|
|
119
236
|
}
|
|
237
|
+
|
|
238
|
+
/** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
|
|
239
|
+
export async function cachedSessionRepresentative(
|
|
240
|
+
session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad,
|
|
241
|
+
): Promise<HistorySessionRepresentative> {
|
|
242
|
+
const { event, notice } = await cachedSessionSummary(session, transcriptPath, cacheRoot, load);
|
|
243
|
+
return { event, notice };
|
|
244
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -44,7 +44,7 @@ export type { BootToolNames } from "./boot/text.js";
|
|
|
44
44
|
// host-supplied notes tool context or decoded history projection/lazy corpus context.
|
|
45
45
|
export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
|
|
46
46
|
export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
|
|
47
|
-
export { historyList, historyRead } from "./tools/history.js";
|
|
47
|
+
export { historyList, historySearch, historyRead } from "./tools/history.js";
|
|
48
48
|
export { projectHistory } from "./history/history.js";
|
|
49
49
|
export type { HistoryProjection } from "./history/history.js";
|
|
50
50
|
export type { HistoryContext, HistoryCorpus, HistoryHarness, HistorySession, HistorySessionData } from "./history/corpus.js";
|
package/src/notes/errors.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type NoteErrorCode = "invalid_policy" | "
|
|
1
|
+
export type NoteErrorCode = "invalid_policy" | "pin_limit" | "readonly" | "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" | "invalid_cwd" | "io_error" | "internal_error";
|
|
2
2
|
|
|
3
3
|
/** Typed store refusal. Edit locations are exposed in camelCase. */
|
|
4
4
|
export class NoteError extends Error {
|
package/src/notes/frontmatter.ts
CHANGED
|
@@ -34,9 +34,6 @@ const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"] as const;
|
|
|
34
34
|
/** Emission order, exactly the Design's key list. */
|
|
35
35
|
const KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"] as const;
|
|
36
36
|
|
|
37
|
-
/** A note description is one line; longer is not a description, it is prose in the wrong place. */
|
|
38
|
-
export const MAX_DESCRIPTION_CHARS = 160;
|
|
39
|
-
|
|
40
37
|
/** Collapse any whitespace run to one space and trim; an empty result is no description. */
|
|
41
38
|
export function collapseDescription(value: string): string | undefined {
|
|
42
39
|
const collapsed = value.replace(/\s+/g, " ").trim();
|
package/src/notes/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createNotesStore, noteIdentity } from "./store.js";
|
|
1
|
+
export { createNotesStore, noteIdentity, compareNoteRows } from "./store.js";
|
|
2
2
|
export { effectiveNotePolicy, type NotePolicy, type NotePolicyFields } from "./policy.js";
|
|
3
3
|
export { NoteError, type NoteErrorCode } from "./errors.js";
|
|
4
4
|
export { projectKey } from "./project-namespace.js";
|
package/src/notes/policy.ts
CHANGED
|
@@ -2,8 +2,13 @@ import { NoteError } from "./errors.js";
|
|
|
2
2
|
|
|
3
3
|
export type NotePolicyFields = { pinned?: boolean; budget?: number; readonly?: boolean };
|
|
4
4
|
export type NotePolicy = Required<NotePolicyFields>;
|
|
5
|
-
export const DEFAULT_NOTE_BUDGET =
|
|
5
|
+
export const DEFAULT_NOTE_BUDGET = 8192;
|
|
6
|
+
export const DEFAULT_CHEATSHEET_BUDGET = 4096;
|
|
6
7
|
export const MAX_PINNED_NOTES = 5;
|
|
8
|
+
export const WARNING_OPEN_TAG = "<notesoup:warning>";
|
|
9
|
+
export const WARNING_CLOSE_TAG = "</notesoup:warning>";
|
|
10
|
+
/** Boot index truncates descriptions past this code-point cap; longer values still save with a warning. */
|
|
11
|
+
export const MAX_DESCRIPTION_CHARS = 160;
|
|
7
12
|
/** Defaults and ordering live here; no other layer assigns behavior by page name. */
|
|
8
13
|
const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"] as const;
|
|
9
14
|
|
|
@@ -12,7 +17,7 @@ export function validateNotePolicy(fields: NotePolicyFields): void {
|
|
|
12
17
|
if (fields[key] !== undefined && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
|
|
13
18
|
}
|
|
14
19
|
if (fields.budget !== undefined && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
|
|
15
|
-
throw new NoteError("invalid_policy", "budget must be a positive
|
|
20
|
+
throw new NoteError("invalid_policy", "budget must be a positive integer.");
|
|
16
21
|
}
|
|
17
22
|
}
|
|
18
23
|
|
|
@@ -22,7 +27,7 @@ export function effectiveNotePolicy(fields: NotePolicyFields, path: string): Not
|
|
|
22
27
|
const defaultPage = DEFAULT_PINNED_PAGES.some(page => page === path);
|
|
23
28
|
return {
|
|
24
29
|
pinned: fields.pinned ?? defaultPage,
|
|
25
|
-
budget: fields.budget ?? (defaultPage ?
|
|
30
|
+
budget: fields.budget ?? (defaultPage ? DEFAULT_CHEATSHEET_BUDGET : DEFAULT_NOTE_BUDGET),
|
|
26
31
|
readonly: fields.readonly ?? false,
|
|
27
32
|
};
|
|
28
33
|
}
|
|
@@ -32,9 +37,43 @@ export function pinnedPageOrder(path: string): number {
|
|
|
32
37
|
return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
|
|
33
38
|
}
|
|
34
39
|
|
|
40
|
+
export function truncateToUtf8Bytes(text: string, maxBytes: number): { text: string; shownChars: number; totalChars: number; truncated: boolean } {
|
|
41
|
+
if (Buffer.byteLength(text, "utf8") <= maxBytes) return { text, shownChars: 0, totalChars: 0, truncated: false };
|
|
42
|
+
const chars = Array.from(text);
|
|
43
|
+
let bytes = 0;
|
|
44
|
+
let shown = 0;
|
|
45
|
+
for (const char of chars) {
|
|
46
|
+
const size = Buffer.byteLength(char, "utf8");
|
|
47
|
+
if (bytes + size > maxBytes) break;
|
|
48
|
+
bytes += size;
|
|
49
|
+
shown++;
|
|
50
|
+
}
|
|
51
|
+
return { text: chars.slice(0, shown).join(""), shownChars: shown, totalChars: chars.length, truncated: true };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function renderWarnings(warnings: readonly string[]): string {
|
|
55
|
+
if (warnings.length === 0) return "";
|
|
56
|
+
if (warnings.length === 1) return `${WARNING_OPEN_TAG}${warnings[0]}${WARNING_CLOSE_TAG}`;
|
|
57
|
+
return `${WARNING_OPEN_TAG}\n${warnings.join("\n")}\n${WARNING_CLOSE_TAG}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
35
60
|
export function noteBudgetWarnings(body: string, policy: NotePolicy): string[] {
|
|
36
|
-
const
|
|
37
|
-
|
|
61
|
+
const bytes = Buffer.byteLength(body, "utf8");
|
|
62
|
+
if (bytes <= policy.budget) return [];
|
|
63
|
+
const action = policy.pinned ? "boot truncates it to budget — trim, split, or unpin." : "trim or split it.";
|
|
64
|
+
return [`note body is ${bytes} bytes (budget ${policy.budget}); ${action}`];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function noteDescriptionWarnings(description?: string): string[] {
|
|
68
|
+
if (description === undefined) return [];
|
|
69
|
+
const count = Array.from(description).length;
|
|
70
|
+
return count > MAX_DESCRIPTION_CHARS
|
|
71
|
+
? [`description is ${count} chars (max ${MAX_DESCRIPTION_CHARS}); boot index truncates it.`]
|
|
72
|
+
: [];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function noteWarnings(body: string, policy: NotePolicy, description?: string): string[] {
|
|
76
|
+
return [...noteBudgetWarnings(body, policy), ...noteDescriptionWarnings(description)];
|
|
38
77
|
}
|
|
39
78
|
|
|
40
79
|
export function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void {
|