notesoup 0.42.0 → 0.44.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.
Files changed (126) hide show
  1. package/dist/src/boot/render.js +11 -20
  2. package/dist/src/boot/snapshot.d.ts +2 -0
  3. package/dist/src/boot/snapshot.js +4 -5
  4. package/dist/src/boot/text.js +4 -2
  5. package/dist/src/budget/parse.d.ts +14 -0
  6. package/dist/src/budget/parse.js +36 -0
  7. package/dist/src/budget/policy.js +2 -7
  8. package/dist/src/budget/text.d.ts +2 -0
  9. package/dist/src/budget/text.js +2 -0
  10. package/dist/src/claude/helper.js +3 -4
  11. package/dist/src/claude/thresholds.js +45 -66
  12. package/dist/src/dream/lock.js +6 -13
  13. package/dist/src/dream/report.js +5 -15
  14. package/dist/src/history/history.js +4 -2
  15. package/dist/src/history/query.js +10 -22
  16. package/dist/src/notes/address.d.ts +2 -3
  17. package/dist/src/notes/address.js +10 -22
  18. package/dist/src/notes/errors.d.ts +2 -0
  19. package/dist/src/notes/errors.js +5 -0
  20. package/dist/src/notes/frontmatter.js +16 -2
  21. package/dist/src/notes/identity.js +2 -4
  22. package/dist/src/notes/paths.d.ts +7 -2
  23. package/dist/src/notes/paths.js +18 -60
  24. package/dist/src/notes/project-home.d.ts +25 -0
  25. package/dist/src/notes/project-home.js +231 -0
  26. package/dist/src/notes/store.d.ts +4 -2
  27. package/dist/src/notes/store.js +52 -45
  28. package/dist/src/pi/boot.js +17 -9
  29. package/dist/src/pi/budget.d.ts +3 -3
  30. package/dist/src/pi/budget.js +11 -11
  31. package/dist/src/pi/dream/cli.js +43 -11
  32. package/dist/src/pi/estimate.d.ts +1 -5
  33. package/dist/src/pi/estimate.js +4 -4
  34. package/dist/src/pi/history.js +1 -4
  35. package/dist/src/pi/notes/adapter.d.ts +1 -1
  36. package/dist/src/pi/notes/adapter.js +3 -3
  37. package/dist/src/pi/reset/artifacts.d.ts +0 -2
  38. package/dist/src/pi/reset/artifacts.js +4 -4
  39. package/dist/src/pi/reset/committed.js +2 -2
  40. package/dist/src/pi/runtime.js +8 -5
  41. package/dist/src/pi/thresholds.js +5 -9
  42. package/dist/src/pi/tool-result.d.ts +1 -4
  43. package/dist/src/pi/tool-result.js +1 -1
  44. package/dist/src/pi/window.d.ts +5 -0
  45. package/dist/src/pi/window.js +7 -0
  46. package/dist/src/settings.d.ts +2 -0
  47. package/dist/src/settings.js +4 -3
  48. package/dist/src/tools/history.js +4 -7
  49. package/dist/src/tools/notes.d.ts +47 -21
  50. package/dist/src/tools/notes.js +20 -19
  51. package/dist/src/tools/output.d.ts +0 -3
  52. package/dist/src/tools/output.js +1 -9
  53. package/dist/src/tools/result.d.ts +1 -0
  54. package/dist/src/tools/result.js +14 -20
  55. package/dist/src/tools/schema.d.ts +0 -1
  56. package/dist/src/tools/schema.js +0 -1
  57. package/dist/test/agent-loop.test.js +1 -2
  58. package/dist/test/boot.integration.test.js +1 -1
  59. package/dist/test/claude-mod.test.js +253 -10
  60. package/dist/test/claude-validation.test.d.ts +1 -0
  61. package/dist/test/claude-validation.test.js +73 -0
  62. package/dist/test/dream-skill.test.js +2 -4
  63. package/dist/test/dream.test.js +14 -0
  64. package/dist/test/helpers/extension.js +1 -1
  65. package/dist/test/history.integration.test.js +2 -1
  66. package/dist/test/host-neutral.test.js +15 -0
  67. package/dist/test/notes-library.test.js +30 -1
  68. package/dist/test/notes.integration.test.js +7 -7
  69. package/dist/test/notes.test.js +36 -14
  70. package/dist/test/project-home.test.d.ts +1 -0
  71. package/dist/test/project-home.test.js +134 -0
  72. package/dist/test/reset-lifecycle.test.js +1 -1
  73. package/docs/claude-code-mod.md +5 -3
  74. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  75. package/mods/notesoup/dist/claude/helper.js +359 -218
  76. package/mods/notesoup/hooks/register.ts +158 -67
  77. package/mods/notesoup/playbook.md +1 -1
  78. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  79. package/mods/notesoup/skills/memory/SKILL.md +62 -0
  80. package/package.json +5 -3
  81. package/playbook.md +1 -1
  82. package/skills/dream/SKILL.md +1 -1
  83. package/skills/memory/SKILL.md +2 -1
  84. package/src/boot/render.ts +11 -21
  85. package/src/boot/snapshot.ts +5 -5
  86. package/src/boot/text.ts +4 -2
  87. package/src/budget/parse.ts +39 -0
  88. package/src/budget/policy.ts +2 -6
  89. package/src/budget/text.ts +3 -0
  90. package/src/claude/helper.ts +4 -4
  91. package/src/claude/thresholds.ts +45 -62
  92. package/src/dream/lock.ts +3 -9
  93. package/src/dream/report.ts +5 -10
  94. package/src/history/history.ts +4 -2
  95. package/src/history/query.ts +10 -23
  96. package/src/notes/address.ts +9 -21
  97. package/src/notes/errors.ts +6 -0
  98. package/src/notes/frontmatter.ts +12 -2
  99. package/src/notes/identity.ts +1 -3
  100. package/src/notes/paths.ts +14 -52
  101. package/src/notes/project-home.ts +197 -0
  102. package/src/notes/store.ts +46 -45
  103. package/src/pi/boot.ts +15 -17
  104. package/src/pi/budget.ts +10 -11
  105. package/src/pi/dream/cli.ts +35 -10
  106. package/src/pi/estimate.ts +4 -4
  107. package/src/pi/history.ts +1 -5
  108. package/src/pi/notes/adapter.ts +3 -3
  109. package/src/pi/reset/artifacts.ts +4 -4
  110. package/src/pi/reset/committed.ts +2 -2
  111. package/src/pi/runtime.ts +7 -6
  112. package/src/pi/thresholds.ts +5 -11
  113. package/src/pi/tool-result.ts +1 -1
  114. package/src/pi/window.ts +8 -0
  115. package/src/settings.ts +4 -3
  116. package/src/tools/history.ts +4 -8
  117. package/src/tools/notes.ts +22 -25
  118. package/src/tools/output.ts +1 -12
  119. package/src/tools/result.ts +14 -19
  120. package/src/tools/schema.ts +0 -1
  121. package/dist/src/dream/playbook.d.ts +0 -1
  122. package/dist/src/dream/playbook.js +0 -2
  123. package/dist/src/pi/reset/text.d.ts +0 -4
  124. package/dist/src/pi/reset/text.js +0 -7
  125. package/src/dream/playbook.ts +0 -3
  126. package/src/pi/reset/text.ts +0 -9
@@ -1,6 +1,6 @@
1
1
  import { deriveThresholds } from "../budget/policy.js";
2
2
  import { SettingsManager } from "@earendil-works/pi-coding-agent";
3
- import { DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
3
+ import { DEFAULT_RESERVE_TOKENS } from "../budget/constants.js";
4
4
  import { mergeNotesoupSettings } from "../settings.js";
5
5
  import { errorMessage } from "../error-message.js";
6
6
  function readThresholdSettingsFromManager(ctx, settingsManager) {
@@ -16,17 +16,13 @@ function readThresholdSettingsFromManager(ctx, settingsManager) {
16
16
  */
17
17
  export function readThresholdSettings(ctx, settingsManager) {
18
18
  try {
19
- if (settingsManager)
20
- return readThresholdSettingsFromManager(ctx, settingsManager);
21
- return readThresholdSettingsFromManager(ctx, SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }));
19
+ const manager = settingsManager ?? SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
20
+ return readThresholdSettingsFromManager(ctx, manager);
22
21
  }
23
22
  catch (error) {
24
23
  return {
25
- thresholds: {
26
- reminder: DEFAULT_RESERVE_TOKENS + DEFAULT_REMINDER_MARGIN_TOKENS,
27
- reserve: DEFAULT_RESERVE_TOKENS,
28
- warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
29
- },
24
+ // The same derivation over Pi's default reserve, so the fallback cannot drift from it.
25
+ thresholds: deriveThresholds(DEFAULT_RESERVE_TOKENS, {}).thresholds,
30
26
  automatic: true,
31
27
  warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
32
28
  };
@@ -1,10 +1,7 @@
1
1
  /** Pi transport for host-neutral operations. */
2
2
  import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
3
  import type { Static, TSchema } from "typebox";
5
- import { type Operation, type Outcome, type Renderer } from "../tools/result.js";
6
- /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
7
- export declare function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined>;
4
+ import { type Operation, type Outcome } from "../tools/result.js";
8
5
  export type ToolNamespace = {
9
6
  name: string;
10
7
  description: string;
@@ -2,7 +2,7 @@
2
2
  import { defineTool } from "@earendil-works/pi-coding-agent";
3
3
  import { wireResult } from "../tools/result.js";
4
4
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
5
- export function piOperationResult(render, outcome) {
5
+ function piOperationResult(render, outcome) {
6
6
  return {
7
7
  content: [{ type: "text", text: render(outcome) }],
8
8
  structuredContent: wireResult(outcome),
@@ -21,6 +21,11 @@ export declare function hasWindowMessage(ctx: SessionReader, customType: string)
21
21
  export declare function currentWindowId(ctx: SessionReader): string;
22
22
  /** The durable window active just before the marker: the last earlier marker, else the root window. */
23
23
  export declare function previousWindowId(ctx: SessionReader, markerId: string): string;
24
+ /**
25
+ * An entry that cannot appear between a reset marker and its boot/continuation without
26
+ * breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
27
+ */
28
+ export declare function isForeignResetTailEntry(entry: SessionEntry): boolean;
24
29
  /** Match a provider-facing boot message, optionally by window identity. */
25
30
  export declare function isWindowBoot(message: AgentMessage, windowId?: string): boolean;
26
31
  /** Match a persisted boot entry by raw identity, even when a later edit hides it from projection. */
@@ -64,6 +64,13 @@ function hasWindowId(details, windowId) {
64
64
  typeof details.windowId === "string" &&
65
65
  details.windowId === windowId;
66
66
  }
67
+ /**
68
+ * An entry that cannot appear between a reset marker and its boot/continuation without
69
+ * breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
70
+ */
71
+ export function isForeignResetTailEntry(entry) {
72
+ return isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary";
73
+ }
67
74
  /** Match a provider-facing boot message, optionally by window identity. */
68
75
  export function isWindowBoot(message, windowId) {
69
76
  return message.role === "custom" && message.customType === BOOT_TYPE && (windowId === undefined || hasWindowId(message.details, windowId));
@@ -13,5 +13,7 @@ export type NotesoupSettings = {
13
13
  warningRunwayTokens?: unknown;
14
14
  dreamer?: unknown;
15
15
  };
16
+ /** A plain settings object; arrays and null are not one. */
17
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
16
18
  /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
17
19
  export declare function mergeNotesoupSettings(globalSettings: unknown, projectSettings: unknown): NotesoupSettings;
@@ -1,15 +1,16 @@
1
1
  export const NOTESOUP_SETTINGS_KEY = "notesoup";
2
2
  /** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
3
3
  export const NOTESOUP_DREAMER_KEY = "dreamer";
4
- function isSettingsObject(value) {
4
+ /** A plain settings object; arrays and null are not one. */
5
+ export function isPlainObject(value) {
5
6
  return typeof value === "object" && value !== null && !Array.isArray(value);
6
7
  }
7
8
  /** Read the raw "notesoup" object from one parsed settings scope. */
8
9
  function notesoupSettings(settings) {
9
- if (!isSettingsObject(settings))
10
+ if (!isPlainObject(settings))
10
11
  return {};
11
12
  const value = settings[NOTESOUP_SETTINGS_KEY];
12
- return isSettingsObject(value) ? value : {};
13
+ return isPlainObject(value) ? value : {};
13
14
  }
14
15
  /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
15
16
  export function mergeNotesoupSettings(globalSettings, projectSettings) {
@@ -1,6 +1,6 @@
1
1
  /** Host-neutral history operations: one bounded payload for text and structured results. */
2
2
  import { Type } from "typebox";
3
- import { HISTORY_PREVIEW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
3
+ import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
4
4
  import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
5
5
  import { historyRoles, searchQuery } from "./schema.js";
6
6
  import { HistoryPageSchema, selectPage } from "../history/query.js";
@@ -48,9 +48,6 @@ function renderPageItem(item) {
48
48
  lines.push(item.content);
49
49
  return lines.join("\n");
50
50
  }
51
- function isFoldedRow(item) {
52
- return "folded" in item;
53
- }
54
51
  function renderFoldedRow(row) {
55
52
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
56
53
  const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
@@ -60,7 +57,7 @@ function renderPage(page) {
60
57
  // An empty selection has no anchors either, so it would otherwise render as nothing at all.
61
58
  if (page.items.length === 0)
62
59
  return "No events match these filters.";
63
- const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
60
+ const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
64
61
  const cursors = [
65
62
  page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
66
63
  page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
@@ -145,8 +142,8 @@ export const historyListParameters = Type.Object({
145
142
  until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
146
143
  from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
147
144
  window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
148
- limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
149
- max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
145
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
146
+ max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
150
147
  }, { additionalProperties: false });
151
148
  export const historyList = {
152
149
  name: "history_list",
@@ -2,10 +2,6 @@ import type { NotesIdentity } from "../notes/identity.js";
2
2
  import { Type, type Static } from "typebox";
3
3
  import { type NoteChange } from "../notes/index.js";
4
4
  import { type Outcome } from "./result.js";
5
- /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
6
- export declare const MAX_METADATA_ENTRY_BYTES = 1024;
7
- /** An extra value that cannot be carried is named in place, never silently dropped. */
8
- export declare const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
9
5
  export declare const NoteMetadataSchema: Type.TObject<{
10
6
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
11
7
  created_at: Type.TString;
@@ -33,8 +29,6 @@ export declare const NotesReadDataSchema: Type.TObject<{
33
29
  text: Type.TString;
34
30
  total_chars: Type.TInteger;
35
31
  next_offset_chars: Type.TUnion<[Type.TInteger, Type.TNull]>;
36
- address: Type.TString;
37
- project_key: Type.TOptional<Type.TString>;
38
32
  metadata: Type.TObject<{
39
33
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
40
34
  created_at: Type.TString;
@@ -43,16 +37,28 @@ export declare const NotesReadDataSchema: Type.TObject<{
43
37
  project: Type.TOptional<Type.TString>;
44
38
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
45
39
  }>;
40
+ project_root: Type.TOptional<Type.TString>;
41
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
42
+ name: Type.TString;
43
+ path: Type.TString;
44
+ }>>>;
45
+ address: Type.TString;
46
+ project_key: Type.TOptional<Type.TString>;
46
47
  }>;
47
48
  export type NotesReadData = Static<typeof NotesReadDataSchema>;
48
49
  export declare const NotesListDataSchema: Type.TObject<{
49
50
  more: Type.TInteger;
50
51
  homes_unavailable: Type.TArray<Type.TString>;
51
52
  files: Type.TArray<Type.TObject<{
52
- address: Type.TString;
53
- project_key: Type.TOptional<Type.TString>;
54
53
  updated_at: Type.TString;
55
54
  crumpled_at: Type.TOptional<Type.TString>;
55
+ project_root: Type.TOptional<Type.TString>;
56
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
57
+ name: Type.TString;
58
+ path: Type.TString;
59
+ }>>>;
60
+ address: Type.TString;
61
+ project_key: Type.TOptional<Type.TString>;
56
62
  }>>;
57
63
  }>;
58
64
  export type NotesListData = Static<typeof NotesListDataSchema>;
@@ -65,10 +71,15 @@ export declare const NotesSearchDataSchema: Type.TObject<{
65
71
  text: Type.TString;
66
72
  offset_chars: Type.TInteger;
67
73
  }>>;
68
- address: Type.TString;
69
- project_key: Type.TOptional<Type.TString>;
70
74
  updated_at: Type.TString;
71
75
  crumpled_at: Type.TOptional<Type.TString>;
76
+ project_root: Type.TOptional<Type.TString>;
77
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
78
+ name: Type.TString;
79
+ path: Type.TString;
80
+ }>>>;
81
+ address: Type.TString;
82
+ project_key: Type.TOptional<Type.TString>;
72
83
  }>>;
73
84
  }>;
74
85
  export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
@@ -80,7 +91,7 @@ export declare const notesWriteParameters: Type.TObject<{
80
91
  export declare const notesWrite: {
81
92
  readonly name: "notes_write";
82
93
  readonly label: "Notes write";
83
- readonly description: "Create or replace a note. Name it for what it holds and when to use it. Store what git and history can't recover. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
94
+ readonly description: "Create or replace a note. Name it for what it holds and when to use it. Store what git and history can't recover. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes; `@projects/<name>/<path>` reads a named project (discover with glob `@projects/*/**`). Not file paths: never pass them to file tools.";
84
95
  readonly parameters: Type.TObject<{
85
96
  address: Type.TString;
86
97
  content: Type.TString;
@@ -115,7 +126,7 @@ export declare const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
115
126
  export declare const notesUpdate: {
116
127
  readonly name: "notes_update";
117
128
  readonly label: "Notes update";
118
- readonly description: "Edit a note, change its origin or crumpled state, or move it. Each `oldText` must match exactly once unless `replace_all` is true. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
129
+ readonly description: "Edit a note, change its origin or crumpled state, or move it. Each `oldText` must match exactly once unless `replace_all` is true. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes; `@projects/<name>/<path>` reads a named project (discover with glob `@projects/*/**`). Not file paths: never pass them to file tools.";
119
130
  readonly parameters: Type.TObject<{
120
131
  address: Type.TString;
121
132
  edits: Type.TOptional<Type.TArray<Type.TObject<{
@@ -149,7 +160,7 @@ export declare const notesReadParameters: Type.TObject<{
149
160
  export declare const notesRead: {
150
161
  readonly name: "notes_read";
151
162
  readonly label: "Notes read";
152
- readonly description: "Read a note. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
163
+ readonly description: "Read a note. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes; `@projects/<name>/<path>` reads a named project (discover with glob `@projects/*/**`). Not file paths: never pass them to file tools.";
153
164
  readonly parameters: Type.TObject<{
154
165
  offset_chars: Type.TOptional<Type.TInteger>;
155
166
  max_chars: Type.TOptional<Type.TInteger>;
@@ -159,8 +170,6 @@ export declare const notesRead: {
159
170
  text: Type.TString;
160
171
  total_chars: Type.TInteger;
161
172
  next_offset_chars: Type.TUnion<[Type.TInteger, Type.TNull]>;
162
- address: Type.TString;
163
- project_key: Type.TOptional<Type.TString>;
164
173
  metadata: Type.TObject<{
165
174
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
166
175
  created_at: Type.TString;
@@ -169,6 +178,13 @@ export declare const notesRead: {
169
178
  project: Type.TOptional<Type.TString>;
170
179
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
171
180
  }>;
181
+ project_root: Type.TOptional<Type.TString>;
182
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
183
+ name: Type.TString;
184
+ path: Type.TString;
185
+ }>>>;
186
+ address: Type.TString;
187
+ project_key: Type.TOptional<Type.TString>;
172
188
  }>, Type.TObject<{
173
189
  error: Type.TString;
174
190
  code: Type.TString;
@@ -184,7 +200,7 @@ export declare const notesListParameters: Type.TObject<{
184
200
  export declare const notesList: {
185
201
  readonly name: "notes_list";
186
202
  readonly label: "Notes list";
187
- readonly description: "List notes in this session and the four @ homes, newest first. Not pageable; `more` counts the rest. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
203
+ readonly description: "List notes in this session and the four @ homes, newest first. Not pageable; `more` counts the rest. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes; `@projects/<name>/<path>` reads a named project (discover with glob `@projects/*/**`). Not file paths: never pass them to file tools.";
188
204
  readonly parameters: Type.TObject<{
189
205
  glob: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
190
206
  limit: Type.TOptional<Type.TInteger>;
@@ -194,10 +210,15 @@ export declare const notesList: {
194
210
  more: Type.TInteger;
195
211
  homes_unavailable: Type.TArray<Type.TString>;
196
212
  files: Type.TArray<Type.TObject<{
197
- address: Type.TString;
198
- project_key: Type.TOptional<Type.TString>;
199
213
  updated_at: Type.TString;
200
214
  crumpled_at: Type.TOptional<Type.TString>;
215
+ project_root: Type.TOptional<Type.TString>;
216
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
217
+ name: Type.TString;
218
+ path: Type.TString;
219
+ }>>>;
220
+ address: Type.TString;
221
+ project_key: Type.TOptional<Type.TString>;
201
222
  }>>;
202
223
  }>, Type.TObject<{
203
224
  error: Type.TString;
@@ -218,7 +239,7 @@ export declare const MATCH_SHORTENED_MARKER = " [truncated]";
218
239
  export declare const notesSearch: {
219
240
  readonly name: "notes_search";
220
241
  readonly label: "Notes search";
221
- readonly description: "Search note bodies for literal text, case-insensitive. Returns matching lines with offsets for `notes_read`. Not pageable; `more` counts the rest. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
242
+ readonly description: "Search note bodies for literal text, case-insensitive. Returns matching lines with offsets for `notes_read`. Not pageable; `more` counts the rest. Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes; `@projects/<name>/<path>` reads a named project (discover with glob `@projects/*/**`). Not file paths: never pass them to file tools.";
222
243
  readonly parameters: Type.TObject<{
223
244
  query: Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
224
245
  glob: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
@@ -235,10 +256,15 @@ export declare const notesSearch: {
235
256
  text: Type.TString;
236
257
  offset_chars: Type.TInteger;
237
258
  }>>;
238
- address: Type.TString;
239
- project_key: Type.TOptional<Type.TString>;
240
259
  updated_at: Type.TString;
241
260
  crumpled_at: Type.TOptional<Type.TString>;
261
+ project_root: Type.TOptional<Type.TString>;
262
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
263
+ name: Type.TString;
264
+ path: Type.TString;
265
+ }>>>;
266
+ address: Type.TString;
267
+ project_key: Type.TOptional<Type.TString>;
242
268
  }>>;
243
269
  }>, Type.TObject<{
244
270
  error: Type.TString;
@@ -13,11 +13,7 @@ const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional)
13
13
  const CRUMPLED_LIST_PARAMETER = Type.Optional(Type.Boolean({ description: "(optional) true = list only crumpled notes." }));
14
14
  const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
15
15
  const GLOB_PARAMETER = nullableString("(optional) Glob over full addresses.");
16
- const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes. Not file paths: never pass them to file tools.";
17
- /** The one receipt field a caller cannot derive from the address itself. */
18
- function projectKeyField(scope, projectKey) {
19
- return scope === "project" ? { project_key: projectKey } : {};
20
- }
16
+ const ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable homes; `@projects/<name>/<path>` reads a named project (discover with glob `@projects/*/**`). Not file paths: never pass them to file tools.";
21
17
  /**
22
18
  * Typed refusal. Every fact a caller needs is already in the message; there is no separate context.
23
19
  * Convert expected refusals; unexpected errors propagate unchanged.
@@ -32,20 +28,13 @@ function failureOf(error) {
32
28
  return failure("io_error", "notes operation failed");
33
29
  throw error;
34
30
  }
35
- function byRecent(a, b) {
36
- return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
37
- }
38
31
  /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
39
32
  const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
40
33
  /** One unrecognized entry, and the verbatim extras together, are bounded so `extra` cannot outgrow the read. */
41
- export const MAX_METADATA_ENTRY_BYTES = 1024;
34
+ const MAX_METADATA_ENTRY_BYTES = 1024;
42
35
  const MAX_METADATA_VERBATIM_BYTES = 2048;
43
36
  /** An extra value that cannot be carried is named in place, never silently dropped. */
44
- export const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
45
- /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
46
- function extraEntryBytes(key, value) {
47
- return structuredBytes(key) + 1 + structuredBytes(value);
48
- }
37
+ const TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
49
38
  export const NoteMetadataSchema = Type.Object({
50
39
  origin: Type.Union([...ORIGIN_VALUES]),
51
40
  created_at: Type.String(),
@@ -68,7 +57,8 @@ function noteMetadata(meta) {
68
57
  // A key too large to carry cannot be named at all; an oversized value is named in place.
69
58
  if (structuredBytes(key) > MAX_METADATA_ENTRY_BYTES)
70
59
  continue;
71
- const entryBytes = extraEntryBytes(key, value);
60
+ // The key counts too: hand-written frontmatter can have arbitrarily long keys.
61
+ const entryBytes = structuredBytes(key) + 1 + structuredBytes(value);
72
62
  if (entryBytes > MAX_METADATA_ENTRY_BYTES || verbatimBytes + entryBytes > MAX_METADATA_VERBATIM_BYTES) {
73
63
  put(key, TOO_LARGE_EXTRA_VALUE);
74
64
  continue;
@@ -98,13 +88,23 @@ function renderMetadata(metadata) {
98
88
  fields.push(`extra ${JSON.stringify(metadata.extra)}`);
99
89
  return fields.join(" | ");
100
90
  }
101
- /** Address plus project key in one line; the project key never replaces the address. */
91
+ /** Keep the address visible, with project context and at most one sibling hint line. */
102
92
  function renderIdentity(identity) {
103
- return identity.project_key === undefined ? identity.address : `${identity.address} (project ${identity.project_key})`;
93
+ let text = identity.project_key === undefined ? identity.address : `${identity.address} (project ${identity.project_key})`;
94
+ if (identity.project_root !== undefined)
95
+ text += ` (project_root ${identity.project_root})`;
96
+ if (identity.project_siblings !== undefined)
97
+ text += `\n Same-basename projects: ${identity.project_siblings.map(sibling => `${sibling.name} (${sibling.path})`).join(", ")}`;
98
+ return text;
104
99
  }
100
+ const ProjectReceiptSchema = {
101
+ project_root: Type.Optional(Type.String()),
102
+ project_siblings: Type.Optional(Type.Array(Type.Object({ name: Type.String(), path: Type.String() }, { additionalProperties: false }))),
103
+ };
105
104
  const ListedFileSchema = Type.Object({
106
105
  address: Type.String(),
107
106
  project_key: Type.Optional(Type.String()),
107
+ ...ProjectReceiptSchema,
108
108
  updated_at: Type.String(),
109
109
  crumpled_at: Type.Optional(Type.String()),
110
110
  }, { additionalProperties: false });
@@ -136,6 +136,7 @@ export const NotesUpdateDataSchema = Type.Object({
136
136
  export const NotesReadDataSchema = Type.Object({
137
137
  address: Type.String(),
138
138
  project_key: Type.Optional(Type.String()),
139
+ ...ProjectReceiptSchema,
139
140
  metadata: NoteMetadataSchema,
140
141
  ...TextWindowSchema.properties,
141
142
  }, { additionalProperties: false });
@@ -171,7 +172,7 @@ function snapshot(rows, limit, status, renderData, shrink) {
171
172
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable homes is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer homes.`);
172
173
  }
173
174
  function listedFile(row, identity) {
174
- return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
175
+ return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
175
176
  }
176
177
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
177
178
  function renderWriteData(data) {
@@ -347,7 +348,7 @@ export const notesSearch = {
347
348
  async execute(params, identity) {
348
349
  try {
349
350
  const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? undefined, crumpled: params.crumpled });
350
- const files = rows.sort(byRecent).map(row => ({
351
+ const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map(row => ({
351
352
  ...listedFile(row, identity),
352
353
  matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, offset_chars: match.offsetChars })),
353
354
  }));
@@ -1,13 +1,10 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
2
  export declare const TOOL_OUTPUT_MAX_BYTES: number;
4
3
  /** The per-call limit as the model reads it in refusals. */
5
4
  export declare const TOOL_OUTPUT_LIMIT = "32 KB";
6
5
  export declare const DEFAULT_READ_WINDOW_CHARS = 12000;
7
6
  export declare const MAX_READ_WINDOW_CHARS = 50000;
8
7
  export declare const HISTORY_PREVIEW_CHARS = 1200;
9
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
10
- export declare function withinTextBudget(text: string, budget?: number): boolean;
11
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
12
9
  export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
13
10
  /**
@@ -1,18 +1,10 @@
1
1
  /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
2
- export { earliestMatchOffsetChars } from "../text-match.js";
3
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
4
3
  /** The per-call limit as the model reads it in refusals. */
5
4
  export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
6
5
  export const DEFAULT_READ_WINDOW_CHARS = 12000;
7
6
  export const MAX_READ_WINDOW_CHARS = 50000;
8
7
  export const HISTORY_PREVIEW_CHARS = 1200;
9
- function json(value) {
10
- return JSON.stringify(value);
11
- }
12
- /** True when `text` fits the wire budget verbatim, for raw payloads with no JSON encoding. */
13
- export function withinTextBudget(text, budget = TOOL_OUTPUT_MAX_BYTES) {
14
- return Buffer.byteLength(text, "utf8") <= budget;
15
- }
16
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
17
9
  export function prefixFit(text, fits) {
18
10
  if (fits(text))
@@ -37,5 +29,5 @@ export function prefixFit(text, fits) {
37
29
  * undefined unless the tool has metadata worth persisting.
38
30
  */
39
31
  export function output(value, details, terminate = false) {
40
- return { content: [{ type: "text", text: json(value) }], details, terminate };
32
+ return { content: [{ type: "text", text: JSON.stringify(value) }], details, terminate };
41
33
  }
@@ -17,6 +17,7 @@ export type Outcome<T> = {
17
17
  export declare function success<T>(data: T): Outcome<T>;
18
18
  /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
19
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. */
20
21
  export declare function failure(code: string, message: string): Outcome<never>;
21
22
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
22
23
  export declare const WireErrorSchema: Type.TObject<{
@@ -1,6 +1,6 @@
1
1
  /** Internal outcomes, compact wire results, and bounded read windows. */
2
2
  import { Type } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES, withinTextBudget } from "./output.js";
3
+ import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit, TOOL_OUTPUT_LIMIT, TOOL_OUTPUT_MAX_BYTES } from "./output.js";
4
4
  /** The one refusal shape: `code` is a stable internal identifier, `message` the bounded reading. */
5
5
  export const OperationErrorSchema = Type.Object({
6
6
  code: Type.String(),
@@ -11,12 +11,11 @@ export function success(data) {
11
11
  }
12
12
  /** A code is an internal stable identifier and is never clipped; the dynamic message is the bounded surface. */
13
13
  export const ERROR_MESSAGE_MAX_CHARS = 2000;
14
- function boundedMessage(message) {
15
- const chars = Array.from(message);
16
- return chars.length <= ERROR_MESSAGE_MAX_CHARS ? message : `${chars.slice(0, ERROR_MESSAGE_MAX_CHARS).join("")}…[truncated ${chars.length - ERROR_MESSAGE_MAX_CHARS} chars]`;
17
- }
14
+ /** Bounded refusal: a runaway message is clipped with a marker instead of filling the wire. */
18
15
  export function failure(code, message) {
19
- return { ok: false, error: { code, message: boundedMessage(message) } };
16
+ const chars = Array.from(message);
17
+ 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]`;
18
+ return { ok: false, error: { code, message: bounded } };
20
19
  }
21
20
  /** Public results have no success envelope. `error` is reserved for a refusal message. */
22
21
  export const WireErrorSchema = Type.Object({ error: Type.String(), code: Type.String() }, { additionalProperties: false });
@@ -42,7 +41,7 @@ export function structuredBytes(value) {
42
41
  * measure covers everything the renderer puts around the payload, headers and footers included.
43
42
  */
44
43
  export function fitsResult(result, render) {
45
- return withinTextBudget(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
44
+ return Buffer.byteLength(render(result), "utf8") <= TOOL_OUTPUT_MAX_BYTES && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
46
45
  }
47
46
  /** `text` is verbatim, with no marker inserted, so windows concatenate back into the source. */
48
47
  export const TextWindowSchema = Type.Object({
@@ -71,7 +70,8 @@ export function readTextWindow(text, offset, limit, makeData, render) {
71
70
  const requested = offset ?? 0;
72
71
  const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
73
72
  const requestedChars = limit ?? DEFAULT_READ_WINDOW_CHARS;
74
- const range = Math.min(requestedChars, chars.length - start);
73
+ // A start past the end (a caller that skipped its own offset check) has nothing to deliver.
74
+ const range = Math.max(0, Math.min(requestedChars, chars.length - start));
75
75
  const window = (delivered) => {
76
76
  const end = start + delivered;
77
77
  return {
@@ -81,21 +81,15 @@ export function readTextWindow(text, offset, limit, makeData, render) {
81
81
  };
82
82
  };
83
83
  const fits = (delivered) => fitsResult(success(makeData(window(delivered))), render);
84
- // Test the full range first: its footer can disappear at the end of the document.
84
+ // Test the full range first: its footer can disappear at the end of the document, and an
85
+ // empty source is a complete window rather than a refusal.
85
86
  if (fits(range))
86
87
  return success(makeData(window(range)));
87
- let low = 0;
88
- let high = range;
89
- while (low < high) {
90
- const mid = Math.ceil((low + high) / 2);
91
- if (fits(mid))
92
- low = mid;
93
- else
94
- high = mid - 1;
95
- }
96
- if (low === 0)
88
+ // The kept count is monotone in the serialized size, so the shared prefix search owns the shrink.
89
+ const delivered = Array.from(prefixFit(window(range).text, (candidate) => fits(Array.from(candidate).length))).length;
90
+ if (delivered === 0)
97
91
  return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
98
- return success(makeData(window(low)));
92
+ return success(makeData(window(delivered)));
99
93
  }
100
94
  /** The continuation line never becomes part of `window.text`, and a complete window has none. */
101
95
  export function renderTextWindow(window) {
@@ -1,6 +1,5 @@
1
1
  import { Type } from "typebox";
2
2
  export declare const nullableString: (description?: string) => Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
3
- export declare const positiveInteger: () => Type.TOptional<Type.TInteger>;
4
3
  export declare const historyRoles: () => Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
5
4
  /** Search query parameter: one literal, or several literals combined with OR. */
6
5
  export declare const searchQuery: (description?: string) => Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
@@ -1,7 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import { HistoryRoleSchema } from "../history/history.js";
3
3
  export const nullableString = (description) => Type.Optional(Type.Union([Type.String(), Type.Null()], description === undefined ? {} : { description }));
4
- export const positiveInteger = () => Type.Optional(Type.Integer({ minimum: 1 }));
5
4
  export const historyRoles = () => Type.Optional(Type.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
6
5
  /** Search query parameter: one literal, or several literals combined with OR. */
7
6
  export const searchQuery = (description) => Type.Union([Type.String(), Type.Array(Type.String(), { minItems: 1 })], description === undefined ? {} : { description });
@@ -8,8 +8,7 @@ import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, Mod
8
8
  import notesoup, { createNotesoup } from "../src/pi/extension.js";
9
9
  import { BOOT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../src/pi/entries.js";
10
10
  import { CONTEXT_WINDOW_OPEN_TAG } from "../src/boot/text.js";
11
- import { CONTINUATION, WARNING_CONTENT, WARNING_PROMPT } from "../src/pi/reset/text.js";
12
- import { GUIDANCE_OPEN_TAG } from "../src/budget/text.js";
11
+ import { CONTINUATION, GUIDANCE_OPEN_TAG, WARNING_CONTENT, WARNING_PROMPT } from "../src/budget/text.js";
13
12
  async function openFixture(options) {
14
13
  const dir = options.cwd ?? mkdtempSync(join(tmpdir(), "notesoup-agent-loop-"));
15
14
  const ownsDir = options.cwd === undefined;
@@ -6,7 +6,7 @@ import test from "node:test";
6
6
  import { historyFromSession } from "../src/pi/history.js";
7
7
  import { BOOT_TYPE, GUIDANCE_TYPE, RESET_MARKER_TYPE } from "../src/pi/entries.js";
8
8
  import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_PROTOCOL_OPEN_TAG } from "../src/boot/text.js";
9
- import { CONTINUATION } from "../src/pi/reset/text.js";
9
+ import { CONTINUATION } from "../src/budget/text.js";
10
10
  import { listNotes } from "./helpers/notes.js";
11
11
  import { CONTINUATION_TYPE, MANUAL_WIPE_TYPE } from "../src/pi/entries.js";
12
12
  import { appendText, call, commitTurnEndBoundary, context, makeExtension, manager, noticesOf, resultData, resultJson, resultRead, runContextHook, runContextWithSystemHook, runHandlers, runManualCompact, runCommand, sentOf, } from "./helpers/extension.js";