notesoup 0.57.4 → 0.58.1

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.
Files changed (129) hide show
  1. package/README.md +15 -1
  2. package/dist/plugins/claude/src/helper.js +2 -11
  3. package/dist/plugins/claude/src/thresholds.js +23 -43
  4. package/dist/plugins/codex/src/mcp.js +3 -11
  5. package/dist/plugins/codex/src/state.d.ts +1 -1
  6. package/dist/plugins/codex/src/state.js +1 -1
  7. package/dist/plugins/dsh/tools.js +1 -1
  8. package/dist/plugins/pi/boot.d.ts +1 -1
  9. package/dist/plugins/pi/boot.js +2 -3
  10. package/dist/plugins/pi/budget.d.ts +1 -1
  11. package/dist/plugins/pi/budget.js +1 -1
  12. package/dist/plugins/pi/render.d.ts +1 -1
  13. package/dist/plugins/pi/render.js +20 -11
  14. package/dist/plugins/pi/runtime.js +6 -2
  15. package/dist/plugins/pi/tool-result.d.ts +2 -1
  16. package/dist/plugins/pi/window.js +24 -1
  17. package/dist/src/boot/render.d.ts +3 -4
  18. package/dist/src/boot/render.js +23 -21
  19. package/dist/src/boot/text.d.ts +2 -5
  20. package/dist/src/boot/text.js +12 -9
  21. package/dist/src/budget/text.d.ts +1 -1
  22. package/dist/src/budget/text.js +1 -1
  23. package/dist/src/history/corpus.d.ts +1 -1
  24. package/dist/src/history/corpus.js +1 -1
  25. package/dist/src/history/history.d.ts +2 -2
  26. package/dist/src/history/history.js +5 -8
  27. package/dist/src/history/query.d.ts +11 -3
  28. package/dist/src/history/query.js +7 -11
  29. package/dist/src/index.d.ts +4 -3
  30. package/dist/src/index.js +1 -1
  31. package/dist/src/notes/constants.d.ts +1 -1
  32. package/dist/src/notes/constants.js +1 -1
  33. package/dist/src/notes/errors.d.ts +1 -1
  34. package/dist/src/notes/frontmatter.d.ts +2 -1
  35. package/dist/src/notes/frontmatter.js +3 -1
  36. package/dist/src/notes/index.d.ts +1 -0
  37. package/dist/src/notes/index.js +1 -0
  38. package/dist/src/notes/policy.d.ts +16 -0
  39. package/dist/src/notes/policy.js +43 -0
  40. package/dist/src/notes/store.d.ts +7 -2
  41. package/dist/src/notes/store.js +61 -19
  42. package/dist/src/result.d.ts +21 -0
  43. package/dist/src/result.js +18 -0
  44. package/dist/src/text-match.d.ts +8 -0
  45. package/dist/src/text-match.js +34 -0
  46. package/dist/src/tools/dream.d.ts +9 -1
  47. package/dist/src/tools/dream.js +2 -1
  48. package/dist/src/tools/history.js +14 -5
  49. package/dist/src/tools/notes.d.ts +75 -13
  50. package/dist/src/tools/notes.js +58 -19
  51. package/dist/src/tools/output.d.ts +1 -3
  52. package/dist/src/tools/output.js +1 -19
  53. package/dist/src/tools/result.d.ts +2 -20
  54. package/dist/src/tools/result.js +4 -18
  55. package/dist/src/tools/schema.d.ts +3 -7
  56. package/dist/src/tools/schema.js +10 -16
  57. package/dist/test/agent-loop.test.js +78 -6
  58. package/dist/test/boot.integration.test.js +30 -3
  59. package/dist/test/claude-mod.test.js +101 -16
  60. package/dist/test/codex-history.test.js +2 -2
  61. package/dist/test/codex-plugin.test.js +2 -0
  62. package/dist/test/dependencies.test.js +38 -3
  63. package/dist/test/dsh.test.js +1 -1
  64. package/dist/test/helpers/dependency-graph.js +12 -6
  65. package/dist/test/helpers/extension.d.ts +2 -1
  66. package/dist/test/history.integration.test.js +47 -1
  67. package/dist/test/host-neutral.test.js +4 -3
  68. package/dist/test/model-facing-text.test.js +20 -16
  69. package/dist/test/note-policy.test.d.ts +1 -0
  70. package/dist/test/note-policy.test.js +227 -0
  71. package/dist/test/notes.integration.test.js +9 -9
  72. package/dist/test/notes.test.js +4 -4
  73. package/dist/test/pi-render.test.js +28 -1
  74. package/dist/test/project-namespace.test.js +1 -1
  75. package/docs/architecture.md +10 -7
  76. package/docs/claude-code-mod.md +3 -3
  77. package/docs/dsh.md +1 -1
  78. package/docs/notes-library.md +19 -6
  79. package/docs/reset-lifecycle.md +2 -2
  80. package/docs/tool-results.md +3 -1
  81. package/package.json +12 -12
  82. package/playbook.md +1 -1
  83. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  84. package/plugins/claude/dist/claude/helper.js +535 -439
  85. package/plugins/claude/hooks/register.ts +26 -36
  86. package/plugins/claude/playbook.md +1 -1
  87. package/plugins/claude/skills/dream/SKILL.md +1 -1
  88. package/plugins/claude/skills/memory/SKILL.md +1 -1
  89. package/plugins/claude/src/helper.ts +2 -11
  90. package/plugins/claude/src/thresholds.ts +22 -42
  91. package/plugins/codex/dist/codex/notesoup.js +519 -403
  92. package/plugins/codex/src/mcp.ts +5 -12
  93. package/plugins/codex/src/state.ts +1 -1
  94. package/plugins/dsh/tools.ts +2 -1
  95. package/plugins/pi/boot.ts +3 -4
  96. package/plugins/pi/budget.ts +1 -1
  97. package/plugins/pi/render.ts +20 -8
  98. package/plugins/pi/runtime.ts +6 -2
  99. package/plugins/pi/tool-result.ts +2 -1
  100. package/plugins/pi/window.ts +20 -1
  101. package/skills/dream/SKILL.md +1 -1
  102. package/skills/memory/SKILL.md +1 -1
  103. package/src/boot/render.ts +24 -21
  104. package/src/boot/text.ts +12 -9
  105. package/src/budget/text.ts +1 -1
  106. package/src/history/corpus.ts +1 -1
  107. package/src/history/history.ts +5 -6
  108. package/src/history/query.ts +11 -14
  109. package/src/index.ts +5 -2
  110. package/src/notes/constants.ts +1 -1
  111. package/src/notes/errors.ts +1 -1
  112. package/src/notes/frontmatter.ts +4 -2
  113. package/src/notes/index.ts +1 -0
  114. package/src/notes/policy.ts +49 -0
  115. package/src/notes/store.ts +63 -24
  116. package/src/result.ts +26 -0
  117. package/src/text-match.ts +32 -0
  118. package/src/tools/dream.ts +2 -1
  119. package/src/tools/history.ts +15 -6
  120. package/src/tools/notes.ts +60 -20
  121. package/src/tools/output.ts +1 -17
  122. package/src/tools/result.ts +4 -26
  123. package/src/tools/schema.ts +11 -17
  124. package/dist/plugins/codex/src/history.d.ts +0 -3
  125. package/dist/plugins/codex/src/history.js +0 -2
  126. package/dist/plugins/codex/src/transcript.d.ts +0 -3
  127. package/dist/plugins/codex/src/transcript.js +0 -2
  128. package/plugins/codex/src/history.ts +0 -3
  129. package/plugins/codex/src/transcript.ts +0 -3
@@ -1,5 +1,5 @@
1
1
  /** A read-only history corpus: identity/discovery is separate from loading a projection. */
2
- import { type Outcome } from "../tools/result.js";
2
+ import { type Outcome } from "../result.js";
3
3
  import type { HistoryEvent, HistoryProjection } from "./history.js";
4
4
  export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
5
5
  export type HistorySessionData = {
@@ -1,5 +1,5 @@
1
1
  /** A read-only history corpus: identity/discovery is separate from loading a projection. */
2
- import { failure, success } from "../tools/result.js";
2
+ import { failure, success } from "../result.js";
3
3
  import { sessionRepresentative } from "./query.js";
4
4
  const HARNESSES = new Set(["pi", "claude", "codex", "dsh"]);
5
5
  export function sessionIdentity(session) {
@@ -154,5 +154,5 @@ export declare function allItems(projection: HistoryProjection): HistoryEvent[];
154
154
  * time or a time that cannot be read.
155
155
  */
156
156
  export declare function inSelection(event: HistoryEvent, params: HistoryFilter): boolean;
157
- /** Without roles or query a call shows the conversation; either one shows the requested events. */
158
- export declare function filteredItems(projection: HistoryProjection, params: HistoryFilter, conversation: boolean): HistoryEvent[];
157
+ /** Ordered events inside the requested seq/time range and optional roles, before folding. */
158
+ export declare function filteredItems(projection: HistoryProjection, params: HistoryFilter): HistoryEvent[];
@@ -196,12 +196,9 @@ export function inSelection(event, params) {
196
196
  const at = Date.parse(event.createdAt);
197
197
  return !Number.isNaN(at) && (params.sinceMs === undefined || at >= params.sinceMs) && (params.untilMs === undefined || at < params.untilMs);
198
198
  }
199
- /** Without roles or query a call shows the conversation; either one shows the requested events. */
200
- export function filteredItems(projection, params, conversation) {
201
- let items = allItems(projection).filter((item) => inSelection(item, params));
202
- if (params.roles)
203
- items = items.filter((item) => params.roles.includes(item.role));
204
- if (!params.roles && conversation)
205
- items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
206
- return items.sort((a, b) => a.seq - b.seq);
199
+ /** Ordered events inside the requested seq/time range and optional roles, before folding. */
200
+ export function filteredItems(projection, params) {
201
+ return allItems(projection)
202
+ .filter((item) => inSelection(item, params) && (!params.roles || params.roles.includes(item.role)))
203
+ .sort((a, b) => a.seq - b.seq);
207
204
  }
@@ -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 "../tools/result.js";
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
- export declare function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage>;
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): Outcome<HistoryPage>;
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 "../tools/result.js";
4
- import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
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, false)) {
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, false).filter((event) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "");
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, false)) {
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
- const narrow = prepared.multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
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
  }
@@ -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 { Operation, OperationError, Outcome, Renderer, TextWindow } from "./tools/result.js";
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,3 +1,3 @@
1
- export declare const MAX_NOTE_BYTES = 1000000;
1
+ export declare const MAX_NOTE_BYTES = 512000;
2
2
  /** Write-time cap on a virtual note path. Reads and legacy replay stay uncapped. */
3
3
  export declare const MAX_NOTE_PATH_BYTES = 512;
@@ -1,3 +1,3 @@
1
- export const MAX_NOTE_BYTES = 1_000_000;
1
+ export const MAX_NOTE_BYTES = 512_000;
2
2
  /** Write-time cap on a virtual note path. Reads and legacy replay stay uncapped. */
3
3
  export const MAX_NOTE_PATH_BYTES = 512;
@@ -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";
@@ -1,4 +1,5 @@
1
1
  export { createNotesStore, noteIdentity } from "./store.js";
2
+ export { effectiveNotePolicy } from "./policy.js";
2
3
  export { NoteError } from "./errors.js";
3
4
  export { projectKey } from "./project-namespace.js";
4
5
  export { slugify } from "./paths.js";
@@ -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,16 +22,17 @@ 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;
@@ -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. */
@@ -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
  }
@@ -209,6 +218,8 @@ function assertWritablePath(vpath) {
209
218
  }
210
219
  /** Rounded up, so a note just over the limit never reads as exactly at it. */
211
220
  function megabytes(bytes) {
221
+ if (bytes < 1_000_000)
222
+ return `${Math.ceil(bytes / 1_000)} KB`;
212
223
  return `${Math.ceil(bytes / 10_000) / 100} MB`;
213
224
  }
214
225
  function assertSerializedSize(content) {
@@ -253,8 +264,25 @@ function assertDreamNote(scope, who, identity, raw, address) {
253
264
  /** Create a store over one validated, immutable snapshot of the supplied explicit identity. */
254
265
  export function createNotesStore(input) {
255
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
+ }
256
283
  async function write(address, content, options = {}) {
257
284
  const stableOptions = { ...options };
285
+ validateNotePolicy(stableOptions);
258
286
  const destination = assertAddress(address);
259
287
  assertWritablePath(destination.path);
260
288
  const scope = destination.scope;
@@ -263,12 +291,16 @@ export function createNotesStore(input) {
263
291
  // re-attribute a user-written note to the agent that happened to rewrite it.
264
292
  const origin = stableOptions.origin === undefined ? undefined : assertOrigin(stableOptions.origin);
265
293
  const path = physicalPath(scope, destination.path, identity, destination.who);
266
- return withPathQueue(path, async () => {
294
+ const root = scopeDir(scope, identity, destination.who);
295
+ return withPathQueues([root], () => withPathQueue(path, async () => {
267
296
  const now = writeStamp();
268
297
  const cleanBody = stripLeadingFrontmatter(content);
269
298
  const existingRaw = await readFileIfExists(path);
270
299
  assertDreamNote(scope, destination.who, identity, existingRaw, address);
271
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 };
272
304
  const outcome = existing === undefined ? "created" : existing.crumpledAt === undefined ? "overwrote" : "uncrumpled";
273
305
  const meta = existing ?? {
274
306
  scope,
@@ -280,15 +312,17 @@ export function createNotesStore(input) {
280
312
  ...(scope === "session" ? { project: identity.projectKey } : {}),
281
313
  };
282
314
  meta.scope = scope;
315
+ applyNotePolicy(meta, stableOptions);
283
316
  if (origin !== undefined)
284
317
  meta.origin = origin;
285
318
  delete meta.crumpledAt;
286
319
  meta.updatedAt = now;
287
320
  const serialized = serializeNote(meta, cleanBody);
288
321
  assertSerializedSize(serialized);
322
+ await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
289
323
  await atomicWrite(path, serialized);
290
- return { meta, outcome };
291
- });
324
+ return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
325
+ }));
292
326
  }
293
327
  async function read(address) {
294
328
  const destination = assertAddress(address);
@@ -312,18 +346,21 @@ export function createNotesStore(input) {
312
346
  async function update(address, edits, options = {}) {
313
347
  const operations = edits === undefined ? [] : edits.map((operation) => ({ ...operation }));
314
348
  const stableOptions = { ...options };
349
+ validateNotePolicy(stableOptions);
315
350
  const from = assertAddress(address);
316
351
  const destination = stableOptions.renameTo === undefined ? from : assertAddress(stableOptions.renameTo);
317
352
  assertWritablePath(destination.path);
318
353
  const scope = destination.scope;
319
354
  assertWritableNamespace(from.scope, from.who, identity);
320
355
  assertWritableNamespace(scope, destination.who, identity);
321
- if (operations.length === 0 && stableOptions.origin === undefined && stableOptions.crumpled === undefined && stableOptions.renameTo === undefined) {
322
- 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.");
323
358
  }
324
359
  const fromPath = physicalPath(from.scope, from.path, identity, from.who);
325
360
  const path = physicalPath(scope, destination.path, identity, destination.who);
326
361
  const differentPaths = resolve(fromPath) !== resolve(path);
362
+ const fromRoot = scopeDir(from.scope, identity, from.who);
363
+ const root = scopeDir(scope, identity, destination.who);
327
364
  const mutate = async () => {
328
365
  const raw = await readFileIfExists(fromPath);
329
366
  if (raw === undefined)
@@ -340,7 +377,12 @@ export function createNotesStore(input) {
340
377
  throw new NoteError("already_exists", `${noteIdentity(identity, stableOptions.renameTo).address} already holds a note; crumple it first or pick another address.`);
341
378
  }
342
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);
343
384
  const beforeMeta = { ...meta };
385
+ applyNotePolicy(meta, stableOptions);
344
386
  meta.scope = scope;
345
387
  if (from.scope !== "session" && scope === "session")
346
388
  meta.project = identity.projectKey;
@@ -379,11 +421,12 @@ export function createNotesStore(input) {
379
421
  delete meta.crumpledAt;
380
422
  const bodyChanged = body !== next;
381
423
  const originChanged = beforeMeta.origin !== meta.origin;
382
- if (bodyChanged || originChanged || moved)
424
+ const policyChanged = beforeMeta.pinned !== meta.pinned || beforeMeta.budget !== meta.budget || beforeMeta.readonly !== meta.readonly;
425
+ if (bodyChanged || originChanged || policyChanged || moved)
383
426
  meta.updatedAt = writeStamp();
384
427
  const serialized = serializeNote(meta, next);
385
428
  assertSerializedSize(serialized);
386
- const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
429
+ const metadataChanged = originChanged || policyChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
387
430
  let change;
388
431
  // A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
389
432
  // whole serialized file, so the frontmatter part stays visible in the diff.
@@ -395,21 +438,18 @@ export function createNotesStore(input) {
395
438
  change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
396
439
  else
397
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);
398
442
  await atomicWrite(sameFile ? sourceReal : path, serialized);
399
443
  if (moved)
400
444
  await rm(fromPath, { force: true });
401
- 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 };
402
446
  };
403
- // Exact aliases share one queue; other spellings lock both paths in stable order.
404
- if (!differentPaths)
405
- return withPathQueue(path, mutate);
406
- const [first, second] = [fromPath, path].sort();
407
- return withPathQueue(first, () => withPathQueue(second, mutate));
447
+ return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
408
448
  }
409
449
  /** Moving alone shares validation and persistence with a combined edit-and-move. */
410
450
  async function rename(fromAddress, toAddress) {
411
- const { meta, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
412
- return { meta, replacedCrumpledTarget };
451
+ const { meta, warnings, replacedCrumpledTarget } = await update(fromAddress, undefined, { renameTo: toAddress });
452
+ return { meta, warnings, replacedCrumpledTarget };
413
453
  }
414
454
  async function forget(address) {
415
455
  if (identity.dreaming === undefined)
@@ -417,17 +457,18 @@ export function createNotesStore(input) {
417
457
  const target = assertAddress(address);
418
458
  assertWritableNamespace(target.scope, target.who, identity);
419
459
  const path = physicalPath(target.scope, target.path, identity, target.who);
420
- return withPathQueue(path, async () => {
460
+ return withPathQueues([scopeDir(target.scope, identity, target.who)], () => withPathQueue(path, async () => {
421
461
  const raw = await readFileIfExists(path);
422
462
  if (raw === undefined)
423
463
  throw new NoteError("not_found", `No note at ${noteIdentity(identity, address).address}.`);
424
464
  assertDreamNote(target.scope, target.who, identity, raw, address);
425
465
  const { meta } = parseNote(raw);
466
+ assertNoteUnlocked(meta);
426
467
  if (meta.crumpledAt === undefined)
427
468
  throw new NoteError("not_crumpled", `${noteIdentity(identity, address).address} isn't crumpled; crumple it before deleting.`);
428
469
  await unlink(path);
429
470
  return { ...meta, scope: target.scope };
430
- });
471
+ }));
431
472
  }
432
473
  async function* scan(options, status) {
433
474
  const glob = assertGlobPattern(options.glob);
@@ -497,8 +538,9 @@ export function createNotesStore(input) {
497
538
  const rows = [];
498
539
  for await (const note of scan(stableOptions, status)) {
499
540
  const { address, path, scope, meta, body } = note;
541
+ const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
500
542
  if (stableQueries.length === 0) {
501
- rows.push({ address, path, scope, meta, matches: [] });
543
+ rows.push({ address, path, scope, meta, warnings, matches: [] });
502
544
  continue;
503
545
  }
504
546
  // Offsets address the note body alone: no frontmatter length is predicted, so an
@@ -513,7 +555,7 @@ export function createNotesStore(input) {
513
555
  baseChars += Array.from(line).length + 1;
514
556
  }
515
557
  if (matches.length > 0)
516
- rows.push({ address, path, scope, meta, matches });
558
+ rows.push({ address, path, scope, meta, warnings, matches });
517
559
  }
518
560
  rows.sort((a, b) => a.address.localeCompare(b.address));
519
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
+ }
@@ -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.