notesoup 0.0.0-stage → 0.39.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -2
  3. package/dist/src/boot/render.d.ts +16 -0
  4. package/dist/src/boot/render.js +95 -0
  5. package/dist/src/boot/snapshot.d.ts +32 -0
  6. package/dist/src/boot/snapshot.js +36 -0
  7. package/dist/src/boot/text.d.ts +21 -0
  8. package/dist/src/boot/text.js +52 -0
  9. package/dist/src/budget/constants.d.ts +9 -0
  10. package/dist/src/budget/constants.js +9 -0
  11. package/dist/src/budget/policy.d.ts +19 -0
  12. package/dist/src/budget/policy.js +36 -0
  13. package/dist/src/budget/text.d.ts +8 -0
  14. package/dist/src/budget/text.js +10 -0
  15. package/dist/src/claude/helper.d.ts +15 -0
  16. package/dist/src/claude/helper.js +87 -0
  17. package/dist/src/dream/doctor.d.ts +2 -0
  18. package/dist/src/dream/doctor.js +160 -0
  19. package/dist/src/dream/gates.d.ts +10 -0
  20. package/dist/src/dream/gates.js +26 -0
  21. package/dist/src/dream/git.d.ts +21 -0
  22. package/dist/src/dream/git.js +71 -0
  23. package/dist/src/dream/jail.d.ts +11 -0
  24. package/dist/src/dream/jail.js +71 -0
  25. package/dist/src/dream/lock.d.ts +31 -0
  26. package/dist/src/dream/lock.js +99 -0
  27. package/dist/src/dream/playbook.d.ts +1 -0
  28. package/dist/src/dream/playbook.js +2 -0
  29. package/dist/src/dream/report.d.ts +7 -0
  30. package/dist/src/dream/report.js +43 -0
  31. package/dist/src/dream/result.d.ts +9 -0
  32. package/dist/src/dream/result.js +1 -0
  33. package/dist/src/dream/settings.d.ts +10 -0
  34. package/dist/src/dream/settings.js +14 -0
  35. package/dist/src/history/history.d.ts +151 -0
  36. package/dist/src/history/history.js +195 -0
  37. package/dist/src/history/query.d.ts +75 -0
  38. package/dist/src/history/query.js +143 -0
  39. package/dist/src/index.d.ts +1 -0
  40. package/dist/src/index.js +1 -0
  41. package/dist/src/notes/address.d.ts +31 -0
  42. package/dist/src/notes/address.js +123 -0
  43. package/dist/src/notes/constants.d.ts +3 -0
  44. package/dist/src/notes/constants.js +3 -0
  45. package/dist/src/notes/errors.d.ts +11 -0
  46. package/dist/src/notes/errors.js +13 -0
  47. package/dist/src/notes/frontmatter.d.ts +44 -0
  48. package/dist/src/notes/frontmatter.js +145 -0
  49. package/dist/src/notes/fs-error.d.ts +2 -0
  50. package/dist/src/notes/fs-error.js +5 -0
  51. package/dist/src/notes/identity.d.ts +10 -0
  52. package/dist/src/notes/identity.js +33 -0
  53. package/dist/src/notes/index.d.ts +5 -0
  54. package/dist/src/notes/index.js +3 -0
  55. package/dist/src/notes/paths.d.ts +21 -0
  56. package/dist/src/notes/paths.js +113 -0
  57. package/dist/src/notes/store.d.ts +104 -0
  58. package/dist/src/notes/store.js +478 -0
  59. package/dist/src/pi/boot.d.ts +24 -0
  60. package/dist/src/pi/boot.js +56 -0
  61. package/dist/src/pi/budget.d.ts +13 -0
  62. package/dist/src/pi/budget.js +178 -0
  63. package/dist/src/pi/dream/cli.d.ts +10 -0
  64. package/dist/src/pi/dream/cli.js +140 -0
  65. package/dist/src/pi/dream/runner.d.ts +27 -0
  66. package/dist/src/pi/dream/runner.js +90 -0
  67. package/dist/src/pi/dream/settings.d.ts +7 -0
  68. package/dist/src/pi/dream/settings.js +17 -0
  69. package/dist/src/pi/entries.d.ts +7 -0
  70. package/dist/src/pi/entries.js +7 -0
  71. package/dist/src/pi/estimate.d.ts +16 -0
  72. package/dist/src/pi/estimate.js +99 -0
  73. package/dist/src/pi/extension.d.ts +10 -0
  74. package/dist/src/pi/extension.js +24 -0
  75. package/dist/src/pi/history-tools.d.ts +3 -0
  76. package/dist/src/pi/history-tools.js +10 -0
  77. package/dist/src/pi/history.d.ts +4 -0
  78. package/dist/src/pi/history.js +150 -0
  79. package/dist/src/pi/notes/adapter.d.ts +10 -0
  80. package/dist/src/pi/notes/adapter.js +27 -0
  81. package/dist/src/pi/notes/tools.d.ts +3 -0
  82. package/dist/src/pi/notes/tools.js +15 -0
  83. package/dist/src/pi/reset/artifacts.d.ts +24 -0
  84. package/dist/src/pi/reset/artifacts.js +84 -0
  85. package/dist/src/pi/reset/committed.d.ts +7 -0
  86. package/dist/src/pi/reset/committed.js +28 -0
  87. package/dist/src/pi/reset/lifecycle.d.ts +101 -0
  88. package/dist/src/pi/reset/lifecycle.js +277 -0
  89. package/dist/src/pi/reset/text.d.ts +5 -0
  90. package/dist/src/pi/reset/text.js +6 -0
  91. package/dist/src/pi/runtime.d.ts +3 -0
  92. package/dist/src/pi/runtime.js +206 -0
  93. package/dist/src/pi/session-reader.d.ts +5 -0
  94. package/dist/src/pi/session-reader.js +1 -0
  95. package/dist/src/pi/thresholds.d.ts +17 -0
  96. package/dist/src/pi/thresholds.js +33 -0
  97. package/dist/src/pi/tool-names.d.ts +11 -0
  98. package/dist/src/pi/tool-names.js +11 -0
  99. package/dist/src/pi/tool-result.d.ts +15 -0
  100. package/dist/src/pi/tool-result.js +29 -0
  101. package/dist/src/pi/window.d.ts +41 -0
  102. package/dist/src/pi/window.js +127 -0
  103. package/dist/src/settings.d.ts +9 -0
  104. package/dist/src/settings.js +18 -0
  105. package/dist/src/text-match.d.ts +5 -0
  106. package/dist/src/text-match.js +16 -0
  107. package/dist/src/tools/history.d.ts +67 -0
  108. package/dist/src/tools/history.js +251 -0
  109. package/dist/src/tools/notes.d.ts +282 -0
  110. package/dist/src/tools/notes.js +378 -0
  111. package/dist/src/tools/output.d.ts +23 -0
  112. package/dist/src/tools/output.js +39 -0
  113. package/dist/src/tools/result.d.ts +79 -0
  114. package/dist/src/tools/result.js +130 -0
  115. package/dist/src/tools/schema.d.ts +18 -0
  116. package/dist/src/tools/schema.js +31 -0
  117. package/dist/test/agent-loop.test.d.ts +1 -0
  118. package/dist/test/agent-loop.test.js +1497 -0
  119. package/dist/test/boot.integration.test.d.ts +1 -0
  120. package/dist/test/boot.integration.test.js +294 -0
  121. package/dist/test/budget-settings.integration.test.d.ts +1 -0
  122. package/dist/test/budget-settings.integration.test.js +144 -0
  123. package/dist/test/claude-mod.test.d.ts +1 -0
  124. package/dist/test/claude-mod.test.js +404 -0
  125. package/dist/test/dependencies.test.d.ts +1 -0
  126. package/dist/test/dependencies.test.js +101 -0
  127. package/dist/test/doctor.test.d.ts +1 -0
  128. package/dist/test/doctor.test.js +37 -0
  129. package/dist/test/dream-skill.test.d.ts +1 -0
  130. package/dist/test/dream-skill.test.js +72 -0
  131. package/dist/test/dream.test.d.ts +1 -0
  132. package/dist/test/dream.test.js +136 -0
  133. package/dist/test/helpers/dependency-graph.d.ts +5 -0
  134. package/dist/test/helpers/dependency-graph.js +73 -0
  135. package/dist/test/helpers/extension-test-environment.d.ts +1 -0
  136. package/dist/test/helpers/extension-test-environment.js +9 -0
  137. package/dist/test/helpers/extension.d.ts +119 -0
  138. package/dist/test/helpers/extension.js +368 -0
  139. package/dist/test/helpers/notes.d.ts +6 -0
  140. package/dist/test/helpers/notes.js +13 -0
  141. package/dist/test/history.integration.test.d.ts +1 -0
  142. package/dist/test/history.integration.test.js +556 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +300 -0
  145. package/dist/test/notes-library.test.d.ts +1 -0
  146. package/dist/test/notes-library.test.js +214 -0
  147. package/dist/test/notes.integration.test.d.ts +1 -0
  148. package/dist/test/notes.integration.test.js +497 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +528 -0
  151. package/dist/test/reset-lifecycle.test.d.ts +1 -0
  152. package/dist/test/reset-lifecycle.test.js +605 -0
  153. package/docs/architecture.md +63 -0
  154. package/docs/claude-code-mod.md +9 -0
  155. package/docs/notes-library.md +74 -0
  156. package/docs/reset-lifecycle.md +75 -0
  157. package/docs/sdk-integration.md +39 -0
  158. package/docs/skills.md +30 -0
  159. package/docs/tool-results.md +88 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9324 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +241 -0
  164. package/mods/notesoup/playbook.md +34 -0
  165. package/mods/notesoup/skills/dream/SKILL.md +12 -0
  166. package/mods/pi-context/dist/claude/helper.js +9324 -0
  167. package/package.json +89 -5
  168. package/playbook.md +34 -0
  169. package/skills/dream/SKILL.md +12 -0
  170. package/skills/memory/SKILL.md +59 -0
  171. package/src/boot/render.ts +115 -0
  172. package/src/boot/snapshot.ts +46 -0
  173. package/src/boot/text.ts +66 -0
  174. package/src/budget/constants.ts +9 -0
  175. package/src/budget/policy.ts +36 -0
  176. package/src/budget/text.ts +11 -0
  177. package/src/claude/helper.ts +94 -0
  178. package/src/dream/doctor.ts +117 -0
  179. package/src/dream/gates.ts +26 -0
  180. package/src/dream/git.ts +73 -0
  181. package/src/dream/jail.ts +62 -0
  182. package/src/dream/lock.ts +82 -0
  183. package/src/dream/playbook.ts +3 -0
  184. package/src/dream/report.ts +36 -0
  185. package/src/dream/result.ts +2 -0
  186. package/src/dream/settings.ts +16 -0
  187. package/src/history/history.ts +270 -0
  188. package/src/history/query.ts +147 -0
  189. package/src/index.ts +1 -0
  190. package/src/notes/address.ts +110 -0
  191. package/src/notes/constants.ts +3 -0
  192. package/src/notes/errors.ts +15 -0
  193. package/src/notes/frontmatter.ts +166 -0
  194. package/src/notes/fs-error.ts +5 -0
  195. package/src/notes/identity.ts +40 -0
  196. package/src/notes/index.ts +24 -0
  197. package/src/notes/paths.ts +109 -0
  198. package/src/notes/store.ts +497 -0
  199. package/src/pi/boot.ts +88 -0
  200. package/src/pi/budget.ts +178 -0
  201. package/src/pi/dream/cli.ts +92 -0
  202. package/src/pi/dream/runner.ts +91 -0
  203. package/src/pi/dream/settings.ts +17 -0
  204. package/src/pi/entries.ts +7 -0
  205. package/src/pi/estimate.ts +116 -0
  206. package/src/pi/extension.ts +27 -0
  207. package/src/pi/history-tools.ts +12 -0
  208. package/src/pi/history.ts +162 -0
  209. package/src/pi/notes/adapter.ts +33 -0
  210. package/src/pi/notes/tools.ts +18 -0
  211. package/src/pi/reset/artifacts.ts +100 -0
  212. package/src/pi/reset/committed.ts +26 -0
  213. package/src/pi/reset/lifecycle.ts +342 -0
  214. package/src/pi/reset/text.ts +10 -0
  215. package/src/pi/runtime.ts +200 -0
  216. package/src/pi/session-reader.ts +6 -0
  217. package/src/pi/thresholds.ts +50 -0
  218. package/src/pi/tool-names.ts +13 -0
  219. package/src/pi/tool-result.ts +41 -0
  220. package/src/pi/window.ts +133 -0
  221. package/src/settings.ts +22 -0
  222. package/src/text-match.ts +14 -0
  223. package/src/tools/history.ts +273 -0
  224. package/src/tools/notes.ts +394 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +169 -0
  227. package/src/tools/schema.ts +31 -0
@@ -0,0 +1,282 @@
1
+ import type { NotesIdentity } from "../notes/identity.js";
2
+ import { Type, type Static } from "typebox";
3
+ import { type NoteChange } from "../notes/index.js";
4
+ import { type Outcome } from "./result.js";
5
+ /** One unrecognized entry, and all of them together, are bounded; omissions are counted, never listed. */
6
+ export declare const MAX_METADATA_ENTRY_BYTES = 1024;
7
+ export declare const NoteMetadataSchema: Type.TObject<{
8
+ origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
9
+ created_at: Type.TString;
10
+ updated_at: Type.TString;
11
+ crumpled_at: Type.TOptional<Type.TString>;
12
+ project: Type.TOptional<Type.TString>;
13
+ extra: Type.TRecord<"^.*$", Type.TUnknown>;
14
+ /** Values left in the file but too large to show, summarized so the summary cannot grow. */
15
+ omitted_extra: Type.TOptional<Type.TObject<{
16
+ keys: Type.TInteger;
17
+ bytes: Type.TInteger;
18
+ }>>;
19
+ }>;
20
+ export type NoteMetadata = Static<typeof NoteMetadataSchema>;
21
+ export declare const NotesWriteDataSchema: Type.TObject<{
22
+ address: Type.TString;
23
+ project_key: Type.TOptional<Type.TString>;
24
+ outcome: Type.TUnion<[Type.TLiteral<"created">, Type.TLiteral<"overwrote">, Type.TLiteral<"uncrumpled">]>;
25
+ }>;
26
+ export type NotesWriteData = Static<typeof NotesWriteDataSchema>;
27
+ export declare const NotesUpdateDataSchema: Type.TObject<{
28
+ address: Type.TString;
29
+ project_key: Type.TOptional<Type.TString>;
30
+ applied: Type.TInteger;
31
+ change_kind: Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"body">, Type.TLiteral<"metadata">, Type.TLiteral<"file">]>;
32
+ diff: Type.TString;
33
+ diff_truncated: Type.TOptional<Type.TLiteral<true>>;
34
+ rename_from: Type.TOptional<Type.TString>;
35
+ replaced_crumpled_target: Type.TOptional<Type.TBoolean>;
36
+ }>;
37
+ export type NotesUpdateData = Static<typeof NotesUpdateDataSchema>;
38
+ export declare const NotesReadDataSchema: Type.TObject<{
39
+ text: Type.TString;
40
+ offset_chars: Type.TInteger;
41
+ total_chars: Type.TInteger;
42
+ next_offset_chars: Type.TUnion<[Type.TInteger, Type.TNull]>;
43
+ limited_by: Type.TUnion<[Type.TLiteral<"limit">, Type.TLiteral<"bytes">, Type.TNull]>;
44
+ address: Type.TString;
45
+ project_key: Type.TOptional<Type.TString>;
46
+ metadata: Type.TObject<{
47
+ origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
48
+ created_at: Type.TString;
49
+ updated_at: Type.TString;
50
+ crumpled_at: Type.TOptional<Type.TString>;
51
+ project: Type.TOptional<Type.TString>;
52
+ extra: Type.TRecord<"^.*$", Type.TUnknown>;
53
+ /** Values left in the file but too large to show, summarized so the summary cannot grow. */
54
+ omitted_extra: Type.TOptional<Type.TObject<{
55
+ keys: Type.TInteger;
56
+ bytes: Type.TInteger;
57
+ }>>;
58
+ }>;
59
+ }>;
60
+ export type NotesReadData = Static<typeof NotesReadDataSchema>;
61
+ export declare const NotesListDataSchema: Type.TObject<{
62
+ more: Type.TInteger;
63
+ crumpled_excluded: Type.TInteger;
64
+ homes_unavailable: Type.TArray<Type.TString>;
65
+ files: Type.TArray<Type.TObject<{
66
+ address: Type.TString;
67
+ project_key: Type.TOptional<Type.TString>;
68
+ updated_at: Type.TString;
69
+ crumpled_at: Type.TOptional<Type.TString>;
70
+ }>>;
71
+ }>;
72
+ export type NotesListData = Static<typeof NotesListDataSchema>;
73
+ export declare const NotesSearchDataSchema: Type.TObject<{
74
+ more: Type.TInteger;
75
+ crumpled_excluded: Type.TInteger;
76
+ homes_unavailable: Type.TArray<Type.TString>;
77
+ files: Type.TArray<Type.TObject<{
78
+ matches_total: Type.TInteger;
79
+ matches: Type.TArray<Type.TObject<{
80
+ line: Type.TInteger;
81
+ text: Type.TString;
82
+ truncated: Type.TBoolean;
83
+ offset_chars: Type.TInteger;
84
+ }>>;
85
+ address: Type.TString;
86
+ project_key: Type.TOptional<Type.TString>;
87
+ updated_at: Type.TString;
88
+ crumpled_at: Type.TOptional<Type.TString>;
89
+ }>>;
90
+ }>;
91
+ export type NotesSearchData = Static<typeof NotesSearchDataSchema>;
92
+ export declare const notesWriteParameters: Type.TObject<{
93
+ address: Type.TString;
94
+ content: Type.TString;
95
+ origin: Type.TOptional<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>>;
96
+ }>;
97
+ export declare const notesWrite: {
98
+ readonly name: "notes_write";
99
+ readonly label: "Notes write";
100
+ readonly description: "Create or replace a note body, preserving metadata; uncrumples a crumpled note. Name it for its contents and when to use it. Store what git/history cannot recover. Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
101
+ readonly parameters: Type.TObject<{
102
+ address: Type.TString;
103
+ content: Type.TString;
104
+ origin: Type.TOptional<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>>;
105
+ }>;
106
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
107
+ address: Type.TString;
108
+ project_key: Type.TOptional<Type.TString>;
109
+ outcome: Type.TUnion<[Type.TLiteral<"created">, Type.TLiteral<"overwrote">, Type.TLiteral<"uncrumpled">]>;
110
+ }>, Type.TObject<{
111
+ error: Type.TString;
112
+ code: Type.TString;
113
+ details: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
114
+ }>]>;
115
+ readonly executionMode: "sequential";
116
+ readonly execute: (params: Static<typeof notesWriteParameters>, identity: NotesIdentity) => Promise<Outcome<NotesWriteData>>;
117
+ readonly render: (result: Outcome<NotesWriteData>) => string;
118
+ };
119
+ export declare const notesUpdateParameters: Type.TObject<{
120
+ address: Type.TString;
121
+ edits: Type.TOptional<Type.TArray<Type.TObject<{
122
+ oldText: Type.TString;
123
+ newText: Type.TString;
124
+ }>>>;
125
+ origin: Type.TOptional<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>>;
126
+ crumpled: Type.TOptional<Type.TBoolean>;
127
+ replace_all: Type.TOptional<Type.TBoolean>;
128
+ rename_to: Type.TOptional<Type.TString>;
129
+ }>;
130
+ declare function renderUpdate(result: Outcome<NotesUpdateData>): string;
131
+ export declare const notesUpdate: {
132
+ readonly name: "notes_update";
133
+ readonly label: "Notes update";
134
+ readonly description: "Edit body text, change origin or crumpled state, or move a note. Each oldText must match once unless replace_all is true; edits cannot change frontmatter. Metadata-only updates need origin or crumpled. Returns applied changes and a bounded diff. Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
135
+ readonly parameters: Type.TObject<{
136
+ address: Type.TString;
137
+ edits: Type.TOptional<Type.TArray<Type.TObject<{
138
+ oldText: Type.TString;
139
+ newText: Type.TString;
140
+ }>>>;
141
+ origin: Type.TOptional<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>>;
142
+ crumpled: Type.TOptional<Type.TBoolean>;
143
+ replace_all: Type.TOptional<Type.TBoolean>;
144
+ rename_to: Type.TOptional<Type.TString>;
145
+ }>;
146
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
147
+ address: Type.TString;
148
+ project_key: Type.TOptional<Type.TString>;
149
+ applied: Type.TInteger;
150
+ change_kind: Type.TUnion<[Type.TLiteral<"none">, Type.TLiteral<"body">, Type.TLiteral<"metadata">, Type.TLiteral<"file">]>;
151
+ diff: Type.TString;
152
+ diff_truncated: Type.TOptional<Type.TLiteral<true>>;
153
+ rename_from: Type.TOptional<Type.TString>;
154
+ replaced_crumpled_target: Type.TOptional<Type.TBoolean>;
155
+ }>, Type.TObject<{
156
+ error: Type.TString;
157
+ code: Type.TString;
158
+ details: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
159
+ }>]>;
160
+ readonly executionMode: "sequential";
161
+ readonly execute: (params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string) => Promise<Outcome<NotesUpdateData>>;
162
+ readonly render: typeof renderUpdate;
163
+ };
164
+ export declare const notesReadParameters: Type.TObject<{
165
+ address: Type.TString;
166
+ offset_chars: Type.TOptional<Type.TInteger>;
167
+ limit_chars: Type.TOptional<Type.TInteger>;
168
+ }>;
169
+ export declare const notesRead: {
170
+ readonly name: "notes_read";
171
+ readonly label: "Notes read";
172
+ readonly description: "Read note metadata and a verbatim body slice, excluding frontmatter. Pass next_offset_chars as offset_chars until null. Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
173
+ readonly parameters: Type.TObject<{
174
+ address: Type.TString;
175
+ offset_chars: Type.TOptional<Type.TInteger>;
176
+ limit_chars: Type.TOptional<Type.TInteger>;
177
+ }>;
178
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
179
+ text: Type.TString;
180
+ offset_chars: Type.TInteger;
181
+ total_chars: Type.TInteger;
182
+ next_offset_chars: Type.TUnion<[Type.TInteger, Type.TNull]>;
183
+ limited_by: Type.TUnion<[Type.TLiteral<"limit">, Type.TLiteral<"bytes">, Type.TNull]>;
184
+ address: Type.TString;
185
+ project_key: Type.TOptional<Type.TString>;
186
+ metadata: Type.TObject<{
187
+ origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
188
+ created_at: Type.TString;
189
+ updated_at: Type.TString;
190
+ crumpled_at: Type.TOptional<Type.TString>;
191
+ project: Type.TOptional<Type.TString>;
192
+ extra: Type.TRecord<"^.*$", Type.TUnknown>;
193
+ /** Values left in the file but too large to show, summarized so the summary cannot grow. */
194
+ omitted_extra: Type.TOptional<Type.TObject<{
195
+ keys: Type.TInteger;
196
+ bytes: Type.TInteger;
197
+ }>>;
198
+ }>;
199
+ }>, Type.TObject<{
200
+ error: Type.TString;
201
+ code: Type.TString;
202
+ details: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
203
+ }>]>;
204
+ readonly execute: (params: Static<typeof notesReadParameters>, identity: NotesIdentity) => Promise<Outcome<NotesReadData>>;
205
+ readonly render: (result: Outcome<NotesReadData>) => string;
206
+ };
207
+ export declare const notesListParameters: Type.TObject<{
208
+ pattern: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
209
+ limit: Type.TOptional<Type.TInteger>;
210
+ wastebasket: Type.TOptional<Type.TBoolean>;
211
+ }>;
212
+ export declare const notesList: {
213
+ readonly name: "notes_list";
214
+ readonly label: "Notes list";
215
+ readonly description: "List notes in the session and the four @ homes, newest first. Snapshot, not pageable: more counts omitted files; pattern globs full addresses. Reports unavailable homes and how many crumpled notes were excluded. Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
216
+ readonly parameters: Type.TObject<{
217
+ pattern: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
218
+ limit: Type.TOptional<Type.TInteger>;
219
+ wastebasket: Type.TOptional<Type.TBoolean>;
220
+ }>;
221
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
222
+ more: Type.TInteger;
223
+ crumpled_excluded: Type.TInteger;
224
+ homes_unavailable: Type.TArray<Type.TString>;
225
+ files: Type.TArray<Type.TObject<{
226
+ address: Type.TString;
227
+ project_key: Type.TOptional<Type.TString>;
228
+ updated_at: Type.TString;
229
+ crumpled_at: Type.TOptional<Type.TString>;
230
+ }>>;
231
+ }>, Type.TObject<{
232
+ error: Type.TString;
233
+ code: Type.TString;
234
+ details: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
235
+ }>]>;
236
+ readonly execute: (params: Static<typeof notesListParameters>, identity: NotesIdentity) => Promise<Outcome<NotesListData>>;
237
+ readonly render: (result: Outcome<NotesListData>) => string;
238
+ };
239
+ export declare const notesSearchParameters: Type.TObject<{
240
+ query: Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
241
+ pattern: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
242
+ limit: Type.TOptional<Type.TInteger>;
243
+ max_matches_per_file: Type.TOptional<Type.TInteger>;
244
+ wastebasket: Type.TOptional<Type.TBoolean>;
245
+ }>;
246
+ export declare const notesSearch: {
247
+ readonly name: "notes_search";
248
+ readonly label: "Notes search";
249
+ readonly description: "Search note bodies for case-insensitive literal queries (OR). Returns matching lines and body code-point offsets for notes_read. Snapshot, not pageable: more counts omitted files; matches_total is before per-file capping. pattern globs full addresses across the session and the four @ homes. Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
250
+ readonly parameters: Type.TObject<{
251
+ query: Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
252
+ pattern: Type.TOptional<Type.TUnion<[Type.TString, Type.TNull]>>;
253
+ limit: Type.TOptional<Type.TInteger>;
254
+ max_matches_per_file: Type.TOptional<Type.TInteger>;
255
+ wastebasket: Type.TOptional<Type.TBoolean>;
256
+ }>;
257
+ readonly outputSchema: Type.TUnion<[Type.TObject<{
258
+ more: Type.TInteger;
259
+ crumpled_excluded: Type.TInteger;
260
+ homes_unavailable: Type.TArray<Type.TString>;
261
+ files: Type.TArray<Type.TObject<{
262
+ matches_total: Type.TInteger;
263
+ matches: Type.TArray<Type.TObject<{
264
+ line: Type.TInteger;
265
+ text: Type.TString;
266
+ truncated: Type.TBoolean;
267
+ offset_chars: Type.TInteger;
268
+ }>>;
269
+ address: Type.TString;
270
+ project_key: Type.TOptional<Type.TString>;
271
+ updated_at: Type.TString;
272
+ crumpled_at: Type.TOptional<Type.TString>;
273
+ }>>;
274
+ }>, Type.TObject<{
275
+ error: Type.TString;
276
+ code: Type.TString;
277
+ details: Type.TOptional<Type.TRecord<"^.*$", Type.TUnknown>>;
278
+ }>]>;
279
+ readonly execute: (params: Static<typeof notesSearchParameters>, identity: NotesIdentity) => Promise<Outcome<NotesSearchData>>;
280
+ readonly render: (result: Outcome<NotesSearchData>) => string;
281
+ };
282
+ export {};
@@ -0,0 +1,378 @@
1
+ import { Type } from "typebox";
2
+ import { localIso } from "../notes/frontmatter.js";
3
+ import { isFilesystemError } from "../notes/fs-error.js";
4
+ import { createNotesStore, NoteError, noteIdentity } from "../notes/index.js";
5
+ import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, prefixFit } from "./output.js";
6
+ import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, structuredBytes, success, TextWindowSchema } from "./result.js";
7
+ import { nullableString, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
8
+ const ORIGIN_VALUES = [Type.Literal("user"), Type.Literal("self"), Type.Literal("external")];
9
+ const ORIGIN = Type.Optional(Type.Union([...ORIGIN_VALUES], {
10
+ description: "Content source: user, self (default), or external.",
11
+ }));
12
+ const CRUMPLED_PARAMETER = Type.Optional(Type.Boolean({ description: "true crumples (archives) the note: hidden from list/search, still readable by address; false restores it." }));
13
+ const WASTEBASKET_PARAMETER = Type.Optional(Type.Boolean({ description: "true lists only crumpled notes instead of live ones." }));
14
+ const FILE_LIMIT_PARAMETER = Type.Optional(Type.Integer({ minimum: 1, description: "Max files (default: as many as fit the output budget)." }));
15
+ const ADDRESS_DESCRIPTION = "Addresses: <path> with no @ for this session; @project/, @human/, @self/, @model/ for durable homes (see /skill:memory). Never pass them to filesystem tools.";
16
+ /** The one receipt field a caller cannot derive from the address itself. */
17
+ function projectKeyField(scope, projectKey) {
18
+ return scope === "project" ? { project_key: projectKey } : {};
19
+ }
20
+ const MAX_ERROR_LINE_FACTS = 20;
21
+ /**
22
+ * Typed refusal. Edit locations keep their precise line/edit facts in `details`.
23
+ * Convert expected refusals; unexpected errors propagate unchanged.
24
+ */
25
+ function failureOf(error) {
26
+ if (error instanceof NoteError) {
27
+ const details = {};
28
+ let message = error.message;
29
+ if (error.lineNumbers) {
30
+ if (error.lineNumbers.length > MAX_ERROR_LINE_FACTS) {
31
+ details.line_numbers = error.lineNumbers.slice(0, MAX_ERROR_LINE_FACTS);
32
+ details.line_numbers_total = error.lineNumbers.length;
33
+ message = `${message} (this refusal names ${MAX_ERROR_LINE_FACTS} of ${error.lineNumbers.length} match lines; the note is unchanged)`;
34
+ }
35
+ else {
36
+ details.line_numbers = error.lineNumbers;
37
+ }
38
+ }
39
+ if (error.editIndex !== undefined)
40
+ details.edit_index = error.editIndex;
41
+ return failure(error.code, message, Object.keys(details).length > 0 ? details : undefined);
42
+ }
43
+ // Address, pattern, and query guards raise declared types; nothing else is converted.
44
+ if (error instanceof InvalidQueryError)
45
+ return failure("invalid_query", error.message);
46
+ if (isFilesystemError(error))
47
+ return failure("io_error", "notes operation failed");
48
+ throw error;
49
+ }
50
+ function byRecent(a, b) {
51
+ return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
52
+ }
53
+ /** Metadata keys this layer normalizes; everything else is exposed verbatim under `extra`. */
54
+ const NORMALIZED_META_KEYS = new Set(["scope", "origin", "createdAt", "updatedAt", "lastAccessed", "accessCount", "crumpledAt", "project"]);
55
+ /** One unrecognized entry, and all of them together, are bounded; omissions are counted, never listed. */
56
+ export const MAX_METADATA_ENTRY_BYTES = 1024;
57
+ const MAX_METADATA_EXTRA_BYTES = 2048;
58
+ /** Include the key: hand-written frontmatter can have arbitrarily long keys. */
59
+ function extraEntryBytes(key, value) {
60
+ return structuredBytes(key) + 1 + structuredBytes(value);
61
+ }
62
+ export const NoteMetadataSchema = Type.Object({
63
+ origin: Type.Union([...ORIGIN_VALUES]),
64
+ created_at: Type.String(),
65
+ updated_at: Type.String(),
66
+ crumpled_at: Type.Optional(Type.String()),
67
+ project: Type.Optional(Type.String()),
68
+ extra: Type.Record(Type.String(), Type.Unknown()),
69
+ /** Values left in the file but too large to show, summarized so the summary cannot grow. */
70
+ omitted_extra: Type.Optional(Type.Object({ keys: Type.Integer(), bytes: Type.Integer() })),
71
+ });
72
+ /** Normalize known metadata and bound extras without partially serializing their values. */
73
+ function noteMetadata(meta) {
74
+ const extra = {};
75
+ let extraBytes = 0;
76
+ let omittedKeys = 0;
77
+ let omittedBytes = 0;
78
+ for (const [key, value] of Object.entries(meta)) {
79
+ if (NORMALIZED_META_KEYS.has(key) || value === undefined)
80
+ continue;
81
+ const bytes = extraEntryBytes(key, value);
82
+ if (bytes > MAX_METADATA_ENTRY_BYTES || extraBytes + bytes > MAX_METADATA_EXTRA_BYTES) {
83
+ omittedKeys++;
84
+ omittedBytes += bytes;
85
+ continue;
86
+ }
87
+ extraBytes += bytes;
88
+ // defineProperty keeps a hand-written `__proto__` key as ordinary data.
89
+ Object.defineProperty(extra, key, { value, enumerable: true, writable: true, configurable: true });
90
+ }
91
+ return {
92
+ origin: meta.origin,
93
+ created_at: localIso(meta.createdAt),
94
+ updated_at: localIso(meta.updatedAt),
95
+ ...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
96
+ ...(typeof meta.project === "string" ? { project: meta.project } : {}),
97
+ extra,
98
+ ...(omittedKeys > 0 ? { omitted_extra: { keys: omittedKeys, bytes: omittedBytes } } : {}),
99
+ };
100
+ }
101
+ function renderMetadata(metadata) {
102
+ const fields = [
103
+ `origin ${metadata.origin}`,
104
+ `created ${metadata.created_at}`,
105
+ `updated ${metadata.updated_at}`,
106
+ ...(metadata.crumpled_at === undefined ? [] : [`crumpled ${metadata.crumpled_at}`]),
107
+ ...(metadata.project === undefined ? [] : [`project ${metadata.project}`]),
108
+ ];
109
+ const extra = Object.keys(metadata.extra);
110
+ if (extra.length > 0)
111
+ fields.push(`extra ${JSON.stringify(metadata.extra)}`);
112
+ if (metadata.omitted_extra !== undefined)
113
+ fields.push(`${metadata.omitted_extra.keys} more metadata values (${metadata.omitted_extra.bytes} bytes) are in the note file but too large to show`);
114
+ return fields.join(" | ");
115
+ }
116
+ /** Address plus project key in one line; the project key never replaces the address. */
117
+ function renderIdentity(identity) {
118
+ return identity.project_key === undefined ? identity.address : `${identity.address} (project ${identity.project_key})`;
119
+ }
120
+ const ListedFileSchema = Type.Object({
121
+ address: Type.String(),
122
+ project_key: Type.Optional(Type.String()),
123
+ updated_at: Type.String(),
124
+ crumpled_at: Type.Optional(Type.String()),
125
+ });
126
+ const MatchSchema = Type.Object({
127
+ line: Type.Integer(),
128
+ text: Type.String(),
129
+ truncated: Type.Boolean(),
130
+ offset_chars: Type.Integer(),
131
+ });
132
+ const SearchedFileSchema = Type.Object({
133
+ ...ListedFileSchema.properties,
134
+ matches_total: Type.Integer(),
135
+ matches: Type.Array(MatchSchema),
136
+ });
137
+ const SnapshotSchema = {
138
+ more: Type.Integer(),
139
+ crumpled_excluded: Type.Integer(),
140
+ homes_unavailable: Type.Array(Type.String()),
141
+ };
142
+ export const NotesWriteDataSchema = Type.Object({
143
+ address: Type.String(),
144
+ project_key: Type.Optional(Type.String()),
145
+ outcome: Type.Union([Type.Literal("created"), Type.Literal("overwrote"), Type.Literal("uncrumpled")]),
146
+ });
147
+ export const NotesUpdateDataSchema = Type.Object({
148
+ address: Type.String(),
149
+ project_key: Type.Optional(Type.String()),
150
+ applied: Type.Integer(),
151
+ change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("file")]),
152
+ diff: Type.String(),
153
+ diff_truncated: Type.Optional(Type.Literal(true)),
154
+ rename_from: Type.Optional(Type.String()),
155
+ replaced_crumpled_target: Type.Optional(Type.Boolean()),
156
+ });
157
+ export const NotesReadDataSchema = Type.Object({
158
+ address: Type.String(),
159
+ project_key: Type.Optional(Type.String()),
160
+ metadata: NoteMetadataSchema,
161
+ ...TextWindowSchema.properties,
162
+ });
163
+ export const NotesListDataSchema = Type.Object({
164
+ files: Type.Array(ListedFileSchema),
165
+ ...SnapshotSchema,
166
+ });
167
+ export const NotesSearchDataSchema = Type.Object({
168
+ files: Type.Array(SearchedFileSchema),
169
+ ...SnapshotSchema,
170
+ });
171
+ /** Keep identities intact. Only search previews may shrink to make the first row fit. */
172
+ function snapshot(rows, limit, status, renderData, shrink) {
173
+ const files = [];
174
+ const data = (selected) => ({ files: selected, more: rows.length - selected.length, crumpled_excluded: status.crumpledExcluded, homes_unavailable: status.homesUnavailable });
175
+ const render = (outcome) => renderOutcome(outcome, renderData);
176
+ const fits = (item) => fitsResult(success(data([...files, item])), render);
177
+ for (const item of rows.slice(0, limit)) {
178
+ if (fits(item)) {
179
+ files.push(item);
180
+ continue;
181
+ }
182
+ if (files.length === 0 && shrink) {
183
+ const reduced = shrink(item, fits);
184
+ if (fits(reduced))
185
+ files.push(reduced);
186
+ }
187
+ if (files.length === 0)
188
+ return failure("output_too_large", "The first matching note cannot fit in a response without losing its identity.");
189
+ break;
190
+ }
191
+ const outcome = success(data(files));
192
+ return fitsResult(outcome, render) ? outcome : failure("output_too_large", "The notes snapshot metadata exceeds the response budget.");
193
+ }
194
+ function listedFile(row, identity) {
195
+ return { address: row.address, ...projectKeyField(row.scope, identity.projectKey), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
196
+ }
197
+ export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN }, { additionalProperties: false });
198
+ function renderWriteData(data) {
199
+ return `${data.outcome} ${renderIdentity(data)}`;
200
+ }
201
+ export const notesWrite = {
202
+ name: "notes_write", label: "Notes write",
203
+ description: `Create or replace a note body, preserving metadata; uncrumples a crumpled note. Name it for its contents and when to use it. Store what git/history cannot recover. ${ADDRESS_DESCRIPTION}`,
204
+ parameters: notesWriteParameters, outputSchema: resultSchema(NotesWriteDataSchema), executionMode: "sequential",
205
+ async execute(params, identity) {
206
+ try {
207
+ const { outcome } = await createNotesStore(identity).write(params.address, params.content, { origin: params.origin ?? "self" });
208
+ return success({ ...noteIdentity(identity, params.address), outcome });
209
+ }
210
+ catch (error) {
211
+ return failureOf(error);
212
+ }
213
+ },
214
+ render: (result) => renderOutcome(result, renderWriteData),
215
+ };
216
+ export const notesUpdateParameters = Type.Object({ address: Type.String(), edits: Type.Optional(Type.Array(Type.Object({ oldText: Type.String(), newText: Type.String() }, { additionalProperties: false }))), origin: ORIGIN, crumpled: CRUMPLED_PARAMETER, replace_all: Type.Optional(Type.Boolean()), rename_to: Type.Optional(Type.String({ description: "Move, preserving metadata. Use alone. Refuses live targets; may replace crumpled targets. References are not updated. Empty string is ignored." })) }, { additionalProperties: false });
217
+ function renderUpdateData(data) {
218
+ const head = data.rename_from === undefined
219
+ ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}: ${data.applied} ${data.applied === 1 ? "edit" : "edits"}`
220
+ : `moved ${data.rename_from} -> ${data.address}${data.replaced_crumpled_target === true ? " (replaced a crumpled note)" : ""}`;
221
+ const lines = [head];
222
+ if (data.diff_truncated === true)
223
+ lines.push("diff (this receipt's diff was shortened to fit the output budget; the update itself was applied):");
224
+ else if (data.diff.length > 0)
225
+ lines.push("diff:");
226
+ if (data.diff.length > 0)
227
+ lines.push(data.diff);
228
+ return lines.join("\n");
229
+ }
230
+ function renderUpdate(result) {
231
+ return renderOutcome(result, renderUpdateData);
232
+ }
233
+ /** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix. */
234
+ function boundedUpdate(data) {
235
+ if (fitsResult(success(data), renderUpdate))
236
+ return success(data);
237
+ const shortened = { ...data, diff_truncated: true };
238
+ const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...shortened, diff: candidate }), renderUpdate));
239
+ const result = success({ ...shortened, diff });
240
+ return fitsResult(result, renderUpdate) ? result : failure("output_too_large", "The update was applied, but its receipt metadata exceeds the response budget.");
241
+ }
242
+ export const notesUpdate = {
243
+ name: "notes_update", label: "Notes update",
244
+ description: `Edit body text, change origin or crumpled state, or move a note. Each oldText must match once unless replace_all is true; edits cannot change frontmatter. Metadata-only updates need origin or crumpled. Returns applied changes and a bounded diff. ${ADDRESS_DESCRIPTION}`,
245
+ parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
246
+ async execute(params, identity, renderDiff) {
247
+ try {
248
+ const store = createNotesStore(identity);
249
+ // Empty filler is not a request: models that pass every parameter get the edit path.
250
+ const renameTo = params.rename_to === "" ? undefined : params.rename_to;
251
+ if (renameTo !== undefined) {
252
+ if ((params.edits?.length ?? 0) > 0 || params.origin !== undefined || params.crumpled !== undefined || params.replace_all === true) {
253
+ return failureOf(new NoteError("invalid_scope", "rename_to is used alone: do not combine it with edits, origin, crumpled, or replace_all"));
254
+ }
255
+ const { replacedCrumpledTarget } = await store.rename(params.address, renameTo);
256
+ const from = noteIdentity(identity, params.address).address;
257
+ const to = noteIdentity(identity, renameTo);
258
+ return boundedUpdate({ ...to, rename_from: from, applied: 0, change_kind: "file", diff: `rename ${from} -> ${to.address}`, replaced_crumpled_target: replacedCrumpledTarget });
259
+ }
260
+ const { applied, change } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all });
261
+ return boundedUpdate({ ...noteIdentity(identity, params.address), applied, change_kind: change.kind, diff: renderDiff(change) });
262
+ }
263
+ catch (error) {
264
+ return failureOf(error);
265
+ }
266
+ },
267
+ render: renderUpdate,
268
+ };
269
+ export const notesReadParameters = Type.Object({ address: Type.String(), offset_chars: Type.Optional(Type.Integer({ description: "Body code-point offset (default 0); negative counts from EOF." })), limit_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `Max code points (default ${DEFAULT_READ_WINDOW_CHARS}); also bounded by output bytes.` })) }, { additionalProperties: false });
270
+ function renderReadData(data) {
271
+ return `${renderIdentity(data)}\n${renderMetadata(data.metadata)}\n\n${renderTextWindow(data)}`;
272
+ }
273
+ export const notesRead = {
274
+ name: "notes_read", label: "Notes read",
275
+ description: `Read note metadata and a verbatim body slice, excluding frontmatter. Pass next_offset_chars as offset_chars until null. ${ADDRESS_DESCRIPTION}`,
276
+ parameters: notesReadParameters, outputSchema: resultSchema(NotesReadDataSchema),
277
+ async execute(params, identity) {
278
+ try {
279
+ const note = await createNotesStore(identity).read(params.address);
280
+ if (!note)
281
+ return failure("not_found", "note not found");
282
+ const totalChars = Array.from(note.body).length;
283
+ if (params.offset_chars !== undefined && params.offset_chars > totalChars)
284
+ return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end of the body: the note has ${totalChars} body chars; the largest legal offset is ${totalChars} (an empty end-read)`);
285
+ const resolved = noteIdentity(identity, params.address);
286
+ const metadata = noteMetadata(note.meta);
287
+ return readTextWindow(note.body, params.offset_chars, params.limit_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
288
+ }
289
+ catch (error) {
290
+ return failureOf(error);
291
+ }
292
+ },
293
+ render: (result) => renderOutcome(result, renderReadData),
294
+ };
295
+ export const notesListParameters = Type.Object({ pattern: nullableString(), limit: FILE_LIMIT_PARAMETER, wastebasket: WASTEBASKET_PARAMETER }, { additionalProperties: false });
296
+ function renderListData(data) {
297
+ const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
298
+ for (const file of data.files) {
299
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
300
+ }
301
+ if (data.more > 0)
302
+ lines.push(`${data.more} more matching notes omitted; narrow with pattern`);
303
+ if (data.crumpled_excluded > 0)
304
+ lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to list them`);
305
+ for (const home of data.homes_unavailable)
306
+ lines.push(`${home} could not be read`);
307
+ return lines.join("\n");
308
+ }
309
+ export const notesList = {
310
+ name: "notes_list", label: "Notes list",
311
+ description: `List notes in the session and the four @ homes, newest first. Snapshot, not pageable: more counts omitted files; pattern globs full addresses. Reports unavailable homes and how many crumpled notes were excluded. ${ADDRESS_DESCRIPTION}`,
312
+ parameters: notesListParameters, outputSchema: resultSchema(NotesListDataSchema),
313
+ async execute(params, identity) {
314
+ try {
315
+ const { rows, status } = await createNotesStore(identity).listWithStatus({ pattern: params.pattern ?? undefined, wastebasket: params.wastebasket });
316
+ return snapshot(rows.map(row => listedFile(row, identity)), params.limit, status, renderListData);
317
+ }
318
+ catch (error) {
319
+ return failureOf(error);
320
+ }
321
+ },
322
+ render: (result) => renderOutcome(result, renderListData),
323
+ };
324
+ export const notesSearchParameters = Type.Object({ query: searchQuery(), pattern: nullableString(), limit: FILE_LIMIT_PARAMETER, max_matches_per_file: Type.Optional(Type.Integer({ minimum: 1, description: "Max matches shown per file (default: no cap); matches_total still counts all." })), wastebasket: WASTEBASKET_PARAMETER }, { additionalProperties: false });
325
+ function renderSearchData(data) {
326
+ const lines = [`${data.files.length} ${data.files.length === 1 ? "file" : "files"}`];
327
+ for (const file of data.files) {
328
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | ${file.matches_total} ${file.matches_total === 1 ? "match" : "matches"}${file.matches.length < file.matches_total ? ` (${file.matches.length} shown)` : ""}`);
329
+ for (const match of file.matches)
330
+ lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}${match.truncated ? " [line shortened]" : ""}`);
331
+ }
332
+ if (data.more > 0)
333
+ lines.push(`${data.more} more matching files omitted; narrow with pattern`);
334
+ if (data.crumpled_excluded > 0)
335
+ lines.push(`${data.crumpled_excluded} crumpled notes hidden; pass wastebasket to search them`);
336
+ for (const home of data.homes_unavailable)
337
+ lines.push(`${home} could not be read`);
338
+ return lines.join("\n");
339
+ }
340
+ /** Prefer whole match lines; shorten the first line only if no whole line fits. */
341
+ function fitSearchFile(file, fits) {
342
+ let low = 0;
343
+ let high = file.matches.length;
344
+ while (low < high) {
345
+ const mid = Math.ceil((low + high) / 2);
346
+ if (fits({ ...file, matches: file.matches.slice(0, mid) }))
347
+ low = mid;
348
+ else
349
+ high = mid - 1;
350
+ }
351
+ if (low > 0)
352
+ return { ...file, matches: file.matches.slice(0, low) };
353
+ const first = file.matches[0];
354
+ if (!first)
355
+ return file;
356
+ const withText = (text) => ({ ...file, matches: [{ ...first, text, truncated: true }] });
357
+ return withText(prefixFit(first.text, text => fits(withText(text))));
358
+ }
359
+ export const notesSearch = {
360
+ name: "notes_search", label: "Notes search",
361
+ description: `Search note bodies for case-insensitive literal queries (OR). Returns matching lines and body code-point offsets for notes_read. Snapshot, not pageable: more counts omitted files; matches_total is before per-file capping. pattern globs full addresses across the session and the four @ homes. ${ADDRESS_DESCRIPTION}`,
362
+ parameters: notesSearchParameters, outputSchema: resultSchema(NotesSearchDataSchema),
363
+ async execute(params, identity) {
364
+ try {
365
+ const { rows, status } = await createNotesStore(identity).searchWithStatus(searchQueries(params.query), { pattern: params.pattern ?? undefined, wastebasket: params.wastebasket });
366
+ const files = rows.sort(byRecent).map(row => ({
367
+ ...listedFile(row, identity),
368
+ matches_total: row.matches.length,
369
+ matches: row.matches.slice(0, params.max_matches_per_file).map(match => ({ line: match.line, text: match.text, truncated: false, offset_chars: match.offsetChars })),
370
+ }));
371
+ return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
372
+ }
373
+ catch (error) {
374
+ return failureOf(error);
375
+ }
376
+ },
377
+ render: (result) => renderOutcome(result, renderSearchData),
378
+ };