neuralbrain 0.0.2 → 0.1.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 (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +1 -1
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
package/src/lib/scope.ts CHANGED
@@ -10,6 +10,8 @@
10
10
  *
11
11
  * 1. Normalise what is unambiguous — case and surrounding whitespace, and
12
12
  * internal whitespace to '-'. These are spellings of one name.
13
+ * Hierarchical subprojects use '/' to separate segments (e.g.
14
+ * 'acme/socials/calendar').
13
15
  *
14
16
  * 2. REJECT what would require a guess. A filesystem path is the obvious
15
17
  * case: turning '/home/user/Projects/Foo' into 'foo' is inference, it
@@ -24,15 +26,29 @@
24
26
  * see what it actually wrote.
25
27
  */
26
28
 
27
- export const PROJECT_ID_MAX_LENGTH = 128;
29
+ export const PROJECT_ID_MAX_LENGTH = 256;
28
30
 
29
- /** Lowercase alphanumerics plus dot, underscore and hyphen. */
31
+ /** Lowercase alphanumerics plus dot, underscore and hyphen (per segment). */
30
32
  const PROJECT_ID_ALLOWED = /^[a-z0-9._-]+$/;
31
33
 
34
+ /** Windows drive prefix like C:/ or d:/ */
35
+ const WINDOWS_DRIVE_PREFIX = /^[a-zA-Z]:\//;
36
+
32
37
  export type ProjectIdResult =
33
38
  | { ok: true; projectId: string }
34
39
  | { ok: false; error: string };
35
40
 
41
+ function pathRejectionError(trimmed: string): ProjectIdResult {
42
+ return {
43
+ ok: false,
44
+ error:
45
+ `project_id '${trimmed}' looks like a path. Send a stable identifier ` +
46
+ `(e.g. 'neuralbrain' or 'acme/app'), not a filesystem path: use the project_id ` +
47
+ `set in .brainrc (which wins over the folder name), else the project root folder ` +
48
+ `name (git repo root; main repo for a worktree), never a subfolder, so all agents come up with the same id.`,
49
+ };
50
+ }
51
+
36
52
  export function normalizeProjectId(raw: unknown): ProjectIdResult {
37
53
  if (typeof raw !== 'string') {
38
54
  return { ok: false, error: 'project_id must be a string' };
@@ -43,33 +59,57 @@ export function normalizeProjectId(raw: unknown): ProjectIdResult {
43
59
  return { ok: false, error: 'project_id must not be empty' };
44
60
  }
45
61
 
46
- // Reject rather than derive. See rule 2 in the header.
47
- if (trimmed.includes('/') || trimmed.includes('\\')) {
48
- return {
49
- ok: false,
50
- error:
51
- `project_id '${trimmed}' looks like a path. Send a stable identifier ` +
52
- `(e.g. 'neuralbrain'), not a filesystem path: use the project root ` +
53
- `folder name (from .brainrc, else the git repo root; the main repo for a worktree), ` +
54
- `never a subfolder, so all agents come up with the same id.`,
55
- };
62
+ // Reject filesystem paths rather than deriving. See rule 2 in the header.
63
+ if (
64
+ trimmed.startsWith('/') ||
65
+ trimmed.includes('\\') ||
66
+ WINDOWS_DRIVE_PREFIX.test(trimmed) ||
67
+ trimmed.startsWith('~') ||
68
+ trimmed === '.' ||
69
+ trimmed === '..' ||
70
+ trimmed.startsWith('./') ||
71
+ trimmed.startsWith('../')
72
+ ) {
73
+ return pathRejectionError(trimmed);
56
74
  }
57
75
 
58
- const normalized = trimmed.toLowerCase().replace(/\s+/g, '-');
76
+ // Trim trailing slashes and collapse consecutive slashes into single '/'
77
+ const cleaned = trimmed.replace(/\/+$/, '').replace(/\/{2,}/g, '/');
78
+ if (cleaned === '') {
79
+ return pathRejectionError(trimmed);
80
+ }
59
81
 
60
- if (normalized.length > PROJECT_ID_MAX_LENGTH) {
61
- return {
62
- ok: false,
63
- error: `project_id must be ${PROJECT_ID_MAX_LENGTH} characters or fewer (got ${normalized.length})`,
64
- };
82
+ const rawSegments = cleaned.split('/');
83
+ const normalizedSegments: string[] = [];
84
+
85
+ for (const rawSeg of rawSegments) {
86
+ const seg = rawSeg.trim().toLowerCase().replace(/\s+/g, '-');
87
+ if (seg === '') {
88
+ return {
89
+ ok: false,
90
+ error: `project_id '${trimmed}' contains an empty path segment.`,
91
+ };
92
+ }
93
+ if (seg === '.' || seg === '..') {
94
+ return pathRejectionError(trimmed);
95
+ }
96
+ if (!PROJECT_ID_ALLOWED.test(seg)) {
97
+ return {
98
+ ok: false,
99
+ error:
100
+ `project_id '${trimmed}' contains unsupported characters. Allowed after ` +
101
+ `normalisation: lowercase letters, digits, '.', '_' and '-' (with '/' separating hierarchy segments).`,
102
+ };
103
+ }
104
+ normalizedSegments.push(seg);
65
105
  }
66
106
 
67
- if (!PROJECT_ID_ALLOWED.test(normalized)) {
107
+ const normalized = normalizedSegments.join('/');
108
+
109
+ if (normalized.length > PROJECT_ID_MAX_LENGTH) {
68
110
  return {
69
111
  ok: false,
70
- error:
71
- `project_id '${trimmed}' contains unsupported characters. Allowed after ` +
72
- `normalisation: lowercase letters, digits, '.', '_' and '-'.`,
112
+ error: `project_id must be ${PROJECT_ID_MAX_LENGTH} characters or fewer (got ${normalized.length})`,
73
113
  };
74
114
  }
75
115
 
@@ -119,3 +159,161 @@ export function resolveScope(
119
159
 
120
160
  return { ok: true, scope, projectId: null };
121
161
  }
162
+
163
+ /**
164
+ * Returns every ancestor prefix from root down to the project itself.
165
+ * e.g. 'acme/socials/calendar' -> ['acme', 'acme/socials', 'acme/socials/calendar'].
166
+ */
167
+ export function getProjectAncestors(projectId: string): string[] {
168
+ const norm = normalizeProjectId(projectId);
169
+ const clean = norm.ok
170
+ ? norm.projectId
171
+ : projectId.trim().replace(/\/+$/, '').replace(/\/{2,}/g, '/');
172
+ if (!clean) return [];
173
+
174
+ const parts = clean.split('/').filter(Boolean);
175
+ const ancestors: string[] = [];
176
+ for (let i = 0; i < parts.length; i++) {
177
+ ancestors.push(parts.slice(0, i + 1).join('/'));
178
+ }
179
+ return ancestors;
180
+ }
181
+
182
+ /**
183
+ * Exact ASCII B-tree index range scan bounds for strict descendants of `projectId`.
184
+ * '/' is ASCII 47 and '0' is ASCII 48, so `project_id >= '${id}/' AND project_id < '${id}0'`
185
+ * matches all children without LIKE wildcard issues and uses B-tree indexes directly.
186
+ */
187
+ export function getProjectChildRange(projectId: string): { gte: string; lt: string } {
188
+ const norm = normalizeProjectId(projectId);
189
+ const clean = norm.ok ? norm.projectId : projectId.trim().replace(/\/+$/, '');
190
+ return { gte: `${clean}/`, lt: `${clean}0` };
191
+ }
192
+
193
+ export type MatchTier = 'exact' | 'ancestor' | 'child' | 'global' | 'unknown';
194
+
195
+ export function classifyMatchTier(
196
+ rowScope: string,
197
+ rowProjectId: string | null | undefined,
198
+ queryProjectId?: string | null
199
+ ): { match_tier: MatchTier; ancestor_distance?: number } {
200
+ if (rowScope === 'global') {
201
+ return { match_tier: 'global' };
202
+ }
203
+ if (rowScope !== 'project' || !rowProjectId) {
204
+ return { match_tier: 'unknown' };
205
+ }
206
+ if (!queryProjectId || !queryProjectId.trim()) {
207
+ return { match_tier: 'exact' };
208
+ }
209
+
210
+ const queryRes = normalizeProjectId(queryProjectId);
211
+ const rowRes = normalizeProjectId(rowProjectId);
212
+ const queryNorm = queryRes.ok ? queryRes.projectId : queryProjectId.trim();
213
+ const rowNorm = rowRes.ok ? rowRes.projectId : rowProjectId.trim();
214
+
215
+ if (rowNorm === queryNorm) {
216
+ return { match_tier: 'exact' };
217
+ }
218
+ if (queryNorm.startsWith(`${rowNorm}/`)) {
219
+ const ancestorDistance = queryNorm.split('/').length - rowNorm.split('/').length;
220
+ return { match_tier: 'ancestor', ancestor_distance: ancestorDistance };
221
+ }
222
+ if (rowNorm.startsWith(`${queryNorm}/`)) {
223
+ return { match_tier: 'child' };
224
+ }
225
+ return { match_tier: 'exact' };
226
+ }
227
+
228
+ export interface HierarchicalScopeSqlOptions {
229
+ tableAlias?: string;
230
+ scope?: string;
231
+ projectId?: string | null;
232
+ includeAncestors?: boolean;
233
+ includeChildren?: boolean;
234
+ includeGlobal?: boolean;
235
+ userId?: string | null;
236
+ }
237
+
238
+ export function buildHierarchicalScopeSql(options: HierarchicalScopeSqlOptions): {
239
+ clause: string;
240
+ params: unknown[];
241
+ normalizedProjectId: string | null;
242
+ } {
243
+ const includeAncestors = options.includeAncestors ?? true;
244
+ const includeChildren = options.includeChildren ?? false;
245
+ const includeGlobal = options.includeGlobal ?? true;
246
+
247
+ const prefix = options.tableAlias ? `${options.tableAlias}.` : '';
248
+ const colScope = `${prefix}scope`;
249
+ const colProject = `${prefix}project_id`;
250
+ const colUser = `${prefix}user_id`;
251
+
252
+ let normalizedProjectId: string | null = null;
253
+ if (typeof options.projectId === 'string' && options.projectId.trim() !== '') {
254
+ const norm = normalizeProjectId(options.projectId);
255
+ normalizedProjectId = norm.ok ? norm.projectId : options.projectId.trim();
256
+ }
257
+
258
+ const cleanUserId =
259
+ typeof options.userId === 'string' && options.userId.trim() !== ''
260
+ ? options.userId.trim()
261
+ : null;
262
+
263
+ const params: unknown[] = [];
264
+ let scopeClause: string;
265
+
266
+ if (options.scope === 'unknown') {
267
+ scopeClause = `${colScope} = 'unknown'`;
268
+ } else if (options.scope === 'global') {
269
+ scopeClause = `${colScope} = 'global'`;
270
+ } else if (normalizedProjectId !== null) {
271
+ const projParts: string[] = [];
272
+ if (includeAncestors) {
273
+ const ancestors = getProjectAncestors(normalizedProjectId);
274
+ const placeholders = ancestors.map(() => '?').join(', ');
275
+ projParts.push(`${colProject} IN (${placeholders})`);
276
+ params.push(...ancestors);
277
+ } else {
278
+ projParts.push(`${colProject} = ?`);
279
+ params.push(normalizedProjectId);
280
+ }
281
+
282
+ if (includeChildren) {
283
+ const range = getProjectChildRange(normalizedProjectId);
284
+ projParts.push(`(${colProject} >= ? AND ${colProject} < ?)`);
285
+ params.push(range.gte, range.lt);
286
+ }
287
+
288
+ const projExpr = projParts.join(' OR ');
289
+ const projectBranch = `(${colScope} = 'project' AND (${projExpr}))`;
290
+ scopeClause = includeGlobal
291
+ ? `(${projectBranch} OR ${colScope} = 'global')`
292
+ : projectBranch;
293
+ } else if (options.scope === 'project') {
294
+ scopeClause = includeGlobal
295
+ ? `(${colScope} = 'project' OR ${colScope} = 'global')`
296
+ : `${colScope} = 'project'`;
297
+ } else {
298
+ scopeClause = includeGlobal ? `${colScope} = 'global'` : '1 = 0';
299
+ }
300
+
301
+ if (cleanUserId !== null) {
302
+ const wrapped =
303
+ scopeClause.startsWith('(') && scopeClause.endsWith(')')
304
+ ? scopeClause
305
+ : `(${scopeClause})`;
306
+ params.push(cleanUserId);
307
+ return {
308
+ clause: `${wrapped} AND ${colUser} = ?`,
309
+ params,
310
+ normalizedProjectId,
311
+ };
312
+ }
313
+
314
+ return {
315
+ clause: scopeClause,
316
+ params,
317
+ normalizedProjectId,
318
+ };
319
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Deterministic, zero-dependency linguistic signal tagger and query-intent detector.
3
+ *
4
+ * Extracts universal conversational and coding memory signals (`preference`,
5
+ * `state_update`, `completed_action`, `planned_action`) at capture time in strictly
6
+ * bounded O(N) time without mutating raw `observations.input` or `observations.output`,
7
+ * and detects preference / current-state query intent at retrieval time.
8
+ */
9
+
10
+ import { safeUtf16Slice, splitIntoPassages } from './condenser';
11
+
12
+ export type SignalTag =
13
+ | 'preference'
14
+ | 'state_update'
15
+ | 'completed_action'
16
+ | 'planned_action';
17
+
18
+ export const SIGNAL_TAG_ORDER: readonly SignalTag[] = [
19
+ 'preference',
20
+ 'state_update',
21
+ 'completed_action',
22
+ 'planned_action',
23
+ ];
24
+
25
+ export const MAX_SIGNAL_SCAN_CHARS = 8_000;
26
+ const MAX_SIGNAL_SCAN_PASSAGES = 60;
27
+ const MAX_CONCISE_SUMMARY_CHARS = 400;
28
+ const MAX_QUERY_INTENT_SCAN_CHARS = 4_000;
29
+
30
+ export interface ExtractSignalTagsInput {
31
+ kind: 'prompt' | 'response' | 'tool_call' | string;
32
+ input?: string | null;
33
+ output?: string | null;
34
+ }
35
+
36
+ export interface QuerySignalIntent {
37
+ wantsPreference: boolean;
38
+ wantsStateUpdate: boolean;
39
+ }
40
+
41
+ const LEADING_LIST_MARKER_RE = /^\s{0,8}(?:[-*+>]|\d{1,3}[.)])\s{1,4}/;
42
+ const QUESTION_END_RE = /\?['"”’)\]}]{0,4}$/;
43
+
44
+ const INTERROGATIVE_START_RE =
45
+ /^(?:what|which|who|where|when|why|how|do|does|did|is|are|was|were|can|could|should|would|will|have|has)\b/i;
46
+
47
+ const IMPERATIVE_DO_NOT_START_RE = /^do\s{1,3}not\b/i;
48
+
49
+ const SUBORDINATE_WHEN_WHERE_RE =
50
+ /^(?:when|where)\s{1,3}(?!do\b|does\b|did\b|is\b|are\b|was\b|were\b|can\b|could\b|should\b|would\b|will\b|have\b|has\b)/i;
51
+
52
+ const DECLARATIVE_AFTER_COMMA_RE =
53
+ /,\s{1,3}(?:i['’]?(?:m|ve|d)?\b|we['’]?(?:re|ve|d)?\b|my\b|our\b|please\b|always\b|never\b|now\b)/i;
54
+
55
+ const CONDITIONAL_OR_NEGATED_PREFIX_RE =
56
+ /(?:n['’]t|\b(?:if|whether|unless|you|your|they|he|she|not|never|no))\s{1,3}$/i;
57
+
58
+ const CONDITIONAL_CLAUSE_PREFIX_RE = /\b(?:if|whether|unless)\s{1,3}$/i;
59
+
60
+ const PLANNED_BLOCKED_PREFIX_RE =
61
+ /(?:n['’]t|\b(?:if|whether|unless|not|never|no))\s{1,3}$/i;
62
+
63
+ const ASSISTANT_META_CHATTER_RE =
64
+ /\b(?:going\s{1,3}to\s{1,3}(?:explain|walk|show|list|outline|cover|help|break|share|summarize|discuss|provide)|if\s{1,3}you\b|for\s{1,3}example\b|you\s{1,3}(?:can|could|might|may|should)\b|now\s{1,3}we\s{1,3}have\s{1,3}(?:a\s{1,3}|some\s{1,3}|two\s{1,3}|three\s{1,3}|several\s{1,3})?(?:options?|ways?|steps?|approaches?)\b)/i;
65
+
66
+ const PREFERENCE_COMBINED_RE = new RegExp(
67
+ [
68
+ String.raw`\b(?:i|we)\s{1,3}(?:really\s{1,3}|strongly\s{1,3}|generally\s{1,3}|usually\s{1,3}|always\s{1,3})?(?:prefer|like|love|enjoy|hate|dislike|avoid|stick\s{1,3}to|favou?r)\b`,
69
+ String.raw`\b(?:i['’]d|i\s{1,3}would|we['’]d|we\s{1,3}would)\s{1,3}rather\b`,
70
+ String.raw`\b(?:always|never)\s{1,3}use\b`,
71
+ String.raw`\b(?:please\s{1,3})?(?:do\s{1,3}not|don['’]t)\s{1,3}use\b`,
72
+ String.raw`\b(?:my|our)\s{1,3}(?:favou?rite|preferred|go-to|usual)\b`,
73
+ String.raw`\bskip\s{1,3}the\s{1,3}basics\b`,
74
+ ].join('|'),
75
+ 'i'
76
+ );
77
+
78
+ const STATE_UPDATE_SUBJECTLESS_RE =
79
+ /\b(?:(?:i|we|our\s{1,3}team)\s{1,3})?(?:just\s{1,3}|recently\s{1,3})?(?:switched|migrated|moved|transitioned|upgraded|updated|downgraded)\s{1,3}(?:to|from)\b/i;
80
+
81
+ const STATE_UPDATE_OTHER_RE = new RegExp(
82
+ [
83
+ String.raw`\bchanged\s{1,3}from\b`,
84
+ String.raw`\bno\s{1,3}longer\s{1,3}(?:use|using|work|working|live|living|have|do|doing|support|supporting)\b`,
85
+ String.raw`\bstopped\s{1,3}(?:using|doing|taking|going)\b`,
86
+ String.raw`\breplaced\s{1,3}[` + '`' + String.raw`'"a-zA-Z0-9_./-]{1,40}\s{1,3}with\b`,
87
+ String.raw`\bnow\s{1,3}(?:i|we)\s{1,3}(?:use|live|work|run|prefer|have)\b`,
88
+ String.raw`\b(?:i|we)\s{1,3}now\s{1,3}(?:use|live|work|run|prefer|have)\b`,
89
+ String.raw`\bjust\s{1,3}started\s{1,3}(?:using|working|learning|taking|running)\b`,
90
+ ].join('|'),
91
+ 'i'
92
+ );
93
+
94
+ const COMPLETED_ACTION_RE =
95
+ /\b(?:i['’]ve|we['’]ve|(?:i|we)(?:\s{1,3}have)?)\s{1,3}(?:just\s{1,3}|finally\s{1,3}|recently\s{1,3})?(?:finished|completed|deployed|shipped|merged|implemented|fixed|resolved|published|bought|purchased|adopted|attended|visited|graduated)\b/i;
96
+
97
+ const PLANNED_ACTION_RE = new RegExp(
98
+ [
99
+ String.raw`\b(?:i['’]m|i\s{1,3}am|we['’]re|we\s{1,3}are|i|we)\s{1,3}(?:planning\s{1,3}to|plan\s{1,3}to|going\s{1,3}to|thinking\s{1,3}(?:of|about)|considering|hoping\s{1,3}to|about\s{1,3}to)\b`,
100
+ String.raw`\b(?:need|needs)\s{1,3}to\s{1,3}(?:implement|fix|refactor|migrate|upgrade|buy|schedule|book)\b`,
101
+ ].join('|'),
102
+ 'i'
103
+ );
104
+
105
+ const WANTS_PREFERENCE_RE =
106
+ /\b(?:recommend\w{0,20}|suggest\w{0,20}|tips?|ideas?|advice|advis\w{0,20}|how\s{1,3}should\s{1,3}(?:i|we)|what\s{1,3}should\s{1,3}(?:i|we)|prefer\w{0,20}|favou?rites?|convention\w{0,20}|best\s{1,3}way\s{1,3}to|tailor\w{0,20})\b/i;
107
+
108
+ const WANTS_STATE_UPDATE_RE =
109
+ /\b(?:current(?:ly)?|right\s{1,3}now|nowadays|these\s{1,3}days|latest|still\s{1,3}(?:use|using|on|at|with|in)|anymore|switched|migrated|moved|updated|upgraded)\b/i;
110
+
111
+ function isInterrogativeSentence(rawSentence: string): boolean {
112
+ const cleaned = rawSentence.replace(LEADING_LIST_MARKER_RE, '').trim();
113
+ if (!cleaned) return true;
114
+ if (QUESTION_END_RE.test(cleaned)) return true;
115
+
116
+ if (INTERROGATIVE_START_RE.test(cleaned)) {
117
+ if (IMPERATIVE_DO_NOT_START_RE.test(cleaned)) {
118
+ return false;
119
+ }
120
+ if (SUBORDINATE_WHEN_WHERE_RE.test(cleaned) && DECLARATIVE_AFTER_COMMA_RE.test(cleaned)) {
121
+ return false;
122
+ }
123
+ return true;
124
+ }
125
+
126
+ return false;
127
+ }
128
+
129
+ function matchesUnconditioned(sentence: string, re: RegExp): boolean {
130
+ const m = re.exec(sentence);
131
+ if (!m) return false;
132
+ const prefix = sentence.slice(Math.max(0, m.index - 16), m.index);
133
+ return !CONDITIONAL_CLAUSE_PREFIX_RE.test(prefix);
134
+ }
135
+
136
+ function matchesPlannedAction(sentence: string): boolean {
137
+ const m = PLANNED_ACTION_RE.exec(sentence);
138
+ if (!m) return false;
139
+ const prefix = sentence.slice(Math.max(0, m.index - 24), m.index);
140
+ return !PLANNED_BLOCKED_PREFIX_RE.test(prefix);
141
+ }
142
+
143
+ function matchesStateUpdate(sentence: string): boolean {
144
+ const m = STATE_UPDATE_SUBJECTLESS_RE.exec(sentence);
145
+ if (m) {
146
+ const prefix = sentence.slice(Math.max(0, m.index - 24), m.index);
147
+ const hasFirstPersonSubject = /^(?:i|we|our\s{1,3}team)\s/i.test(m[0]);
148
+ const blocked = hasFirstPersonSubject
149
+ ? CONDITIONAL_CLAUSE_PREFIX_RE.test(prefix)
150
+ : CONDITIONAL_OR_NEGATED_PREFIX_RE.test(prefix);
151
+ if (!blocked) {
152
+ return true;
153
+ }
154
+ }
155
+
156
+ const pm = STATE_UPDATE_OTHER_RE.exec(sentence);
157
+ if (!pm) return false;
158
+ const prefix = sentence.slice(Math.max(0, pm.index - 24), pm.index);
159
+ return !CONDITIONAL_OR_NEGATED_PREFIX_RE.test(prefix);
160
+ }
161
+
162
+ /**
163
+ * Deterministically extracts linguistic signal tags (`preference`, `state_update`,
164
+ * `completed_action`, `planned_action`) in canonical order.
165
+ *
166
+ * Anti-noise invariants:
167
+ * - `'preference'` is extracted strictly from `kind === 'prompt'` (`input`) so
168
+ * assistant `response` turns suggesting options never pollute preference signals.
169
+ * - `tool_call` outputs and verbose assistant essays are ignored; concise declarative
170
+ * summaries (`<= 400` chars) may emit non-preference action/state tags.
171
+ * - Interrogative sentences (ending in `?` or starting with question auxiliaries)
172
+ * are skipped so questions asking about state/preferences are never tagged as assertions.
173
+ */
174
+ export function extractSignalTags(obs: ExtractSignalTagsInput): SignalTag[] {
175
+ if (!obs || typeof obs !== 'object') return [];
176
+ const kind = typeof obs.kind === 'string' ? obs.kind : '';
177
+ if (kind === 'tool_call') return [];
178
+
179
+ const isPrompt = kind === 'prompt';
180
+ let sourceText = '';
181
+
182
+ if (isPrompt) {
183
+ sourceText = typeof obs.input === 'string' ? obs.input : '';
184
+ } else {
185
+ const candidate =
186
+ typeof obs.output === 'string' && obs.output.trim() !== ''
187
+ ? obs.output
188
+ : typeof obs.input === 'string'
189
+ ? obs.input
190
+ : '';
191
+ if (!candidate) return [];
192
+ // Only allow concise declarative summaries on non-prompt turns; skip verbose assistant essays
193
+ if (candidate.length > MAX_CONCISE_SUMMARY_CHARS) return [];
194
+ const trimmed = candidate.trim();
195
+ if (!trimmed || trimmed.length > MAX_CONCISE_SUMMARY_CHARS) return [];
196
+ sourceText = trimmed;
197
+ }
198
+
199
+ if (!sourceText) return [];
200
+
201
+ const bounded =
202
+ sourceText.length > MAX_SIGNAL_SCAN_CHARS
203
+ ? safeUtf16Slice(sourceText, 0, MAX_SIGNAL_SCAN_CHARS)
204
+ : sourceText;
205
+
206
+ const passages = splitIntoPassages(bounded);
207
+ if (passages.length === 0) return [];
208
+
209
+ const maxPassages = Math.min(passages.length, MAX_SIGNAL_SCAN_PASSAGES);
210
+ const maxPossibleTags = isPrompt ? 4 : 3;
211
+ const found = new Set<SignalTag>();
212
+
213
+ for (let i = 0; i < maxPassages; i++) {
214
+ const sentence = passages[i].text;
215
+ // Every multi-word linguistic cue contains whitespace; skip whitespace-free hex/base64/token blobs in O(1)
216
+ if (!sentence || (sentence.indexOf(' ') === -1 && sentence.indexOf('\t') === -1)) continue;
217
+ if (isInterrogativeSentence(sentence)) continue;
218
+ if (!isPrompt && ASSISTANT_META_CHATTER_RE.test(sentence)) continue;
219
+
220
+ if (isPrompt && !found.has('preference') && matchesUnconditioned(sentence, PREFERENCE_COMBINED_RE)) {
221
+ found.add('preference');
222
+ }
223
+ if (!found.has('state_update') && matchesStateUpdate(sentence)) {
224
+ found.add('state_update');
225
+ }
226
+ if (!found.has('completed_action') && matchesUnconditioned(sentence, COMPLETED_ACTION_RE)) {
227
+ found.add('completed_action');
228
+ }
229
+ if (!found.has('planned_action') && matchesPlannedAction(sentence)) {
230
+ found.add('planned_action');
231
+ }
232
+
233
+ if (found.size >= maxPossibleTags) break;
234
+ }
235
+
236
+ if (found.size === 0) return [];
237
+ return SIGNAL_TAG_ORDER.filter((tag) => found.has(tag));
238
+ }
239
+
240
+ /**
241
+ * Detects whether a search query seeks recommendations/preferences (`wantsPreference`)
242
+ * and/or current-state / state-transition facts (`wantsStateUpdate`).
243
+ */
244
+ export function detectQuerySignalIntent(q: string): QuerySignalIntent {
245
+ if (typeof q !== 'string' || q.length === 0) {
246
+ return { wantsPreference: false, wantsStateUpdate: false };
247
+ }
248
+ const sample =
249
+ q.length > MAX_QUERY_INTENT_SCAN_CHARS
250
+ ? safeUtf16Slice(q, 0, MAX_QUERY_INTENT_SCAN_CHARS)
251
+ : q;
252
+
253
+ return {
254
+ wantsPreference: WANTS_PREFERENCE_RE.test(sample),
255
+ wantsStateUpdate: WANTS_STATE_UPDATE_RE.test(sample),
256
+ };
257
+ }