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
|
@@ -1,17 +1,22 @@
|
|
|
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 } from "typebox";
|
|
7
7
|
import { Check } from "typebox/value";
|
|
8
8
|
import { sessionIdentity } from "./corpus.js";
|
|
9
9
|
import { HistoryRoleSchema, ToolCallStatusSchema } from "./history.js";
|
|
10
|
-
import {
|
|
10
|
+
import { summarizeProjection } from "./query.js";
|
|
11
11
|
import { validateCodexLineageSources } from "./codex-transcript.js";
|
|
12
12
|
// Bump whenever strict decoding, representative selection, or cached event presentation changes.
|
|
13
|
-
const VERSION = "strict-
|
|
13
|
+
const VERSION = "strict-summary-v3";
|
|
14
|
+
const VERSION_PREFIX = `{"version":${JSON.stringify(VERSION)}`;
|
|
14
15
|
const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
|
|
16
|
+
export const HISTORY_SUMMARY_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
|
|
17
|
+
const SWEEP_INTERVAL_MS = 10 * 60 * 1000;
|
|
18
|
+
const TMP_TTL_MS = 60 * 60 * 1000;
|
|
19
|
+
const lastSweep = new Map();
|
|
15
20
|
const FingerprintSchema = Type.Object({
|
|
16
21
|
path: Type.String(), dev: Type.String(), ino: Type.String(), size: Type.String(), mtimeNs: Type.String(), ctimeNs: Type.String(),
|
|
17
22
|
}, { additionalProperties: false });
|
|
@@ -29,9 +34,20 @@ const EventSchema = Type.Object({
|
|
|
29
34
|
}, { additionalProperties: false })) }, { additionalProperties: false })),
|
|
30
35
|
}, { additionalProperties: false })),
|
|
31
36
|
}, { additionalProperties: false });
|
|
37
|
+
const LatestByRoleSchema = Type.Object({
|
|
38
|
+
user: Type.Optional(EventSchema),
|
|
39
|
+
assistant: Type.Optional(EventSchema),
|
|
40
|
+
tool: Type.Optional(EventSchema),
|
|
41
|
+
context: Type.Optional(EventSchema),
|
|
42
|
+
}, { additionalProperties: false });
|
|
32
43
|
const EntrySchema = Type.Object({
|
|
33
44
|
version: Type.Literal(VERSION), path: Type.String(), session: Type.String(),
|
|
34
|
-
event: Type.Union([EventSchema, Type.Null()]),
|
|
45
|
+
event: Type.Union([EventSchema, Type.Null()]),
|
|
46
|
+
latestByRole: LatestByRoleSchema,
|
|
47
|
+
minCreatedAt: Type.Union([Type.Number(), Type.Null()]),
|
|
48
|
+
maxCreatedAt: Type.Union([Type.Number(), Type.Null()]),
|
|
49
|
+
hasUntimed: Type.Boolean(),
|
|
50
|
+
notice: Type.Optional(Type.String()),
|
|
35
51
|
fingerprints: Type.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
|
|
36
52
|
lineageSources: Type.Array(Type.Object({ home: Type.String(), rolloutId: Type.String(), path: Type.String() }, { additionalProperties: false }), { maxItems: 63 }),
|
|
37
53
|
}, { additionalProperties: false });
|
|
@@ -58,12 +74,17 @@ function completeDependencies(path, harness, sources, lineage) {
|
|
|
58
74
|
const expected = [path, ...lineage.map((source) => source.path)];
|
|
59
75
|
return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
|
|
60
76
|
}
|
|
61
|
-
async function readEntry(path) {
|
|
77
|
+
async function readEntry(path, now = Date.now()) {
|
|
62
78
|
const file = await open(path, "r");
|
|
79
|
+
let expired = false;
|
|
63
80
|
try {
|
|
64
81
|
const info = await file.stat();
|
|
65
82
|
if (!info.isFile() || info.size > MAX_ENTRY_BYTES)
|
|
66
83
|
return undefined;
|
|
84
|
+
if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS) {
|
|
85
|
+
expired = true;
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
67
88
|
const buffer = Buffer.alloc(info.size + 1);
|
|
68
89
|
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
69
90
|
if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES)
|
|
@@ -72,10 +93,74 @@ async function readEntry(path) {
|
|
|
72
93
|
}
|
|
73
94
|
finally {
|
|
74
95
|
await file.close();
|
|
96
|
+
if (expired)
|
|
97
|
+
await unlink(path).catch(() => { });
|
|
75
98
|
}
|
|
76
99
|
}
|
|
77
|
-
|
|
78
|
-
|
|
100
|
+
async function hasCurrentVersionPrefix(path) {
|
|
101
|
+
const file = await open(path, "r");
|
|
102
|
+
try {
|
|
103
|
+
const buffer = Buffer.alloc(VERSION_PREFIX.length);
|
|
104
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
105
|
+
return bytesRead === VERSION_PREFIX.length && buffer.toString("utf8") === VERSION_PREFIX;
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
await file.close();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Remove expired (>3 days), obsolete-version (e.g. v1), and stale temporary cache files. */
|
|
115
|
+
export async function pruneHistorySummaryCache(cacheRoot, now = Date.now()) {
|
|
116
|
+
let entries;
|
|
117
|
+
try {
|
|
118
|
+
entries = await readdir(cacheRoot, { withFileTypes: true });
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
for (const entry of entries) {
|
|
124
|
+
if (!entry.isFile())
|
|
125
|
+
continue;
|
|
126
|
+
const full = join(cacheRoot, entry.name);
|
|
127
|
+
try {
|
|
128
|
+
const info = await stat(full);
|
|
129
|
+
if (entry.name.endsWith(".tmp")) {
|
|
130
|
+
if (now - info.mtimeMs > TMP_TTL_MS)
|
|
131
|
+
await unlink(full).catch(() => { });
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (!entry.name.endsWith(".json"))
|
|
135
|
+
continue;
|
|
136
|
+
if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS || !await hasCurrentVersionPrefix(full)) {
|
|
137
|
+
await unlink(full).catch(() => { });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch { /* Concurrent unlink or unreadable file: ignore. */ }
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function maybeSweepCacheRoot(cacheRoot) {
|
|
144
|
+
const now = Date.now();
|
|
145
|
+
const previous = lastSweep.get(cacheRoot);
|
|
146
|
+
if (previous !== undefined && now - previous < SWEEP_INTERVAL_MS)
|
|
147
|
+
return;
|
|
148
|
+
lastSweep.set(cacheRoot, now);
|
|
149
|
+
void pruneHistorySummaryCache(cacheRoot, now).catch(() => { });
|
|
150
|
+
}
|
|
151
|
+
function hydrateEvent(event) {
|
|
152
|
+
return { ...event, createdAt: event.createdAt };
|
|
153
|
+
}
|
|
154
|
+
function hydrateLatestByRole(raw) {
|
|
155
|
+
const out = {};
|
|
156
|
+
for (const role of ["user", "assistant", "tool", "context"]) {
|
|
157
|
+
const ev = raw[role];
|
|
158
|
+
if (ev)
|
|
159
|
+
out[role] = hydrateEvent(ev);
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
async function lookupCachedSummary(session, transcriptPath, cacheRoot) {
|
|
79
164
|
let canonical, cachePath;
|
|
80
165
|
const identity = sessionIdentity(session);
|
|
81
166
|
try {
|
|
@@ -86,10 +171,33 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
|
|
|
86
171
|
&& completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources)
|
|
87
172
|
&& await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints)
|
|
88
173
|
&& await realpath(transcriptPath) === canonical) {
|
|
89
|
-
return {
|
|
174
|
+
return {
|
|
175
|
+
canonical,
|
|
176
|
+
cachePath,
|
|
177
|
+
summary: {
|
|
178
|
+
event: entry.event === null ? undefined : hydrateEvent(entry.event),
|
|
179
|
+
latestByRole: hydrateLatestByRole(entry.latestByRole),
|
|
180
|
+
minCreatedAt: entry.minCreatedAt,
|
|
181
|
+
maxCreatedAt: entry.maxCreatedAt,
|
|
182
|
+
hasUntimed: entry.hasUntimed,
|
|
183
|
+
notice: entry.notice,
|
|
184
|
+
},
|
|
185
|
+
};
|
|
90
186
|
}
|
|
91
187
|
}
|
|
92
|
-
catch { /* Absent/corrupt/unwritable cache or changed source:
|
|
188
|
+
catch { /* Absent/corrupt/unwritable cache or changed source: miss. */ }
|
|
189
|
+
return { canonical, cachePath };
|
|
190
|
+
}
|
|
191
|
+
/** Read-only check of a warm, validated summary; never decodes on miss. */
|
|
192
|
+
export async function peekCachedSessionSummary(session, transcriptPath, cacheRoot) {
|
|
193
|
+
return (await lookupCachedSummary(session, transcriptPath, cacheRoot)).summary;
|
|
194
|
+
}
|
|
195
|
+
/** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
|
|
196
|
+
export async function cachedSessionSummary(session, transcriptPath, cacheRoot, load) {
|
|
197
|
+
const identity = sessionIdentity(session);
|
|
198
|
+
const { summary, canonical, cachePath } = await lookupCachedSummary(session, transcriptPath, cacheRoot);
|
|
199
|
+
if (summary)
|
|
200
|
+
return summary;
|
|
93
201
|
const fingerprints = new Map();
|
|
94
202
|
let stable = canonical !== undefined;
|
|
95
203
|
const track = async (path) => {
|
|
@@ -104,14 +212,26 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
|
|
|
104
212
|
if (canonical)
|
|
105
213
|
await track(canonical);
|
|
106
214
|
const { data, lineageSources = [] } = await load(track);
|
|
107
|
-
const
|
|
108
|
-
const result = {
|
|
215
|
+
const computed = summarizeProjection(data.projection);
|
|
216
|
+
const result = { ...computed, notice: data.notice, loaded: data };
|
|
109
217
|
try {
|
|
110
218
|
const sources = [...fingerprints.values()];
|
|
111
219
|
if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources)
|
|
112
220
|
|| !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath(transcriptPath) !== canonical)
|
|
113
221
|
return result;
|
|
114
|
-
const entry = JSON.stringify({
|
|
222
|
+
const entry = JSON.stringify({
|
|
223
|
+
version: VERSION,
|
|
224
|
+
path: canonical,
|
|
225
|
+
session: identity,
|
|
226
|
+
event: computed.event ?? null,
|
|
227
|
+
latestByRole: computed.latestByRole,
|
|
228
|
+
minCreatedAt: computed.minCreatedAt,
|
|
229
|
+
maxCreatedAt: computed.maxCreatedAt,
|
|
230
|
+
hasUntimed: computed.hasUntimed,
|
|
231
|
+
notice: data.notice,
|
|
232
|
+
fingerprints: sources,
|
|
233
|
+
lineageSources,
|
|
234
|
+
});
|
|
115
235
|
if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES)
|
|
116
236
|
return result;
|
|
117
237
|
await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
|
|
@@ -119,6 +239,7 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
|
|
|
119
239
|
try {
|
|
120
240
|
await writeFile(temporary, entry, { flag: "wx", mode: 0o600 });
|
|
121
241
|
await rename(temporary, cachePath);
|
|
242
|
+
maybeSweepCacheRoot(cacheRoot);
|
|
122
243
|
}
|
|
123
244
|
finally {
|
|
124
245
|
await unlink(temporary).catch(() => { });
|
|
@@ -127,3 +248,8 @@ export async function cachedSessionRepresentative(session, transcriptPath, cache
|
|
|
127
248
|
catch { /* The cache cannot turn readable history into a refusal. */ }
|
|
128
249
|
return result;
|
|
129
250
|
}
|
|
251
|
+
/** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
|
|
252
|
+
export async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
|
|
253
|
+
const { event, notice } = await cachedSessionSummary(session, transcriptPath, cacheRoot, load);
|
|
254
|
+
return { event, notice };
|
|
255
|
+
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
|
|
|
21
21
|
export type { BootToolNames } from "./boot/text.js";
|
|
22
22
|
export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
|
|
23
23
|
export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
|
|
24
|
-
export { historyList, historyRead } from "./tools/history.js";
|
|
24
|
+
export { historyList, historySearch, historyRead } from "./tools/history.js";
|
|
25
25
|
export { projectHistory } from "./history/history.js";
|
|
26
26
|
export type { HistoryProjection } from "./history/history.js";
|
|
27
27
|
export type { HistoryContext, HistoryCorpus, HistoryHarness, HistorySession, HistorySessionData } from "./history/corpus.js";
|
package/dist/src/index.js
CHANGED
|
@@ -21,7 +21,7 @@ export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
|
|
|
21
21
|
// host-supplied notes tool context or decoded history projection/lazy corpus context.
|
|
22
22
|
export { notesList, notesRead, notesUpdate, notesWrite } from "./tools/notes.js";
|
|
23
23
|
export { notesIdentityForCall, notesToolContext } from "./tools/notes-context.js";
|
|
24
|
-
export { historyList, historyRead } from "./tools/history.js";
|
|
24
|
+
export { historyList, historySearch, historyRead } from "./tools/history.js";
|
|
25
25
|
export { projectHistory } from "./history/history.js";
|
|
26
26
|
// Budget: pure thresholds and the approved reset prose.
|
|
27
27
|
export { deriveThresholds, remainingBudget } from "./budget/policy.js";
|
|
@@ -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
|
/** Typed store refusal. Edit locations are exposed in camelCase. */
|
|
3
3
|
export declare class NoteError extends Error {
|
|
4
4
|
readonly code: NoteErrorCode;
|
|
@@ -25,8 +25,6 @@ export type NoteMeta = NotePolicyFields & {
|
|
|
25
25
|
description?: string;
|
|
26
26
|
[key: string]: unknown;
|
|
27
27
|
};
|
|
28
|
-
/** A note description is one line; longer is not a description, it is prose in the wrong place. */
|
|
29
|
-
export declare const MAX_DESCRIPTION_CHARS = 160;
|
|
30
28
|
/** Collapse any whitespace run to one space and trim; an empty result is no description. */
|
|
31
29
|
export declare function collapseDescription(value: string): string | undefined;
|
|
32
30
|
/**
|
|
@@ -4,8 +4,6 @@ const ORIGINS = ["user", "self", "external"];
|
|
|
4
4
|
const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
|
|
5
5
|
/** Emission order, exactly the Design's key list. */
|
|
6
6
|
const KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
|
|
7
|
-
/** A note description is one line; longer is not a description, it is prose in the wrong place. */
|
|
8
|
-
export const MAX_DESCRIPTION_CHARS = 160;
|
|
9
7
|
/** Collapse any whitespace run to one space and trim; an empty result is no description. */
|
|
10
8
|
export function collapseDescription(value) {
|
|
11
9
|
const collapsed = value.replace(/\s+/g, " ").trim();
|
|
@@ -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/dist/src/notes/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createNotesStore, noteIdentity } from "./store.js";
|
|
1
|
+
export { createNotesStore, noteIdentity, compareNoteRows } from "./store.js";
|
|
2
2
|
export { effectiveNotePolicy } from "./policy.js";
|
|
3
3
|
export { NoteError } from "./errors.js";
|
|
4
4
|
export { projectKey } from "./project-namespace.js";
|
|
@@ -4,13 +4,27 @@ export type NotePolicyFields = {
|
|
|
4
4
|
readonly?: boolean;
|
|
5
5
|
};
|
|
6
6
|
export type NotePolicy = Required<NotePolicyFields>;
|
|
7
|
-
export declare const DEFAULT_NOTE_BUDGET =
|
|
7
|
+
export declare const DEFAULT_NOTE_BUDGET = 8192;
|
|
8
|
+
export declare const DEFAULT_CHEATSHEET_BUDGET = 4096;
|
|
8
9
|
export declare const MAX_PINNED_NOTES = 5;
|
|
10
|
+
export declare const WARNING_OPEN_TAG = "<notesoup:warning>";
|
|
11
|
+
export declare const WARNING_CLOSE_TAG = "</notesoup:warning>";
|
|
12
|
+
/** Boot index truncates descriptions past this code-point cap; longer values still save with a warning. */
|
|
13
|
+
export declare const MAX_DESCRIPTION_CHARS = 160;
|
|
9
14
|
export declare function validateNotePolicy(fields: NotePolicyFields): void;
|
|
10
15
|
/** Only root default pages are pinned implicitly; an explicit false always wins. */
|
|
11
16
|
export declare function effectiveNotePolicy(fields: NotePolicyFields, path: string): NotePolicy;
|
|
12
17
|
export declare function pinnedPageOrder(path: string): number;
|
|
18
|
+
export declare function truncateToUtf8Bytes(text: string, maxBytes: number): {
|
|
19
|
+
text: string;
|
|
20
|
+
shownChars: number;
|
|
21
|
+
totalChars: number;
|
|
22
|
+
truncated: boolean;
|
|
23
|
+
};
|
|
24
|
+
export declare function renderWarnings(warnings: readonly string[]): string;
|
|
13
25
|
export declare function noteBudgetWarnings(body: string, policy: NotePolicy): string[];
|
|
26
|
+
export declare function noteDescriptionWarnings(description?: string): string[];
|
|
27
|
+
export declare function noteWarnings(body: string, policy: NotePolicy, description?: string): string[];
|
|
14
28
|
export declare function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void;
|
|
15
29
|
/** Apply only explicit values, leaving absent on-disk defaults absent across moves. */
|
|
16
30
|
export declare function applyNotePolicy(target: NotePolicyFields, fields: NotePolicyFields): void;
|
package/dist/src/notes/policy.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { NoteError } from "./errors.js";
|
|
2
|
-
export const DEFAULT_NOTE_BUDGET =
|
|
2
|
+
export const DEFAULT_NOTE_BUDGET = 8192;
|
|
3
|
+
export const DEFAULT_CHEATSHEET_BUDGET = 4096;
|
|
3
4
|
export const MAX_PINNED_NOTES = 5;
|
|
5
|
+
export const WARNING_OPEN_TAG = "<notesoup:warning>";
|
|
6
|
+
export const WARNING_CLOSE_TAG = "</notesoup:warning>";
|
|
7
|
+
/** Boot index truncates descriptions past this code-point cap; longer values still save with a warning. */
|
|
8
|
+
export const MAX_DESCRIPTION_CHARS = 160;
|
|
4
9
|
/** Defaults and ordering live here; no other layer assigns behavior by page name. */
|
|
5
10
|
const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"];
|
|
6
11
|
export function validateNotePolicy(fields) {
|
|
@@ -9,7 +14,7 @@ export function validateNotePolicy(fields) {
|
|
|
9
14
|
throw new NoteError("invalid_policy", `${key} must be a boolean.`);
|
|
10
15
|
}
|
|
11
16
|
if (fields.budget !== undefined && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
|
|
12
|
-
throw new NoteError("invalid_policy", "budget must be a positive
|
|
17
|
+
throw new NoteError("invalid_policy", "budget must be a positive integer.");
|
|
13
18
|
}
|
|
14
19
|
}
|
|
15
20
|
/** Only root default pages are pinned implicitly; an explicit false always wins. */
|
|
@@ -18,7 +23,7 @@ export function effectiveNotePolicy(fields, path) {
|
|
|
18
23
|
const defaultPage = DEFAULT_PINNED_PAGES.some(page => page === path);
|
|
19
24
|
return {
|
|
20
25
|
pinned: fields.pinned ?? defaultPage,
|
|
21
|
-
budget: fields.budget ?? (defaultPage ?
|
|
26
|
+
budget: fields.budget ?? (defaultPage ? DEFAULT_CHEATSHEET_BUDGET : DEFAULT_NOTE_BUDGET),
|
|
22
27
|
readonly: fields.readonly ?? false,
|
|
23
28
|
};
|
|
24
29
|
}
|
|
@@ -26,9 +31,45 @@ export function pinnedPageOrder(path) {
|
|
|
26
31
|
const index = DEFAULT_PINNED_PAGES.findIndex(page => page === path);
|
|
27
32
|
return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
|
|
28
33
|
}
|
|
34
|
+
export function truncateToUtf8Bytes(text, maxBytes) {
|
|
35
|
+
if (Buffer.byteLength(text, "utf8") <= maxBytes)
|
|
36
|
+
return { text, shownChars: 0, totalChars: 0, truncated: false };
|
|
37
|
+
const chars = Array.from(text);
|
|
38
|
+
let bytes = 0;
|
|
39
|
+
let shown = 0;
|
|
40
|
+
for (const char of chars) {
|
|
41
|
+
const size = Buffer.byteLength(char, "utf8");
|
|
42
|
+
if (bytes + size > maxBytes)
|
|
43
|
+
break;
|
|
44
|
+
bytes += size;
|
|
45
|
+
shown++;
|
|
46
|
+
}
|
|
47
|
+
return { text: chars.slice(0, shown).join(""), shownChars: shown, totalChars: chars.length, truncated: true };
|
|
48
|
+
}
|
|
49
|
+
export function renderWarnings(warnings) {
|
|
50
|
+
if (warnings.length === 0)
|
|
51
|
+
return "";
|
|
52
|
+
if (warnings.length === 1)
|
|
53
|
+
return `${WARNING_OPEN_TAG}${warnings[0]}${WARNING_CLOSE_TAG}`;
|
|
54
|
+
return `${WARNING_OPEN_TAG}\n${warnings.join("\n")}\n${WARNING_CLOSE_TAG}`;
|
|
55
|
+
}
|
|
29
56
|
export function noteBudgetWarnings(body, policy) {
|
|
30
|
-
const
|
|
31
|
-
|
|
57
|
+
const bytes = Buffer.byteLength(body, "utf8");
|
|
58
|
+
if (bytes <= policy.budget)
|
|
59
|
+
return [];
|
|
60
|
+
const action = policy.pinned ? "boot truncates it to budget — trim, split, or unpin." : "trim or split it.";
|
|
61
|
+
return [`note body is ${bytes} bytes (budget ${policy.budget}); ${action}`];
|
|
62
|
+
}
|
|
63
|
+
export function noteDescriptionWarnings(description) {
|
|
64
|
+
if (description === undefined)
|
|
65
|
+
return [];
|
|
66
|
+
const count = Array.from(description).length;
|
|
67
|
+
return count > MAX_DESCRIPTION_CHARS
|
|
68
|
+
? [`description is ${count} chars (max ${MAX_DESCRIPTION_CHARS}); boot index truncates it.`]
|
|
69
|
+
: [];
|
|
70
|
+
}
|
|
71
|
+
export function noteWarnings(body, policy, description) {
|
|
72
|
+
return [...noteBudgetWarnings(body, policy), ...noteDescriptionWarnings(description)];
|
|
32
73
|
}
|
|
33
74
|
export function assertNoteUnlocked(fields, unlock) {
|
|
34
75
|
if (fields.readonly === true && unlock !== false)
|
|
@@ -4,6 +4,17 @@ import { type Scope } from "./paths.js";
|
|
|
4
4
|
import { type ProjectReceipt } from "./project-namespace.js";
|
|
5
5
|
import { type NotePolicyFields } from "./policy.js";
|
|
6
6
|
export type { NoteMeta, Origin, Scope };
|
|
7
|
+
export declare function compareNoteRows(a: {
|
|
8
|
+
address: string;
|
|
9
|
+
meta: {
|
|
10
|
+
updatedAt: number;
|
|
11
|
+
};
|
|
12
|
+
}, b: {
|
|
13
|
+
address: string;
|
|
14
|
+
meta: {
|
|
15
|
+
updatedAt: number;
|
|
16
|
+
};
|
|
17
|
+
}): number;
|
|
7
18
|
export type NoteRow = {
|
|
8
19
|
address: string;
|
|
9
20
|
scope: Scope;
|
|
@@ -28,6 +39,7 @@ export type NoteSearchRow = {
|
|
|
28
39
|
export type EditOperation = {
|
|
29
40
|
oldText: string;
|
|
30
41
|
newText: string;
|
|
42
|
+
replaceAll?: boolean;
|
|
31
43
|
};
|
|
32
44
|
export type WriteOptions = NotePolicyFields & {
|
|
33
45
|
origin?: Origin;
|
package/dist/src/notes/store.js
CHANGED
|
@@ -7,10 +7,13 @@ import { isFilesystemError } from "./fs-error.js";
|
|
|
7
7
|
import { snapshotNotesIdentity } from "./identity.js";
|
|
8
8
|
import { NoteError } from "./errors.js";
|
|
9
9
|
import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
|
|
10
|
-
import { collapseDescription, isOrigin, localIso,
|
|
10
|
+
import { collapseDescription, isOrigin, localIso, parseNote, serializeNote, stripLeadingFrontmatter } from "./frontmatter.js";
|
|
11
11
|
import { namespaceSlugs, noteFileName, physicalPath, scopeDir, isSessionId, SLUG_PATTERN } from "./paths.js";
|
|
12
12
|
import { projectReceipt } from "./project-namespace.js";
|
|
13
|
-
import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES,
|
|
13
|
+
import { applyNotePolicy, assertNoteUnlocked, effectiveNotePolicy, MAX_PINNED_NOTES, noteWarnings, validateNotePolicy } from "./policy.js";
|
|
14
|
+
export function compareNoteRows(a, b) {
|
|
15
|
+
return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
|
|
16
|
+
}
|
|
14
17
|
// Recency sorts tie-break by address, so two writes sharing one Date.now() tick would silently invert the recent-first contract. Write stamps are strictly increasing per process.
|
|
15
18
|
let lastWriteStamp = 0;
|
|
16
19
|
function writeStamp() {
|
|
@@ -154,16 +157,6 @@ function assertOrigin(value) {
|
|
|
154
157
|
throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
|
|
155
158
|
return value;
|
|
156
159
|
}
|
|
157
|
-
/** A description is one normalized line; empty clears it. Only the authored value is refused, never read. */
|
|
158
|
-
function normalizeDescription(value) {
|
|
159
|
-
const collapsed = collapseDescription(value);
|
|
160
|
-
if (collapsed === undefined)
|
|
161
|
-
return undefined;
|
|
162
|
-
const count = Array.from(collapsed).length;
|
|
163
|
-
if (count > MAX_DESCRIPTION_CHARS)
|
|
164
|
-
throw new NoteError("invalid_description", `description is ${count} characters; limit is ${MAX_DESCRIPTION_CHARS}.`);
|
|
165
|
-
return collapsed;
|
|
166
|
-
}
|
|
167
160
|
function assertWho(value, scope) {
|
|
168
161
|
if (typeof value !== "string" || !(scope === "session" ? isSessionId(value) : SLUG_PATTERN.test(value))) {
|
|
169
162
|
throw new NoteError("invalid_scope", scope === "session" ? "session id must be a safe single directory component" : "who must be a canonical lowercase slug");
|
|
@@ -293,7 +286,7 @@ export function createNotesStore(input) {
|
|
|
293
286
|
async function write(address, content, options = {}) {
|
|
294
287
|
const stableOptions = { ...options };
|
|
295
288
|
validateNotePolicy(stableOptions);
|
|
296
|
-
const description = stableOptions.description === undefined ? undefined :
|
|
289
|
+
const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
|
|
297
290
|
const destination = assertAddress(address);
|
|
298
291
|
assertWritablePath(destination.path);
|
|
299
292
|
const scope = destination.scope;
|
|
@@ -338,7 +331,7 @@ export function createNotesStore(input) {
|
|
|
338
331
|
assertSerializedSize(serialized);
|
|
339
332
|
await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
|
|
340
333
|
await atomicWrite(path, serialized);
|
|
341
|
-
return { meta, outcome, warnings:
|
|
334
|
+
return { meta, outcome, warnings: noteWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description) };
|
|
342
335
|
}));
|
|
343
336
|
}
|
|
344
337
|
async function read(address) {
|
|
@@ -364,7 +357,7 @@ export function createNotesStore(input) {
|
|
|
364
357
|
const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
|
|
365
358
|
const stableOptions = { ...options };
|
|
366
359
|
validateNotePolicy(stableOptions);
|
|
367
|
-
const description = stableOptions.description === undefined ? undefined :
|
|
360
|
+
const description = stableOptions.description === undefined ? undefined : collapseDescription(stableOptions.description);
|
|
368
361
|
const from = assertAddress(address);
|
|
369
362
|
const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
|
|
370
363
|
assertWritablePath(destination.path);
|
|
@@ -421,16 +414,19 @@ export function createNotesStore(input) {
|
|
|
421
414
|
throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
|
|
422
415
|
if (typeof newText !== "string")
|
|
423
416
|
throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
|
|
417
|
+
if (operation.replaceAll !== undefined && typeof operation.replaceAll !== "boolean")
|
|
418
|
+
throw new NoteError("invalid_edit", `edits[${index}].replaceAll must be a boolean.`, { editIndex: index });
|
|
419
|
+
const replaceAll = operation.replaceAll ?? stableOptions.replaceAll ?? false;
|
|
424
420
|
const lines = matchLineNumbers(next, oldText);
|
|
425
421
|
if (lines.length === 0)
|
|
426
422
|
throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
|
|
427
|
-
if (lines.length > 1 && !
|
|
423
|
+
if (lines.length > 1 && !replaceAll) {
|
|
428
424
|
throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
|
|
429
425
|
}
|
|
430
426
|
if (oldText !== newText)
|
|
431
427
|
applied++;
|
|
432
428
|
// Positional splicing preserves user replacement text byte-for-byte.
|
|
433
|
-
if (
|
|
429
|
+
if (replaceAll)
|
|
434
430
|
next = next.split(oldText).join(newText);
|
|
435
431
|
else {
|
|
436
432
|
const matchIndex = next.indexOf(oldText);
|
|
@@ -467,7 +463,7 @@ export function createNotesStore(input) {
|
|
|
467
463
|
await atomicWrite(sameFile ? sourceReal : path, serialized);
|
|
468
464
|
if (moved)
|
|
469
465
|
await rm(fromPath, { force: true });
|
|
470
|
-
return { meta, warnings:
|
|
466
|
+
return { meta, warnings: noteWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
|
|
471
467
|
};
|
|
472
468
|
return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
|
|
473
469
|
}
|
|
@@ -547,7 +543,7 @@ export function createNotesStore(input) {
|
|
|
547
543
|
for await (const row of scan(stableOptions, status)) {
|
|
548
544
|
rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
|
|
549
545
|
}
|
|
550
|
-
rows.sort(
|
|
546
|
+
rows.sort(compareNoteRows);
|
|
551
547
|
return { rows, status: status ?? { namespacesUnavailable: [] } };
|
|
552
548
|
}
|
|
553
549
|
function listWithStatus(options = {}) {
|
|
@@ -562,7 +558,7 @@ export function createNotesStore(input) {
|
|
|
562
558
|
const rows = [];
|
|
563
559
|
for await (const note of scan(stableOptions, status)) {
|
|
564
560
|
const { address, path, scope, meta, body } = note;
|
|
565
|
-
const warnings =
|
|
561
|
+
const warnings = noteWarnings(body, effectiveNotePolicy(meta, path), meta.description);
|
|
566
562
|
if (stableQueries.length === 0) {
|
|
567
563
|
rows.push({ address, path, scope, meta, warnings, matches: [] });
|
|
568
564
|
continue;
|
package/dist/src/text-match.d.ts
CHANGED
|
@@ -6,8 +6,17 @@ export declare class InvalidQueryError extends Error {
|
|
|
6
6
|
export declare function searchQueries(query: unknown): string[];
|
|
7
7
|
/** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
|
|
8
8
|
export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
|
|
9
|
+
/** Compile literal Unicode case-insensitive patterns once per search operation. */
|
|
10
|
+
export declare function compileSearchQueries(queries: readonly string[]): RegExp[];
|
|
11
|
+
/** Count Unicode code points in `text.slice(0, utf16End)` without allocating an array. */
|
|
12
|
+
export declare function codePointCount(text: string, utf16End?: number): number;
|
|
13
|
+
/** Slice `[start, start + limit)` code points without splitting the entire string into an array. */
|
|
14
|
+
export declare function sliceCodePoints(text: string, start: number, limit: number): {
|
|
15
|
+
text: string;
|
|
16
|
+
truncated: boolean;
|
|
17
|
+
};
|
|
9
18
|
/**
|
|
10
19
|
* Code-point offset of the earliest case-insensitive literal match, or -1 when
|
|
11
20
|
* none occurs. Match against the original text so Unicode casing cannot shift offsets.
|
|
12
21
|
*/
|
|
13
|
-
export declare function earliestMatchOffsetChars(text: string, queries: string[]): number;
|
|
22
|
+
export declare function earliestMatchOffsetChars(text: string, queries: readonly (string | RegExp)[]): number;
|
package/dist/src/text-match.js
CHANGED
|
@@ -32,6 +32,45 @@ export function prefixFit(text, fits) {
|
|
|
32
32
|
}
|
|
33
33
|
return chars.slice(0, low).join("");
|
|
34
34
|
}
|
|
35
|
+
/** Compile literal Unicode case-insensitive patterns once per search operation. */
|
|
36
|
+
export function compileSearchQueries(queries) {
|
|
37
|
+
return queries.map((query) => new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu"));
|
|
38
|
+
}
|
|
39
|
+
/** Count Unicode code points in `text.slice(0, utf16End)` without allocating an array. */
|
|
40
|
+
export function codePointCount(text, utf16End = text.length) {
|
|
41
|
+
let count = utf16End;
|
|
42
|
+
for (let i = 0; i < utf16End - 1; i++) {
|
|
43
|
+
const code = text.charCodeAt(i);
|
|
44
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
45
|
+
const next = text.charCodeAt(i + 1);
|
|
46
|
+
if (next >= 0xdc00 && next <= 0xdfff) {
|
|
47
|
+
count--;
|
|
48
|
+
i++;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return count;
|
|
53
|
+
}
|
|
54
|
+
/** Slice `[start, start + limit)` code points without splitting the entire string into an array. */
|
|
55
|
+
export function sliceCodePoints(text, start, limit) {
|
|
56
|
+
const len = text.length;
|
|
57
|
+
let utf16Start = 0;
|
|
58
|
+
let cp = 0;
|
|
59
|
+
while (cp < start && utf16Start < len) {
|
|
60
|
+
const code = text.charCodeAt(utf16Start);
|
|
61
|
+
utf16Start += code >= 0xd800 && code <= 0xdbff && utf16Start + 1 < len && text.charCodeAt(utf16Start + 1) >= 0xdc00 && text.charCodeAt(utf16Start + 1) <= 0xdfff ? 2 : 1;
|
|
62
|
+
cp++;
|
|
63
|
+
}
|
|
64
|
+
let utf16End = utf16Start;
|
|
65
|
+
let taken = 0;
|
|
66
|
+
while (taken < limit && utf16End < len) {
|
|
67
|
+
const code = text.charCodeAt(utf16End);
|
|
68
|
+
utf16End += code >= 0xd800 && code <= 0xdbff && utf16End + 1 < len && text.charCodeAt(utf16End + 1) >= 0xdc00 && text.charCodeAt(utf16End + 1) <= 0xdfff ? 2 : 1;
|
|
69
|
+
taken++;
|
|
70
|
+
}
|
|
71
|
+
const truncated = start > 0 || utf16End < len;
|
|
72
|
+
return { text: truncated ? text.slice(utf16Start, utf16End) : text, truncated };
|
|
73
|
+
}
|
|
35
74
|
/**
|
|
36
75
|
* Code-point offset of the earliest case-insensitive literal match, or -1 when
|
|
37
76
|
* none occurs. Match against the original text so Unicode casing cannot shift offsets.
|
|
@@ -39,12 +78,12 @@ export function prefixFit(text, fits) {
|
|
|
39
78
|
export function earliestMatchOffsetChars(text, queries) {
|
|
40
79
|
let earliest = -1;
|
|
41
80
|
for (const query of queries) {
|
|
42
|
-
const
|
|
43
|
-
const index =
|
|
81
|
+
const pattern = typeof query === "string" ? new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu") : query;
|
|
82
|
+
const index = pattern.exec(text)?.index ?? -1;
|
|
44
83
|
if (index < 0)
|
|
45
84
|
continue;
|
|
46
85
|
if (earliest < 0 || index < earliest)
|
|
47
86
|
earliest = index;
|
|
48
87
|
}
|
|
49
|
-
return earliest < 0 ? -1 :
|
|
88
|
+
return earliest < 0 ? -1 : codePointCount(text, earliest);
|
|
50
89
|
}
|