notesoup 0.57.3 → 0.58.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/README.md +15 -1
- package/dist/plugins/claude/src/helper.js +2 -11
- package/dist/plugins/claude/src/thresholds.js +5 -18
- package/dist/plugins/codex/src/mcp.js +3 -11
- package/dist/plugins/codex/src/state.d.ts +1 -1
- package/dist/plugins/codex/src/state.js +1 -1
- package/dist/plugins/dsh/tools.js +1 -1
- package/dist/plugins/pi/boot.d.ts +1 -1
- package/dist/plugins/pi/boot.js +2 -3
- package/dist/plugins/pi/budget.d.ts +1 -1
- package/dist/plugins/pi/budget.js +1 -1
- package/dist/plugins/pi/render.d.ts +1 -1
- package/dist/plugins/pi/render.js +20 -11
- package/dist/plugins/pi/runtime.js +6 -2
- package/dist/plugins/pi/tool-result.d.ts +2 -1
- package/dist/plugins/pi/window.js +24 -1
- package/dist/src/boot/render.d.ts +3 -4
- package/dist/src/boot/render.js +23 -21
- package/dist/src/boot/text.d.ts +2 -5
- package/dist/src/boot/text.js +12 -9
- package/dist/src/budget/text.d.ts +1 -1
- package/dist/src/budget/text.js +1 -1
- package/dist/src/history/corpus.d.ts +1 -1
- package/dist/src/history/corpus.js +1 -1
- package/dist/src/history/history.d.ts +2 -2
- package/dist/src/history/history.js +5 -8
- package/dist/src/history/query.d.ts +11 -3
- package/dist/src/history/query.js +7 -11
- package/dist/src/index.d.ts +4 -3
- package/dist/src/index.js +1 -1
- package/dist/src/notes/constants.d.ts +1 -1
- package/dist/src/notes/constants.js +1 -1
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/frontmatter.d.ts +2 -1
- package/dist/src/notes/frontmatter.js +3 -1
- package/dist/src/notes/index.d.ts +1 -0
- package/dist/src/notes/index.js +1 -0
- package/dist/src/notes/policy.d.ts +16 -0
- package/dist/src/notes/policy.js +43 -0
- package/dist/src/notes/store.d.ts +8 -3
- package/dist/src/notes/store.js +64 -20
- package/dist/src/result.d.ts +21 -0
- package/dist/src/result.js +18 -0
- package/dist/src/text-match.d.ts +8 -0
- package/dist/src/text-match.js +34 -0
- package/dist/src/tools/dream.d.ts +9 -1
- package/dist/src/tools/dream.js +2 -1
- package/dist/src/tools/history.js +14 -5
- package/dist/src/tools/notes.d.ts +75 -13
- package/dist/src/tools/notes.js +58 -19
- package/dist/src/tools/output.d.ts +1 -3
- package/dist/src/tools/output.js +1 -19
- package/dist/src/tools/result.d.ts +2 -20
- package/dist/src/tools/result.js +4 -18
- package/dist/src/tools/schema.d.ts +3 -7
- package/dist/src/tools/schema.js +10 -16
- package/dist/test/agent-loop.test.js +78 -6
- package/dist/test/boot.integration.test.js +30 -3
- package/dist/test/claude-mod.test.js +7 -6
- package/dist/test/codex-history.test.js +2 -2
- package/dist/test/codex-plugin.test.js +2 -0
- package/dist/test/dependencies.test.js +38 -3
- package/dist/test/dsh.test.js +1 -1
- package/dist/test/helpers/dependency-graph.js +12 -6
- package/dist/test/helpers/extension.d.ts +2 -1
- package/dist/test/history.integration.test.js +47 -1
- package/dist/test/host-neutral.test.js +4 -3
- package/dist/test/model-facing-text.test.js +20 -16
- package/dist/test/note-policy.test.d.ts +1 -0
- package/dist/test/note-policy.test.js +227 -0
- package/dist/test/notes-query-namespaces.test.js +7 -3
- package/dist/test/notes.integration.test.js +10 -10
- package/dist/test/notes.test.js +4 -4
- package/dist/test/pi-render.test.js +28 -1
- package/dist/test/project-namespace.test.js +1 -1
- package/docs/architecture.md +10 -7
- package/docs/dsh.md +1 -1
- package/docs/notes-library.md +20 -7
- package/docs/reset-lifecycle.md +2 -2
- package/docs/tool-results.md +3 -1
- package/package.json +12 -12
- package/playbook.md +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +528 -422
- package/plugins/claude/hooks/register.ts +1 -10
- package/plugins/claude/playbook.md +1 -1
- package/plugins/claude/skills/dream/SKILL.md +1 -1
- package/plugins/claude/skills/memory/SKILL.md +1 -1
- package/plugins/claude/src/helper.ts +2 -11
- package/plugins/claude/src/thresholds.ts +5 -15
- package/plugins/codex/dist/codex/notesoup.js +520 -403
- package/plugins/codex/src/mcp.ts +5 -12
- package/plugins/codex/src/state.ts +1 -1
- package/plugins/dsh/tools.ts +2 -1
- package/plugins/pi/boot.ts +3 -4
- package/plugins/pi/budget.ts +1 -1
- package/plugins/pi/render.ts +20 -8
- package/plugins/pi/runtime.ts +6 -2
- package/plugins/pi/tool-result.ts +2 -1
- package/plugins/pi/window.ts +20 -1
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +1 -1
- package/src/boot/render.ts +24 -21
- package/src/boot/text.ts +12 -9
- package/src/budget/text.ts +1 -1
- package/src/history/corpus.ts +1 -1
- package/src/history/history.ts +5 -6
- package/src/history/query.ts +11 -14
- package/src/index.ts +5 -2
- package/src/notes/constants.ts +1 -1
- package/src/notes/errors.ts +1 -1
- package/src/notes/frontmatter.ts +4 -2
- package/src/notes/index.ts +1 -0
- package/src/notes/policy.ts +49 -0
- package/src/notes/store.ts +66 -26
- package/src/result.ts +26 -0
- package/src/text-match.ts +32 -0
- package/src/tools/dream.ts +2 -1
- package/src/tools/history.ts +15 -6
- package/src/tools/notes.ts +60 -20
- package/src/tools/output.ts +1 -17
- package/src/tools/result.ts +4 -26
- package/src/tools/schema.ts +11 -17
- package/dist/plugins/codex/src/history.d.ts +0 -3
- package/dist/plugins/codex/src/history.js +0 -2
- package/dist/plugins/codex/src/transcript.d.ts +0 -3
- package/dist/plugins/codex/src/transcript.js +0 -2
- package/plugins/codex/src/history.ts +0 -3
- package/plugins/codex/src/transcript.ts +0 -3
|
@@ -1,6 +1,6 @@
|
|
|
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
|
-
import { type Outcome } from "../
|
|
3
|
+
import { type Outcome } from "../result.js";
|
|
4
4
|
import { type HistoryEvent, type HistoryFilter, type HistoryProjection } from "./history.js";
|
|
5
5
|
export declare function isMultiPage(page: HistoryPage): boolean;
|
|
6
6
|
export declare function markMultiPage(page: HistoryPage): HistoryPage;
|
|
@@ -54,7 +54,15 @@ export declare const HistoryPageSchema: Type.TObject<{
|
|
|
54
54
|
}>;
|
|
55
55
|
/** One whole page payload, before it becomes an outcome. */
|
|
56
56
|
export type HistoryPage = Static<typeof HistoryPageSchema>;
|
|
57
|
-
|
|
57
|
+
/** A caller's budget rejected even the shortest page; tool limits and refusal copy belong to the caller. */
|
|
58
|
+
export type HistoryPageResult = Outcome<HistoryPage> | {
|
|
59
|
+
ok: false;
|
|
60
|
+
pageTooLarge: {
|
|
61
|
+
count: number;
|
|
62
|
+
multi: boolean;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
export declare function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult;
|
|
58
66
|
/** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
|
|
59
67
|
export declare function corpusSelection(params: HistorySelection): Outcome<HistorySelection>;
|
|
60
68
|
/** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
|
|
@@ -71,5 +79,5 @@ export declare class CorpusCollector {
|
|
|
71
79
|
addRepresentative(session: string, event: HistoryEvent | undefined): boolean;
|
|
72
80
|
/** Returns whether this session contributes an overview representative. */
|
|
73
81
|
add(session: string, projection: HistoryProjection): boolean;
|
|
74
|
-
page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited?: boolean):
|
|
82
|
+
page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited?: boolean): HistoryPageResult;
|
|
75
83
|
}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
|
|
2
2
|
import { Type } from "typebox";
|
|
3
|
-
import { failure, success } from "../
|
|
4
|
-
import { prefixFit,
|
|
5
|
-
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
6
|
-
import { InvalidQueryError, searchQueries } from "../tools/schema.js";
|
|
3
|
+
import { failure, success } from "../result.js";
|
|
4
|
+
import { earliestMatchOffsetChars, InvalidQueryError, prefixFit, searchQueries } from "../text-match.js";
|
|
7
5
|
import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
|
|
8
6
|
const multiPages = new WeakSet();
|
|
9
7
|
export function isMultiPage(page) { return multiPages.has(page); }
|
|
@@ -79,7 +77,7 @@ function prepareSelection(projection, params) {
|
|
|
79
77
|
const folds = !params.roles && params.query === undefined;
|
|
80
78
|
const candidates = [];
|
|
81
79
|
let run = [];
|
|
82
|
-
for (const event of filteredItems(projection, params
|
|
80
|
+
for (const event of filteredItems(projection, params)) {
|
|
83
81
|
if (folds && (event.role === "tool" || event.role === "context")) {
|
|
84
82
|
run.push(event);
|
|
85
83
|
continue;
|
|
@@ -144,7 +142,7 @@ export function corpusSelection(params) {
|
|
|
144
142
|
}
|
|
145
143
|
/** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
|
|
146
144
|
export function sessionRepresentative(projection, scoped) {
|
|
147
|
-
const events = filteredItems(projection, scoped
|
|
145
|
+
const events = filteredItems(projection, scoped).filter((event) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "");
|
|
148
146
|
if (scoped.roles)
|
|
149
147
|
return events.at(-1);
|
|
150
148
|
return events.find((event) => event.role === "user")
|
|
@@ -200,7 +198,7 @@ export class CorpusCollector {
|
|
|
200
198
|
add(session, projection) {
|
|
201
199
|
if (this.scoped.query === undefined)
|
|
202
200
|
return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
|
|
203
|
-
for (const event of filteredItems(projection, this.scoped
|
|
201
|
+
for (const event of filteredItems(projection, this.scoped)) {
|
|
204
202
|
const document = eventDocument(event);
|
|
205
203
|
if ((event.role === "user" || event.role === "assistant") && document === "")
|
|
206
204
|
continue;
|
|
@@ -239,9 +237,7 @@ function selectPrepared(prepared, scoped, fits, maxChars) {
|
|
|
239
237
|
break;
|
|
240
238
|
}
|
|
241
239
|
const page = pageData(prepared, start, end, maxChars);
|
|
242
|
-
if (!fits(page))
|
|
243
|
-
|
|
244
|
-
return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows${prepared.multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
|
|
245
|
-
}
|
|
240
|
+
if (!fits(page))
|
|
241
|
+
return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
|
|
246
242
|
return success(page);
|
|
247
243
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
* of every internal module. The notes family is also published as `notesoup/notes`; the Pi
|
|
12
12
|
* extension is loaded through the Pi manifest; dsh uses `notesoup/dsh` and `notesoup/dsh/engine`.
|
|
13
13
|
*/
|
|
14
|
-
export { createNotesStore, noteIdentity, projectKey, slugify, NoteError } from "./notes/index.js";
|
|
15
|
-
export type { NoteEditResult, NoteMatch, NoteMeta, NoteReadResult, NoteRenameResult, NoteRow, NoteSearchRow, NotesIdentity, NotesQuery, NotesStore, NoteWriteResult, Origin, Scope, } from "./notes/index.js";
|
|
14
|
+
export { createNotesStore, effectiveNotePolicy, noteIdentity, projectKey, slugify, NoteError } from "./notes/index.js";
|
|
15
|
+
export type { NoteEditResult, NoteMatch, NoteMeta, NotePolicy, NotePolicyFields, NoteReadResult, NoteRenameResult, NoteRow, NoteSearchRow, NotesIdentity, NotesQuery, NotesStore, NoteWriteResult, Origin, Scope, } from "./notes/index.js";
|
|
16
16
|
export { loadNotesSnapshot, unavailableNotesSnapshot } from "./boot/snapshot.js";
|
|
17
17
|
export type { NotesNamespace, NotesSnapshot } from "./boot/snapshot.js";
|
|
18
18
|
export { renderBootBlock } from "./boot/render.js";
|
|
@@ -25,7 +25,8 @@ export { historyList, 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";
|
|
28
|
-
export type {
|
|
28
|
+
export type { OperationError, Outcome } from "./result.js";
|
|
29
|
+
export type { Operation, Renderer, TextWindow } from "./tools/result.js";
|
|
29
30
|
export { deriveThresholds, remainingBudget } from "./budget/policy.js";
|
|
30
31
|
export type { ResolvedThresholds } from "./budget/policy.js";
|
|
31
32
|
export { selectContinuation, tokenBudgetGuidance, warningPrompt, WARNING_BODY } from "./budget/text.js";
|
package/dist/src/index.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* extension is loaded through the Pi manifest; dsh uses `notesoup/dsh` and `notesoup/dsh/engine`.
|
|
13
13
|
*/
|
|
14
14
|
// Notes: the standalone filesystem library, addressed by an explicit identity.
|
|
15
|
-
export { createNotesStore, noteIdentity, projectKey, slugify, NoteError } from "./notes/index.js";
|
|
15
|
+
export { createNotesStore, effectiveNotePolicy, noteIdentity, projectKey, slugify, NoteError } from "./notes/index.js";
|
|
16
16
|
// Boot: five notebooks captured once, rendered from explicit logical tool names.
|
|
17
17
|
export { loadNotesSnapshot, unavailableNotesSnapshot } from "./boot/snapshot.js";
|
|
18
18
|
export { renderBootBlock } from "./boot/render.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type NoteErrorCode = "not_found" | "already_exists" | "ambiguous_edit" | "no_match" | "invalid_edit" | "nothing_to_do" | "not_crumpled" | "too_large" | "invalid_scope" | "invalid_origin" | "invalid_address" | "invalid_pattern" | "invalid_query" | "invalid_offset" | "invalid_cwd" | "io_error" | "internal_error";
|
|
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;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import type { Scope } from "./paths.js";
|
|
2
|
+
import { type NotePolicyFields } from "./policy.js";
|
|
2
3
|
export type Origin = "user" | "self" | "external";
|
|
3
4
|
/**
|
|
4
5
|
* Harness-owned note metadata. The eight required keys are always written; the four optional
|
|
5
6
|
* sleep-shift keys survive this layer untouched when present. `[key: string]: unknown` carries
|
|
6
7
|
* any frontmatter key this layer does not know, preserved verbatim across rewrites.
|
|
7
8
|
*/
|
|
8
|
-
export type NoteMeta = {
|
|
9
|
+
export type NoteMeta = NotePolicyFields & {
|
|
9
10
|
scope: Scope;
|
|
10
11
|
origin: Origin;
|
|
11
12
|
/** Present only while the note is in the wastebasket; serialized as an ISO timestamp. */
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { validateNotePolicy } from "./policy.js";
|
|
1
2
|
const SCOPES = ["session", "project", "human", "agent", "model"];
|
|
2
3
|
const ORIGINS = ["user", "self", "external"];
|
|
3
4
|
const TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
|
|
4
5
|
/** Emission order, exactly the Design's key list. */
|
|
5
|
-
const KNOWN_KEYS = ["origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
|
|
6
|
+
const KNOWN_KEYS = ["pinned", "budget", "readonly", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
|
|
6
7
|
const pad2 = (value) => String(value).padStart(2, "0");
|
|
7
8
|
/**
|
|
8
9
|
* Format epoch milliseconds as an ISO 8601 string in the host's local time zone with an
|
|
@@ -97,6 +98,7 @@ function parseFrontmatter(raw) {
|
|
|
97
98
|
*/
|
|
98
99
|
export function parseNote(raw, now = Date.now()) {
|
|
99
100
|
const { fields, body } = parseFrontmatter(raw);
|
|
101
|
+
validateNotePolicy(fields);
|
|
100
102
|
const meta = { ...fields };
|
|
101
103
|
// scope is a legacy on-disk field: store callers derive it from the file's notebook and
|
|
102
104
|
// overwrite it after parsing, so an absent or outdated value just falls back.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { createNotesStore, noteIdentity } from "./store.js";
|
|
2
|
+
export { effectiveNotePolicy, type NotePolicy, type NotePolicyFields } from "./policy.js";
|
|
2
3
|
export { NoteError, type NoteErrorCode } from "./errors.js";
|
|
3
4
|
export { projectKey } from "./project-namespace.js";
|
|
4
5
|
export { slugify } from "./paths.js";
|
package/dist/src/notes/index.js
CHANGED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type NotePolicyFields = {
|
|
2
|
+
pinned?: boolean;
|
|
3
|
+
budget?: number;
|
|
4
|
+
readonly?: boolean;
|
|
5
|
+
};
|
|
6
|
+
export type NotePolicy = Required<NotePolicyFields>;
|
|
7
|
+
export declare const DEFAULT_NOTE_BUDGET = 2048;
|
|
8
|
+
export declare const MAX_PINNED_NOTES = 5;
|
|
9
|
+
export declare function validateNotePolicy(fields: NotePolicyFields): void;
|
|
10
|
+
/** Only root default pages are pinned implicitly; an explicit false always wins. */
|
|
11
|
+
export declare function effectiveNotePolicy(fields: NotePolicyFields, path: string): NotePolicy;
|
|
12
|
+
export declare function pinnedPageOrder(path: string): number;
|
|
13
|
+
export declare function noteBudgetWarnings(body: string, policy: NotePolicy): string[];
|
|
14
|
+
export declare function assertNoteUnlocked(fields: NotePolicyFields, unlock?: boolean): void;
|
|
15
|
+
/** Apply only explicit values, leaving absent on-disk defaults absent across moves. */
|
|
16
|
+
export declare function applyNotePolicy(target: NotePolicyFields, fields: NotePolicyFields): void;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { NoteError } from "./errors.js";
|
|
2
|
+
export const DEFAULT_NOTE_BUDGET = 2048;
|
|
3
|
+
export const MAX_PINNED_NOTES = 5;
|
|
4
|
+
/** Defaults and ordering live here; no other layer assigns behavior by page name. */
|
|
5
|
+
const DEFAULT_PINNED_PAGES = ["CHEATSHEET.md", "MAP.md"];
|
|
6
|
+
export function validateNotePolicy(fields) {
|
|
7
|
+
for (const key of ["pinned", "readonly"]) {
|
|
8
|
+
if (fields[key] !== undefined && typeof fields[key] !== "boolean")
|
|
9
|
+
throw new NoteError("invalid_policy", `${key} must be a boolean.`);
|
|
10
|
+
}
|
|
11
|
+
if (fields.budget !== undefined && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
|
|
12
|
+
throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Only root default pages are pinned implicitly; an explicit false always wins. */
|
|
16
|
+
export function effectiveNotePolicy(fields, path) {
|
|
17
|
+
validateNotePolicy(fields);
|
|
18
|
+
return {
|
|
19
|
+
pinned: fields.pinned ?? DEFAULT_PINNED_PAGES.some(page => page === path),
|
|
20
|
+
budget: fields.budget ?? DEFAULT_NOTE_BUDGET,
|
|
21
|
+
readonly: fields.readonly ?? false,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export function pinnedPageOrder(path) {
|
|
25
|
+
const index = DEFAULT_PINNED_PAGES.findIndex(page => page === path);
|
|
26
|
+
return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
|
|
27
|
+
}
|
|
28
|
+
export function noteBudgetWarnings(body, policy) {
|
|
29
|
+
const count = Array.from(body).length;
|
|
30
|
+
return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}; the full body is kept.`] : [];
|
|
31
|
+
}
|
|
32
|
+
export function assertNoteUnlocked(fields, unlock) {
|
|
33
|
+
if (fields.readonly === true && unlock !== false)
|
|
34
|
+
throw new NoteError("readonly", "This note has a soft readonly lock; explicitly set readonly:false to unlock before changing it (or in the same call).");
|
|
35
|
+
}
|
|
36
|
+
/** Apply only explicit values, leaving absent on-disk defaults absent across moves. */
|
|
37
|
+
export function applyNotePolicy(target, fields) {
|
|
38
|
+
validateNotePolicy(fields);
|
|
39
|
+
for (const key of ["pinned", "budget", "readonly"]) {
|
|
40
|
+
if (fields[key] !== undefined)
|
|
41
|
+
Object.assign(target, { [key]: fields[key] });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -2,6 +2,7 @@ import { type NotesIdentity } from "./identity.js";
|
|
|
2
2
|
import { type NoteMeta, type Origin } from "./frontmatter.js";
|
|
3
3
|
import { type Scope } from "./paths.js";
|
|
4
4
|
import { type ProjectReceipt } from "./project-namespace.js";
|
|
5
|
+
import { type NotePolicyFields } from "./policy.js";
|
|
5
6
|
export type { NoteMeta, Origin, Scope };
|
|
6
7
|
export type NoteRow = {
|
|
7
8
|
address: string;
|
|
@@ -21,23 +22,24 @@ export type NoteSearchRow = {
|
|
|
21
22
|
scope: Scope;
|
|
22
23
|
path: string;
|
|
23
24
|
meta: NoteMeta;
|
|
25
|
+
warnings: string[];
|
|
24
26
|
matches: NoteMatch[];
|
|
25
27
|
};
|
|
26
28
|
export type EditOperation = {
|
|
27
29
|
oldText: string;
|
|
28
30
|
newText: string;
|
|
29
31
|
};
|
|
30
|
-
export type WriteOptions = {
|
|
32
|
+
export type WriteOptions = NotePolicyFields & {
|
|
31
33
|
origin?: Origin;
|
|
32
34
|
};
|
|
33
|
-
export type EditOptions = {
|
|
35
|
+
export type EditOptions = NotePolicyFields & {
|
|
34
36
|
origin?: Origin;
|
|
35
37
|
crumpled?: boolean;
|
|
36
38
|
replaceAll?: boolean;
|
|
37
39
|
renameTo?: string;
|
|
38
40
|
};
|
|
39
41
|
/** Omitted/null/empty glob or bare @default selects current notebooks; explicit globs match full addresses.
|
|
40
|
-
*
|
|
42
|
+
* A pattern without `@` or `/` matches filenames at any depth; relative paths with `/` match the current session.
|
|
41
43
|
*/
|
|
42
44
|
export type NotesQuery = {
|
|
43
45
|
glob?: string | null;
|
|
@@ -51,6 +53,7 @@ export type NoteReadResult = {
|
|
|
51
53
|
};
|
|
52
54
|
export type NoteWriteResult = {
|
|
53
55
|
meta: NoteMeta;
|
|
56
|
+
warnings: string[];
|
|
54
57
|
outcome: "created" | "overwrote" | "uncrumpled";
|
|
55
58
|
};
|
|
56
59
|
export type NoteChange = {
|
|
@@ -64,6 +67,7 @@ export type NoteChange = {
|
|
|
64
67
|
};
|
|
65
68
|
export type NoteEditResult = {
|
|
66
69
|
meta: NoteMeta;
|
|
70
|
+
warnings: string[];
|
|
67
71
|
applied: number;
|
|
68
72
|
resolvedScope: Scope;
|
|
69
73
|
change: NoteChange;
|
|
@@ -72,6 +76,7 @@ export type NoteEditResult = {
|
|
|
72
76
|
};
|
|
73
77
|
export type NoteRenameResult = {
|
|
74
78
|
meta: NoteMeta;
|
|
79
|
+
warnings: string[];
|
|
75
80
|
replacedCrumpledTarget: boolean;
|
|
76
81
|
};
|
|
77
82
|
/** A notebook, or one unreadable note inside it, that a status-reporting query could not read. */
|
package/dist/src/notes/store.js
CHANGED
|
@@ -10,6 +10,7 @@ import { MAX_NOTE_BYTES, MAX_NOTE_PATH_BYTES } from "./constants.js";
|
|
|
10
10
|
import { 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, noteBudgetWarnings, validateNotePolicy } from "./policy.js";
|
|
13
14
|
// 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.
|
|
14
15
|
let lastWriteStamp = 0;
|
|
15
16
|
function writeStamp() {
|
|
@@ -40,6 +41,14 @@ function withPathQueue(path, operation) {
|
|
|
40
41
|
});
|
|
41
42
|
return result;
|
|
42
43
|
}
|
|
44
|
+
/** Lock each path once in stable order. Mutations acquire notebook keys before file keys;
|
|
45
|
+
* readers take only file keys; admission scans read atomic files without waiting on readers.
|
|
46
|
+
*/
|
|
47
|
+
function withPathQueues(paths, operation) {
|
|
48
|
+
const keys = [...new Set(paths.map(path => resolve(path)))].sort();
|
|
49
|
+
const lock = (index) => index === keys.length ? operation() : withPathQueue(keys[index], () => lock(index + 1));
|
|
50
|
+
return lock(0);
|
|
51
|
+
}
|
|
43
52
|
function errno(error) {
|
|
44
53
|
return typeof error === "object" && error !== null ? error.code : undefined;
|
|
45
54
|
}
|
|
@@ -126,10 +135,12 @@ async function namespacesForPattern(pattern, identity, status) {
|
|
|
126
135
|
}
|
|
127
136
|
return namespaces;
|
|
128
137
|
}
|
|
129
|
-
/** Relative pattern heads resolve to canonical names
|
|
138
|
+
/** Relative pattern heads resolve to canonical names; slashless bare patterns match filenames at any depth. */
|
|
130
139
|
function normalizePattern(pattern, identity) {
|
|
131
140
|
if (!pattern)
|
|
132
141
|
return pattern;
|
|
142
|
+
if (!pattern.startsWith("@") && !pattern.includes("/"))
|
|
143
|
+
return `**/${pattern}`;
|
|
133
144
|
if (pattern.startsWith("@project/"))
|
|
134
145
|
return `@projects/${identity.projectKey}/${pattern.slice("@project/".length)}`;
|
|
135
146
|
if (pattern.startsWith("@self/"))
|
|
@@ -207,6 +218,8 @@ function assertWritablePath(vpath) {
|
|
|
207
218
|
}
|
|
208
219
|
/** Rounded up, so a note just over the limit never reads as exactly at it. */
|
|
209
220
|
function megabytes(bytes) {
|
|
221
|
+
if (bytes < 1_000_000)
|
|
222
|
+
return `${Math.ceil(bytes / 1_000)} KB`;
|
|
210
223
|
return `${Math.ceil(bytes / 10_000) / 100} MB`;
|
|
211
224
|
}
|
|
212
225
|
function assertSerializedSize(content) {
|
|
@@ -251,8 +264,25 @@ function assertDreamNote(scope, who, identity, raw, address) {
|
|
|
251
264
|
/** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
|
|
252
265
|
export function createNotesStore(input) {
|
|
253
266
|
const identity = snapshotNotesIdentity(input);
|
|
267
|
+
/** Only admission of a new live pin needs a count; existing over-cap notebooks can still be repaired. */
|
|
268
|
+
async function assertPinAdmission(root, path, meta, previous, source) {
|
|
269
|
+
const livePin = (value, name) => value !== undefined && value.crumpledAt === undefined && effectiveNotePolicy(value, name).pinned;
|
|
270
|
+
if (!livePin(meta, path) || livePin(previous, path))
|
|
271
|
+
return;
|
|
272
|
+
if (source?.root === root && livePin(source.meta, source.path))
|
|
273
|
+
return;
|
|
274
|
+
let count = 0;
|
|
275
|
+
for (const name of await walkMarkdown(root)) {
|
|
276
|
+
const raw = await readFileIfExists(join(root, name));
|
|
277
|
+
if (raw !== undefined && livePin(parseNote(raw).meta, name))
|
|
278
|
+
count++;
|
|
279
|
+
}
|
|
280
|
+
if (count >= MAX_PINNED_NOTES)
|
|
281
|
+
throw new NoteError("pin_limit", `This notebook already has ${count} live pinned notes; the limit is ${MAX_PINNED_NOTES}. Unpin or crumple one first. Nothing was saved.`);
|
|
282
|
+
}
|
|
254
283
|
async function write(address, content, options = {}) {
|
|
255
284
|
const stableOptions = { ...options };
|
|
285
|
+
validateNotePolicy(stableOptions);
|
|
256
286
|
const destination = assertAddress(address);
|
|
257
287
|
assertWritablePath(destination.path);
|
|
258
288
|
const scope = destination.scope;
|
|
@@ -261,12 +291,16 @@ export function createNotesStore(input) {
|
|
|
261
291
|
// re-attribute a user-written note to the agent that happened to rewrite it.
|
|
262
292
|
const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
|
|
263
293
|
const path = physicalPath(scope, destination.path, identity, destination.who);
|
|
264
|
-
|
|
294
|
+
const root = scopeDir(scope, identity, destination.who);
|
|
295
|
+
return withPathQueues([root], () => withPathQueue(path, async () => {
|
|
265
296
|
const now = writeStamp();
|
|
266
297
|
const cleanBody = stripLeadingFrontmatter(content);
|
|
267
298
|
const existingRaw = await readFileIfExists(path);
|
|
268
299
|
assertDreamNote(scope, destination.who, identity, existingRaw, address);
|
|
269
300
|
const existing = existingRaw === undefined ? undefined : parseNote(existingRaw, now).meta;
|
|
301
|
+
if (existing)
|
|
302
|
+
assertNoteUnlocked(existing, stableOptions.readonly);
|
|
303
|
+
const previous = existing === undefined ? undefined : { ...existing };
|
|
270
304
|
const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
|
|
271
305
|
const meta = existing ?? {
|
|
272
306
|
scope,
|
|
@@ -278,15 +312,17 @@ export function createNotesStore(input) {
|
|
|
278
312
|
...(scope === "session" ? { project: identity.projectKey } : {}),
|
|
279
313
|
};
|
|
280
314
|
meta.scope = scope;
|
|
315
|
+
applyNotePolicy(meta, stableOptions);
|
|
281
316
|
if (origin !== undefined)
|
|
282
317
|
meta.origin = origin;
|
|
283
318
|
delete meta.crumpledAt;
|
|
284
319
|
meta.updatedAt = now;
|
|
285
320
|
const serialized = serializeNote(meta, cleanBody);
|
|
286
321
|
assertSerializedSize(serialized);
|
|
322
|
+
await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
|
|
287
323
|
await atomicWrite(path, serialized);
|
|
288
|
-
return { meta, outcome };
|
|
289
|
-
});
|
|
324
|
+
return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
|
|
325
|
+
}));
|
|
290
326
|
}
|
|
291
327
|
async function read(address) {
|
|
292
328
|
const destination = assertAddress(address);
|
|
@@ -310,18 +346,21 @@ export function createNotesStore(input) {
|
|
|
310
346
|
async function update(address, edits, options = {}) {
|
|
311
347
|
const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
|
|
312
348
|
const stableOptions = { ...options };
|
|
349
|
+
validateNotePolicy(stableOptions);
|
|
313
350
|
const from = assertAddress(address);
|
|
314
351
|
const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
|
|
315
352
|
assertWritablePath(destination.path);
|
|
316
353
|
const scope = destination.scope;
|
|
317
354
|
assertWritableNamespace(from.scope, from.who, identity);
|
|
318
355
|
assertWritableNamespace(scope, destination.who, identity);
|
|
319
|
-
if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined) {
|
|
320
|
-
throw new NoteError("nothing_to_do", "Nothing to change: provide edits, an origin, a crumpled state, or a new address.");
|
|
356
|
+
if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined && stableOptions.pinned === undefined && stableOptions.budget === undefined && stableOptions.readonly === undefined) {
|
|
357
|
+
throw new NoteError("nothing_to_do", "Nothing to change: provide edits, policy, an origin, a crumpled state, or a new address.");
|
|
321
358
|
}
|
|
322
359
|
const fromPath = physicalPath(from.scope, from.path, identity, from.who);
|
|
323
360
|
const path = physicalPath(scope, destination.path, identity, destination.who);
|
|
324
361
|
const differentPaths = resolve(fromPath) !== resolve(path);
|
|
362
|
+
const fromRoot = scopeDir(from.scope, identity, from.who);
|
|
363
|
+
const root = scopeDir(scope, identity, destination.who);
|
|
325
364
|
const mutate = async () => {
|
|
326
365
|
const raw = await readFileIfExists(fromPath);
|
|
327
366
|
if (raw === undefined)
|
|
@@ -338,7 +377,12 @@ export function createNotesStore(input) {
|
|
|
338
377
|
throw new NoteError("already_exists", `${noteIdentity(identity, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
|
|
339
378
|
}
|
|
340
379
|
const { meta, body } = parseNote(raw);
|
|
380
|
+
assertNoteUnlocked(meta, stableOptions.readonly);
|
|
381
|
+
// Replacing a locked crumpled target also needs an explicit unlock.
|
|
382
|
+
if (moved && targetRaw !== undefined)
|
|
383
|
+
assertNoteUnlocked(parseNote(targetRaw).meta, stableOptions.readonly);
|
|
341
384
|
const beforeMeta = { ...meta };
|
|
385
|
+
applyNotePolicy(meta, stableOptions);
|
|
342
386
|
meta.scope = scope;
|
|
343
387
|
if (from.scope !== "session" && scope === "session")
|
|
344
388
|
meta.project = identity.projectKey;
|
|
@@ -377,11 +421,12 @@ export function createNotesStore(input) {
|
|
|
377
421
|
delete meta.crumpledAt;
|
|
378
422
|
const bodyChanged = body !== next;
|
|
379
423
|
const originChanged = beforeMeta.origin !== meta.origin;
|
|
380
|
-
|
|
424
|
+
const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
|
|
425
|
+
if (bodyChanged || originChanged || policyChanged || moved)
|
|
381
426
|
meta.updatedAt = writeStamp();
|
|
382
427
|
const serialized = serializeNote(meta, next);
|
|
383
428
|
assertSerializedSize(serialized);
|
|
384
|
-
const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
429
|
+
const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
385
430
|
let change;
|
|
386
431
|
// A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
|
|
387
432
|
// whole serialized file, so the frontmatter part stays visible in the diff.
|
|
@@ -393,21 +438,18 @@ export function createNotesStore(input) {
|
|
|
393
438
|
change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
|
|
394
439
|
else
|
|
395
440
|
change = { kind: "none", before: "", after: "" };
|
|
441
|
+
await assertPinAdmission(root, noteFileName(destination.path), meta, moved ? targetRaw === undefined ? undefined : parseNote(targetRaw).meta : beforeMeta, moved ? { root: fromRoot, path: noteFileName(from.path), meta: beforeMeta } : undefined);
|
|
396
442
|
await atomicWrite(sameFile ? sourceReal : path, serialized);
|
|
397
443
|
if (moved)
|
|
398
444
|
await rm(fromPath, { force: true });
|
|
399
|
-
return { meta, applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
|
|
445
|
+
return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== undefined };
|
|
400
446
|
};
|
|
401
|
-
|
|
402
|
-
if (!differentPaths)
|
|
403
|
-
return withPathQueue(path, mutate);
|
|
404
|
-
const [first, second] = [fromPath, path].sort();
|
|
405
|
-
return withPathQueue(first, () => withPathQueue(second, mutate));
|
|
447
|
+
return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
|
|
406
448
|
}
|
|
407
449
|
/** Moving alone shares validation and persistence with a combined edit-and-move. */
|
|
408
450
|
async function rename(fromAddress, toAddress) {
|
|
409
|
-
const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
|
|
410
|
-
return { meta, replacedCrumpledTarget };
|
|
451
|
+
const { meta, warnings, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
|
|
452
|
+
return { meta, warnings, replacedCrumpledTarget };
|
|
411
453
|
}
|
|
412
454
|
async function forget(address) {
|
|
413
455
|
if (identity.dreaming === undefined)
|
|
@@ -415,17 +457,18 @@ export function createNotesStore(input) {
|
|
|
415
457
|
const target = assertAddress(address);
|
|
416
458
|
assertWritableNamespace(target.scope, target.who, identity);
|
|
417
459
|
const path = physicalPath(target.scope, target.path, identity, target.who);
|
|
418
|
-
return withPathQueue(path, async () => {
|
|
460
|
+
return withPathQueues([scopeDir(target.scope, identity, target.who)], () => withPathQueue(path, async () => {
|
|
419
461
|
const raw = await readFileIfExists(path);
|
|
420
462
|
if (raw === undefined)
|
|
421
463
|
throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
|
|
422
464
|
assertDreamNote(target.scope, target.who, identity, raw, address);
|
|
423
465
|
const { meta } = parseNote(raw);
|
|
466
|
+
assertNoteUnlocked(meta);
|
|
424
467
|
if (meta.crumpledAt === undefined)
|
|
425
468
|
throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
|
|
426
469
|
await unlink(path);
|
|
427
470
|
return { ...meta, scope: target.scope };
|
|
428
|
-
});
|
|
471
|
+
}));
|
|
429
472
|
}
|
|
430
473
|
async function* scan(options, status) {
|
|
431
474
|
const glob = assertGlobPattern(options.glob);
|
|
@@ -495,8 +538,9 @@ export function createNotesStore(input) {
|
|
|
495
538
|
const rows = [];
|
|
496
539
|
for await (const note of scan(stableOptions, status)) {
|
|
497
540
|
const { address, path, scope, meta, body } = note;
|
|
541
|
+
const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
|
|
498
542
|
if (stableQueries.length === 0) {
|
|
499
|
-
rows.push({ address, path, scope, meta, matches: [] });
|
|
543
|
+
rows.push({ address, path, scope, meta, warnings, matches: [] });
|
|
500
544
|
continue;
|
|
501
545
|
}
|
|
502
546
|
// Offsets address the note body alone: no frontmatter length is predicted, so an
|
|
@@ -511,7 +555,7 @@ export function createNotesStore(input) {
|
|
|
511
555
|
baseChars += Array.from(line).length + 1;
|
|
512
556
|
}
|
|
513
557
|
if (matches.length > 0)
|
|
514
|
-
rows.push({ address, path, scope, meta, matches });
|
|
558
|
+
rows.push({ address, path, scope, meta, warnings, matches });
|
|
515
559
|
}
|
|
516
560
|
rows.sort((a, b) => a.address.localeCompare(b.address));
|
|
517
561
|
return { rows, status: status ?? { namespacesUnavailable: [] } };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Shared outcomes and bounded refusals, independent of tool transport and output budgets. */
|
|
2
|
+
import { Type, type Static } from "typebox";
|
|
3
|
+
/** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
|
|
4
|
+
export declare const OperationErrorSchema: Type.TObject<{
|
|
5
|
+
code: Type.TString;
|
|
6
|
+
message: Type.TString;
|
|
7
|
+
}>;
|
|
8
|
+
export type OperationError = Static<typeof OperationErrorSchema>;
|
|
9
|
+
/** `data` exists without `error`, never both, never neither. */
|
|
10
|
+
export type Outcome<T> = {
|
|
11
|
+
ok: true;
|
|
12
|
+
data: T;
|
|
13
|
+
} | {
|
|
14
|
+
ok: false;
|
|
15
|
+
error: OperationError;
|
|
16
|
+
};
|
|
17
|
+
export declare function success<T>(data: T): Outcome<T>;
|
|
18
|
+
/** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
|
|
19
|
+
export declare const ERROR_MESSAGE_MAX_CHARS = 2000;
|
|
20
|
+
/** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
|
|
21
|
+
export declare function failure(code: string, message: string): Outcome<never>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Shared outcomes and bounded refusals, independent of tool transport and output budgets. */
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
/** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
|
|
4
|
+
export const OperationErrorSchema = Type.Object({
|
|
5
|
+
code: Type.String(),
|
|
6
|
+
message: Type.String(),
|
|
7
|
+
}, { additionalProperties: false });
|
|
8
|
+
export function success(data) {
|
|
9
|
+
return { ok: true, data };
|
|
10
|
+
}
|
|
11
|
+
/** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
|
|
12
|
+
export const ERROR_MESSAGE_MAX_CHARS = 2000;
|
|
13
|
+
/** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
|
|
14
|
+
export function failure(code, message) {
|
|
15
|
+
const chars = Array.from(message);
|
|
16
|
+
const bounded = chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
|
|
17
|
+
return { ok: false, error: { code, message: bounded } };
|
|
18
|
+
}
|
package/dist/src/text-match.d.ts
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/** Expected search-query refusal, distinct from any other Error an operation may raise. */
|
|
2
|
+
export declare class InvalidQueryError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
/** Missing/empty queries disable filtering; empty list entries are ignored, not OR wildcards. */
|
|
6
|
+
export declare function searchQueries(query: unknown): string[];
|
|
7
|
+
/** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
|
|
8
|
+
export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
|
|
1
9
|
/**
|
|
2
10
|
* Code-point offset of the earliest case-insensitive literal match, or -1 when
|
|
3
11
|
* none occurs. Match against the original text so Unicode casing cannot shift offsets.
|
package/dist/src/text-match.js
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
/** Expected search-query refusal, distinct from any other Error an operation may raise. */
|
|
2
|
+
export class InvalidQueryError extends Error {
|
|
3
|
+
constructor(message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "InvalidQueryError";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
/** Missing/empty queries disable filtering; empty list entries are ignored, not OR wildcards. */
|
|
9
|
+
export function searchQueries(query) {
|
|
10
|
+
const candidates = query === undefined ? [] : typeof query === "string" ? [query] : query;
|
|
11
|
+
if (!Array.isArray(candidates))
|
|
12
|
+
throw new InvalidQueryError("`query` must be a string or a list of strings.");
|
|
13
|
+
if (!candidates.every((candidate) => typeof candidate === "string"))
|
|
14
|
+
throw new InvalidQueryError("Every item in the `query` list must be a string.");
|
|
15
|
+
return candidates.filter((candidate) => candidate !== "");
|
|
16
|
+
}
|
|
17
|
+
/** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
|
|
18
|
+
export function prefixFit(text, fits) {
|
|
19
|
+
if (fits(text))
|
|
20
|
+
return text;
|
|
21
|
+
const chars = Array.from(text);
|
|
22
|
+
// Serialized size is non-decreasing in the kept count, so the largest fitting prefix is
|
|
23
|
+
// found by a monotone binary search instead of a quadratic shrink loop.
|
|
24
|
+
let low = 0;
|
|
25
|
+
let high = chars.length;
|
|
26
|
+
while (low < high) {
|
|
27
|
+
const mid = Math.ceil((low + high) / 2);
|
|
28
|
+
if (fits(chars.slice(0, mid).join("")))
|
|
29
|
+
low = mid;
|
|
30
|
+
else
|
|
31
|
+
high = mid - 1;
|
|
32
|
+
}
|
|
33
|
+
return chars.slice(0, low).join("");
|
|
34
|
+
}
|
|
1
35
|
/**
|
|
2
36
|
* Code-point offset of the earliest case-insensitive literal match, or -1 when
|
|
3
37
|
* none occurs. Match against the original text so Unicode casing cannot shift offsets.
|