@causyne/agent 1.20.28 → 1.20.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.28",
3
+ "version": "1.20.30",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/acp/client.js CHANGED
@@ -485,7 +485,7 @@ export class AcpClient {
485
485
  pending.notifyActivity?.();
486
486
  }
487
487
  }
488
- inspectPeerDiagnostics(sessionId) {
488
+ inspectPeerDiagnostics(sessionId, sinceEpochMs) {
489
489
  if (this.exitError) {
490
490
  return this.exitError.message;
491
491
  }
@@ -517,13 +517,13 @@ export class AcpClient {
517
517
  const isOpencode = cmd.includes('opencode')
518
518
  || (this.options.args && this.options.args.some(a => String(a).toLowerCase().includes('opencode')));
519
519
  if (isOpencode) {
520
- const opencodeErr = this.inspectOpencodeLog(sessionId);
520
+ const opencodeErr = this.inspectOpencodeLog(sessionId, sinceEpochMs);
521
521
  if (opencodeErr)
522
522
  return opencodeErr;
523
523
  }
524
524
  return null;
525
525
  }
526
- inspectOpencodeLog(sessionId) {
526
+ inspectOpencodeLog(sessionId, sinceEpochMs) {
527
527
  try {
528
528
  const logPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'log', 'opencode.log');
529
529
  if (!fsSync.existsSync(logPath))
@@ -548,6 +548,19 @@ export class AcpClient {
548
548
  continue;
549
549
  if (sessionId && !line.includes(sessionId))
550
550
  continue;
551
+ // Ignore normal stream cancellations triggered by session/cancel after <tool_call> detection
552
+ if (/\berror=Aborted\b|\bAbortError\b|\bMessageAbortedError\b/i.test(line)) {
553
+ continue;
554
+ }
555
+ if (sinceEpochMs !== undefined) {
556
+ const tsMatch = line.match(/timestamp=([^\s]+)/);
557
+ if (tsMatch?.[1]) {
558
+ const lineEpochMs = Date.parse(tsMatch[1]);
559
+ if (Number.isFinite(lineEpochMs) && lineEpochMs < sinceEpochMs - 250) {
560
+ continue;
561
+ }
562
+ }
563
+ }
551
564
  if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
552
565
  const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
553
566
  if (match && match[1]) {
@@ -570,6 +583,7 @@ export class AcpClient {
570
583
  if (this.exitError)
571
584
  return Promise.reject(this.exitError);
572
585
  const id = this.nextId++;
586
+ const requestStartMs = Date.now();
573
587
  return new Promise((resolve, reject) => {
574
588
  let inactivityTimer;
575
589
  let snifferInterval;
@@ -589,7 +603,7 @@ export class AcpClient {
589
603
  const timer = setTimeout(() => {
590
604
  cleanup();
591
605
  this.pending.delete(id);
592
- const diag = this.inspectPeerDiagnostics(options?.sessionId);
606
+ const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
593
607
  if (diag) {
594
608
  reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
595
609
  }
@@ -608,7 +622,7 @@ export class AcpClient {
608
622
  inactivityTimer = setTimeout(() => {
609
623
  cleanup();
610
624
  this.pending.delete(id);
611
- const diag = this.inspectPeerDiagnostics(options?.sessionId);
625
+ const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
612
626
  if (diag) {
613
627
  reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
614
628
  }
@@ -622,7 +636,7 @@ export class AcpClient {
622
636
  const sid = options?.sessionId;
623
637
  if (sid) {
624
638
  snifferInterval = setInterval(() => {
625
- const fatalDiag = this.inspectPeerDiagnostics(sid);
639
+ const fatalDiag = this.inspectPeerDiagnostics(sid, requestStartMs);
626
640
  if (fatalDiag) {
627
641
  cleanup();
628
642
  clearTimeout(timer);
package/src/acp/client.ts CHANGED
@@ -549,7 +549,7 @@ export class AcpClient {
549
549
  }
550
550
  }
551
551
 
552
- inspectPeerDiagnostics(sessionId?: string): string | null {
552
+ inspectPeerDiagnostics(sessionId?: string, sinceEpochMs?: number): string | null {
553
553
  if (this.exitError) {
554
554
  return this.exitError.message;
555
555
  }
@@ -580,13 +580,13 @@ export class AcpClient {
580
580
  const isOpencode = cmd.includes('opencode')
581
581
  || (this.options.args && this.options.args.some(a => String(a).toLowerCase().includes('opencode')));
582
582
  if (isOpencode) {
583
- const opencodeErr = this.inspectOpencodeLog(sessionId);
583
+ const opencodeErr = this.inspectOpencodeLog(sessionId, sinceEpochMs);
584
584
  if (opencodeErr) return opencodeErr;
585
585
  }
586
586
  return null;
587
587
  }
588
588
 
589
- private inspectOpencodeLog(sessionId?: string): string | null {
589
+ private inspectOpencodeLog(sessionId?: string, sinceEpochMs?: number): string | null {
590
590
  try {
591
591
  const logPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'log', 'opencode.log');
592
592
  if (!fsSync.existsSync(logPath)) return null;
@@ -606,6 +606,19 @@ export class AcpClient {
606
606
  const line = lines[i];
607
607
  if (!line) continue;
608
608
  if (sessionId && !line.includes(sessionId)) continue;
609
+ // Ignore normal stream cancellations triggered by session/cancel after <tool_call> detection
610
+ if (/\berror=Aborted\b|\bAbortError\b|\bMessageAbortedError\b/i.test(line)) {
611
+ continue;
612
+ }
613
+ if (sinceEpochMs !== undefined) {
614
+ const tsMatch = line.match(/timestamp=([^\s]+)/);
615
+ if (tsMatch?.[1]) {
616
+ const lineEpochMs = Date.parse(tsMatch[1]);
617
+ if (Number.isFinite(lineEpochMs) && lineEpochMs < sinceEpochMs - 250) {
618
+ continue;
619
+ }
620
+ }
621
+ }
609
622
  if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
610
623
  const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
611
624
  if (match && match[1]) {
@@ -631,6 +644,7 @@ export class AcpClient {
631
644
  if (!this.child || this.closed) return Promise.reject(new Error('agent process is not running'));
632
645
  if (this.exitError) return Promise.reject(this.exitError);
633
646
  const id = this.nextId++;
647
+ const requestStartMs = Date.now();
634
648
  return new Promise<T>((resolve, reject) => {
635
649
  let inactivityTimer: NodeJS.Timeout | undefined;
636
650
  let snifferInterval: NodeJS.Timeout | undefined;
@@ -649,7 +663,7 @@ export class AcpClient {
649
663
  const timer = setTimeout(() => {
650
664
  cleanup();
651
665
  this.pending.delete(id);
652
- const diag = this.inspectPeerDiagnostics(options?.sessionId);
666
+ const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
653
667
  if (diag) {
654
668
  reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
655
669
  } else {
@@ -665,7 +679,7 @@ export class AcpClient {
665
679
  inactivityTimer = setTimeout(() => {
666
680
  cleanup();
667
681
  this.pending.delete(id);
668
- const diag = this.inspectPeerDiagnostics(options?.sessionId);
682
+ const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
669
683
  if (diag) {
670
684
  reject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
671
685
  } else {
@@ -678,7 +692,7 @@ export class AcpClient {
678
692
  const sid = options?.sessionId;
679
693
  if (sid) {
680
694
  snifferInterval = setInterval(() => {
681
- const fatalDiag = this.inspectPeerDiagnostics(sid);
695
+ const fatalDiag = this.inspectPeerDiagnostics(sid, requestStartMs);
682
696
  if (fatalDiag) {
683
697
  cleanup();
684
698
  clearTimeout(timer);
@@ -218,7 +218,10 @@ export function pruneStaleToolObservations(messages, options = {}) {
218
218
  }
219
219
  if (seen <= keepRecent && !isDuplicateInspection)
220
220
  continue;
221
- if (original.length < minChars)
221
+ const effectiveMinChars = message.name === 'memory_recall'
222
+ ? Math.max(minChars, 4000)
223
+ : minChars;
224
+ if (original.length < effectiveMinChars)
222
225
  continue;
223
226
  let spillPath = message.spillPath;
224
227
  if (!spillPath) {
@@ -228,7 +228,10 @@ export function pruneStaleToolObservations(
228
228
  }
229
229
 
230
230
  if (seen <= keepRecent && !isDuplicateInspection) continue;
231
- if (original.length < minChars) continue;
231
+ const effectiveMinChars = message.name === 'memory_recall'
232
+ ? Math.max(minChars, 4000)
233
+ : minChars;
234
+ if (original.length < effectiveMinChars) continue;
232
235
 
233
236
  let spillPath = message.spillPath;
234
237
  if (!spillPath) {
@@ -67,9 +67,10 @@ export function compileToolObservation(params) {
67
67
  }
68
68
  }
69
69
  const rawPath = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? '').trim();
70
- const relPath = rawPath && workspace
70
+ const rawRel = rawPath && workspace
71
71
  ? (path.isAbsolute(rawPath) ? path.relative(workspace, rawPath) : rawPath)
72
72
  : rawPath;
73
+ const relPath = rawRel ? rawRel.replace(/\\/g, '/') : '';
73
74
  const lowerTool = normalizedTool.toLowerCase();
74
75
  // 1. File mutations (fs_write, fs_edit, MultiEdit, write_file, edit_file)
75
76
  if (['fs_write', 'fs_edit', 'multiedit', 'write_file', 'edit_file', 'replace_file_content', 'write', 'edit'].includes(lowerTool)) {
@@ -184,8 +185,15 @@ export class EpisodicMemoryStore {
184
185
  externalBridgeImported = false;
185
186
  static defaultInstance = null;
186
187
  constructor(customStorePath) {
187
- this.storePath = customStorePath
188
- ? path.resolve(customStorePath)
188
+ if (customStorePath) {
189
+ this.storePath = path.resolve(customStorePath);
190
+ return;
191
+ }
192
+ const isTestRunner = Boolean(process.env.NODE_TEST_CONTEXT) ||
193
+ process.execArgv.includes('--test') ||
194
+ process.argv.includes('--test');
195
+ this.storePath = isTestRunner
196
+ ? path.join(os.tmpdir(), `causyne-test-episodic-${process.pid}.json`)
189
197
  : path.join(causyneHome(), 'episodic-memory.json');
190
198
  }
191
199
  static getInstance() {
@@ -202,6 +210,10 @@ export class EpisodicMemoryStore {
202
210
  const raw = JSON.parse(fs.readFileSync(this.storePath, 'utf8'));
203
211
  if (raw && Array.isArray(raw.observations) && Array.isArray(raw.summaries)) {
204
212
  const cleanedObservations = raw.observations.filter((obs) => {
213
+ if (obs.taskId === 'native-recovery-false')
214
+ return false;
215
+ if (obs.title.includes('.causyne_verify_placeholder'))
216
+ return false;
205
217
  if (obs.type !== 'discovery')
206
218
  return true;
207
219
  return !/^(?:Succeeded|Failed):\s*(?:find|wc|grep|egrep|fgrep|rg|sed|awk|jq|stat|file|ls|cat|head|tail|node\s+-e|python3?\s+-c)\b/i.test(obs.title);
@@ -523,14 +535,15 @@ export class EpisodicMemoryStore {
523
535
  continue;
524
536
  }
525
537
  totalBytes += byteLen;
526
- observations.push(obs);
527
- // Reinforce retrieved memory in ACT-R
538
+ // Reinforce retrieved memory in ACT-R and return the updated observation
528
539
  const reinforced = [...obs.reinforcedAtEpochsMs, nowMs].slice(-MAX_REINFORCEMENT_TIMESTAMPS);
529
- store.observations[idx] = {
540
+ const updatedObs = {
530
541
  ...obs,
531
542
  reinforcedAtEpochsMs: reinforced,
532
543
  reinforcementCount: obs.reinforcementCount + 1
533
544
  };
545
+ store.observations[idx] = updatedObs;
546
+ observations.push(updatedObs);
534
547
  dirty = true;
535
548
  }
536
549
  if (dirty) {
@@ -133,9 +133,10 @@ export function compileToolObservation(params: {
133
133
  const rawPath = String(
134
134
  args.path ?? args.file_path ?? args.filePath ?? args.target ?? ''
135
135
  ).trim();
136
- const relPath = rawPath && workspace
136
+ const rawRel = rawPath && workspace
137
137
  ? (path.isAbsolute(rawPath) ? path.relative(workspace, rawPath) : rawPath)
138
138
  : rawPath;
139
+ const relPath = rawRel ? rawRel.replace(/\\/g, '/') : '';
139
140
 
140
141
  const lowerTool = normalizedTool.toLowerCase();
141
142
 
@@ -261,8 +262,16 @@ export class EpisodicMemoryStore {
261
262
  private static defaultInstance: EpisodicMemoryStore | null = null;
262
263
 
263
264
  constructor(customStorePath?: string) {
264
- this.storePath = customStorePath
265
- ? path.resolve(customStorePath)
265
+ if (customStorePath) {
266
+ this.storePath = path.resolve(customStorePath);
267
+ return;
268
+ }
269
+ const isTestRunner =
270
+ Boolean(process.env.NODE_TEST_CONTEXT) ||
271
+ process.execArgv.includes('--test') ||
272
+ process.argv.includes('--test');
273
+ this.storePath = isTestRunner
274
+ ? path.join(os.tmpdir(), `causyne-test-episodic-${process.pid}.json`)
266
275
  : path.join(causyneHome(), 'episodic-memory.json');
267
276
  }
268
277
 
@@ -280,6 +289,8 @@ export class EpisodicMemoryStore {
280
289
  const raw = JSON.parse(fs.readFileSync(this.storePath, 'utf8')) as Partial<PersistedEpisodicData>;
281
290
  if (raw && Array.isArray(raw.observations) && Array.isArray(raw.summaries)) {
282
291
  const cleanedObservations = raw.observations.filter((obs) => {
292
+ if (obs.taskId === 'native-recovery-false') return false;
293
+ if (obs.title.includes('.causyne_verify_placeholder')) return false;
283
294
  if (obs.type !== 'discovery') return true;
284
295
  return !/^(?:Succeeded|Failed):\s*(?:find|wc|grep|egrep|fgrep|rg|sed|awk|jq|stat|file|ls|cat|head|tail|node\s+-e|python3?\s+-c)\b/i.test(obs.title);
285
296
  });
@@ -640,15 +651,16 @@ export class EpisodicMemoryStore {
640
651
  }
641
652
 
642
653
  totalBytes += byteLen;
643
- observations.push(obs);
644
654
 
645
- // Reinforce retrieved memory in ACT-R
655
+ // Reinforce retrieved memory in ACT-R and return the updated observation
646
656
  const reinforced = [...obs.reinforcedAtEpochsMs, nowMs].slice(-MAX_REINFORCEMENT_TIMESTAMPS);
647
- store.observations[idx] = {
657
+ const updatedObs: EpisodicObservation = {
648
658
  ...obs,
649
659
  reinforcedAtEpochsMs: reinforced,
650
660
  reinforcementCount: obs.reinforcementCount + 1
651
661
  };
662
+ store.observations[idx] = updatedObs;
663
+ observations.push(updatedObs);
652
664
  dirty = true;
653
665
  }
654
666
 
@@ -115,11 +115,11 @@ function extractPrecedingDocComment(lines, lineIndex) {
115
115
  idx--;
116
116
  }
117
117
  const summary = docLines.join(' ').trim();
118
- return summary ? summary.slice(0, 110) : undefined;
118
+ return summary ? summary.slice(0, 65) : undefined;
119
119
  }
120
120
  if (line.startsWith('//') || line.startsWith('#')) {
121
121
  const cleaned = line.replace(/^(?:\/\/+|#+)\s*/, '').trim();
122
- return cleaned ? cleaned.slice(0, 110) : undefined;
122
+ return cleaned ? cleaned.slice(0, 65) : undefined;
123
123
  }
124
124
  return undefined;
125
125
  }
@@ -158,26 +158,147 @@ function extractCollapsedSignature(lines, startIndex, kind) {
158
158
  .trim()
159
159
  .slice(0, 110);
160
160
  }
161
- function findBraceBlockEnd(lines, startIndex) {
162
- let depth = 0;
163
- let opened = false;
161
+ function findBraceBlockEnd(lines, startIndex, kind) {
162
+ const isCallable = kind === 'function' || kind === 'method';
163
+ let inBlockComment = false;
164
+ let parenDepth = 0;
165
+ let seenParamsOpen = false;
166
+ let seenParamsClose = !isCallable;
167
+ let typeBraceDepth = 0;
168
+ let bodyDepth = 0;
169
+ let bodyOpened = false;
170
+ let lastNonWs = '';
164
171
  for (let i = startIndex; i < lines.length; i++) {
165
172
  const line = lines[i] ?? '';
173
+ let inSingleQuote = false;
174
+ let inDoubleQuote = false;
175
+ let inTemplate = false;
166
176
  for (let c = 0; c < line.length; c++) {
167
- const ch = line[c];
168
- if (ch === '{') {
169
- depth += 1;
170
- opened = true;
177
+ const ch = line[c] ?? '';
178
+ const next = line[c + 1] ?? '';
179
+ if (inBlockComment) {
180
+ if (ch === '*' && next === '/') {
181
+ inBlockComment = false;
182
+ c += 1;
183
+ }
184
+ continue;
185
+ }
186
+ if (ch === '\\') {
187
+ c += 1;
188
+ continue;
189
+ }
190
+ if (inSingleQuote) {
191
+ if (ch === '\'')
192
+ inSingleQuote = false;
193
+ continue;
194
+ }
195
+ if (inDoubleQuote) {
196
+ if (ch === '"')
197
+ inDoubleQuote = false;
198
+ continue;
199
+ }
200
+ if (inTemplate) {
201
+ if (ch === '`')
202
+ inTemplate = false;
203
+ continue;
204
+ }
205
+ if (ch === '/' && next === '/') {
206
+ break;
207
+ }
208
+ if (ch === '/' && next === '*') {
209
+ inBlockComment = true;
210
+ c += 1;
211
+ continue;
212
+ }
213
+ if (ch === '\'') {
214
+ inSingleQuote = true;
215
+ if (seenParamsClose && !bodyOpened && typeBraceDepth === 0)
216
+ lastNonWs = ch;
217
+ continue;
218
+ }
219
+ if (ch === '"') {
220
+ inDoubleQuote = true;
221
+ if (seenParamsClose && !bodyOpened && typeBraceDepth === 0)
222
+ lastNonWs = ch;
223
+ continue;
224
+ }
225
+ if (ch === '`') {
226
+ inTemplate = true;
227
+ if (seenParamsClose && !bodyOpened && typeBraceDepth === 0)
228
+ lastNonWs = ch;
229
+ continue;
230
+ }
231
+ if (!seenParamsClose) {
232
+ if (ch === '(') {
233
+ parenDepth += 1;
234
+ seenParamsOpen = true;
235
+ }
236
+ else if (ch === ')') {
237
+ parenDepth -= 1;
238
+ if (seenParamsOpen && parenDepth <= 0) {
239
+ seenParamsClose = true;
240
+ parenDepth = 0;
241
+ lastNonWs = ')';
242
+ }
243
+ }
244
+ continue;
171
245
  }
172
- else if (ch === '}') {
173
- depth -= 1;
174
- if (opened && depth <= 0) {
246
+ if (!bodyOpened) {
247
+ if (typeBraceDepth > 0) {
248
+ if (ch === '{') {
249
+ typeBraceDepth += 1;
250
+ }
251
+ else if (ch === '}') {
252
+ typeBraceDepth -= 1;
253
+ if (typeBraceDepth <= 0) {
254
+ typeBraceDepth = 0;
255
+ lastNonWs = '}';
256
+ }
257
+ }
258
+ continue;
259
+ }
260
+ if (ch === '(') {
261
+ parenDepth += 1;
262
+ lastNonWs = '(';
263
+ }
264
+ else if (ch === ')') {
265
+ parenDepth = Math.max(0, parenDepth - 1);
266
+ lastNonWs = ')';
267
+ }
268
+ else if (ch === '{') {
269
+ if (isCallable &&
270
+ (parenDepth > 0 ||
271
+ lastNonWs === ':' ||
272
+ lastNonWs === '|' ||
273
+ lastNonWs === '&' ||
274
+ lastNonWs === '<' ||
275
+ lastNonWs === ',' ||
276
+ lastNonWs === '=')) {
277
+ typeBraceDepth = 1;
278
+ }
279
+ else {
280
+ bodyOpened = true;
281
+ bodyDepth = 1;
282
+ }
283
+ }
284
+ else if (ch === ';' && parenDepth === 0) {
175
285
  return i + 1;
176
286
  }
287
+ else if (!/\s/.test(ch)) {
288
+ lastNonWs = ch;
289
+ }
290
+ }
291
+ else {
292
+ if (ch === '{') {
293
+ bodyDepth += 1;
294
+ }
295
+ else if (ch === '}') {
296
+ bodyDepth -= 1;
297
+ if (bodyDepth <= 0) {
298
+ return i + 1;
299
+ }
300
+ }
177
301
  }
178
- }
179
- if (!opened && line.trim().endsWith(';')) {
180
- return i + 1;
181
302
  }
182
303
  }
183
304
  return Math.min(lines.length, startIndex + 1);
@@ -206,6 +327,9 @@ export function foldSourceContentOutline(content, filePath, queryFilter) {
206
327
  const ext = path.extname(filePath).toLowerCase();
207
328
  const language = LANGUAGE_BY_EXT[ext] ?? 'text';
208
329
  const lines = content.split(/\r?\n/);
330
+ if (lines.length > 1 && lines[lines.length - 1] === '') {
331
+ lines.pop();
332
+ }
209
333
  const totalLines = lines.length;
210
334
  let importCount = 0;
211
335
  for (const line of lines) {
@@ -234,19 +358,23 @@ export function foldSourceContentOutline(content, filePath, queryFilter) {
234
358
  const rawName = m[pat.nameGroup] || m[3] || '';
235
359
  if (!rawName || RESERVED_METHOD_NAMES.has(rawName))
236
360
  continue;
237
- // For class method pattern, ensure it is either followed by `{` on this/next lines (not a function call ending in `);`)
361
+ // For class method pattern, ensure it is not a bodyless call ending in `;`
238
362
  if (pat.kind === 'method') {
239
363
  const sigCheck = extractCollapsedSignature(lines, i, 'method');
240
- if (sigCheck.endsWith(';') || /=/.test(line))
364
+ if (sigCheck.endsWith(';'))
241
365
  continue;
242
366
  }
243
367
  const exported = /\bexport\b|\bpub\b/.test(line);
244
368
  const lineStart = i + 1;
245
369
  const lineEnd = language === 'python'
246
370
  ? findIndentBlockEnd(lines, i)
247
- : findBraceBlockEnd(lines, i);
371
+ : findBraceBlockEnd(lines, i, pat.kind);
248
372
  const signature = extractCollapsedSignature(lines, i, pat.kind);
249
373
  const docComment = extractPrecedingDocComment(lines, i);
374
+ // Advance past non-class symbol bodies so statements inside functions/methods aren't misread as methods
375
+ if (pat.kind !== 'class') {
376
+ i = Math.max(i, lineEnd - 1);
377
+ }
250
378
  if (lowerQuery) {
251
379
  const hay = `${rawName} ${signature} ${docComment ?? ''}`.toLowerCase();
252
380
  if (!hay.includes(lowerQuery))
@@ -261,10 +389,6 @@ export function foldSourceContentOutline(content, filePath, queryFilter) {
261
389
  exported,
262
390
  ...(docComment ? { docComment } : {})
263
391
  });
264
- // Advance past multi-line parameter list header if applicable so inner lines aren't misread as methods
265
- if (pat.kind === 'function') {
266
- i = Math.max(i, lineEnd - 1);
267
- }
268
392
  break;
269
393
  }
270
394
  }
@@ -127,11 +127,11 @@ function extractPrecedingDocComment(lines: readonly string[], lineIndex: number)
127
127
  idx--;
128
128
  }
129
129
  const summary = docLines.join(' ').trim();
130
- return summary ? summary.slice(0, 110) : undefined;
130
+ return summary ? summary.slice(0, 65) : undefined;
131
131
  }
132
132
  if (line.startsWith('//') || line.startsWith('#')) {
133
133
  const cleaned = line.replace(/^(?:\/\/+|#+)\s*/, '').trim();
134
- return cleaned ? cleaned.slice(0, 110) : undefined;
134
+ return cleaned ? cleaned.slice(0, 65) : undefined;
135
135
  }
136
136
  return undefined;
137
137
  }
@@ -171,26 +171,144 @@ function extractCollapsedSignature(lines: readonly string[], startIndex: number,
171
171
  .slice(0, 110);
172
172
  }
173
173
 
174
- function findBraceBlockEnd(lines: readonly string[], startIndex: number): number {
175
- let depth = 0;
176
- let opened = false;
174
+ function findBraceBlockEnd(lines: readonly string[], startIndex: number, kind: FoldedSymbolKind): number {
175
+ const isCallable = kind === 'function' || kind === 'method';
176
+ let inBlockComment = false;
177
+ let parenDepth = 0;
178
+ let seenParamsOpen = false;
179
+ let seenParamsClose = !isCallable;
180
+ let typeBraceDepth = 0;
181
+ let bodyDepth = 0;
182
+ let bodyOpened = false;
183
+ let lastNonWs = '';
184
+
177
185
  for (let i = startIndex; i < lines.length; i++) {
178
186
  const line = lines[i] ?? '';
187
+ let inSingleQuote = false;
188
+ let inDoubleQuote = false;
189
+ let inTemplate = false;
190
+
179
191
  for (let c = 0; c < line.length; c++) {
180
- const ch = line[c];
181
- if (ch === '{') {
182
- depth += 1;
183
- opened = true;
184
- } else if (ch === '}') {
185
- depth -= 1;
186
- if (opened && depth <= 0) {
192
+ const ch = line[c] ?? '';
193
+ const next = line[c + 1] ?? '';
194
+
195
+ if (inBlockComment) {
196
+ if (ch === '*' && next === '/') {
197
+ inBlockComment = false;
198
+ c += 1;
199
+ }
200
+ continue;
201
+ }
202
+
203
+ if (ch === '\\') {
204
+ c += 1;
205
+ continue;
206
+ }
207
+
208
+ if (inSingleQuote) {
209
+ if (ch === '\'') inSingleQuote = false;
210
+ continue;
211
+ }
212
+ if (inDoubleQuote) {
213
+ if (ch === '"') inDoubleQuote = false;
214
+ continue;
215
+ }
216
+ if (inTemplate) {
217
+ if (ch === '`') inTemplate = false;
218
+ continue;
219
+ }
220
+
221
+ if (ch === '/' && next === '/') {
222
+ break;
223
+ }
224
+ if (ch === '/' && next === '*') {
225
+ inBlockComment = true;
226
+ c += 1;
227
+ continue;
228
+ }
229
+ if (ch === '\'') {
230
+ inSingleQuote = true;
231
+ if (seenParamsClose && !bodyOpened && typeBraceDepth === 0) lastNonWs = ch;
232
+ continue;
233
+ }
234
+ if (ch === '"') {
235
+ inDoubleQuote = true;
236
+ if (seenParamsClose && !bodyOpened && typeBraceDepth === 0) lastNonWs = ch;
237
+ continue;
238
+ }
239
+ if (ch === '`') {
240
+ inTemplate = true;
241
+ if (seenParamsClose && !bodyOpened && typeBraceDepth === 0) lastNonWs = ch;
242
+ continue;
243
+ }
244
+
245
+ if (!seenParamsClose) {
246
+ if (ch === '(') {
247
+ parenDepth += 1;
248
+ seenParamsOpen = true;
249
+ } else if (ch === ')') {
250
+ parenDepth -= 1;
251
+ if (seenParamsOpen && parenDepth <= 0) {
252
+ seenParamsClose = true;
253
+ parenDepth = 0;
254
+ lastNonWs = ')';
255
+ }
256
+ }
257
+ continue;
258
+ }
259
+
260
+ if (!bodyOpened) {
261
+ if (typeBraceDepth > 0) {
262
+ if (ch === '{') {
263
+ typeBraceDepth += 1;
264
+ } else if (ch === '}') {
265
+ typeBraceDepth -= 1;
266
+ if (typeBraceDepth <= 0) {
267
+ typeBraceDepth = 0;
268
+ lastNonWs = '}';
269
+ }
270
+ }
271
+ continue;
272
+ }
273
+
274
+ if (ch === '(') {
275
+ parenDepth += 1;
276
+ lastNonWs = '(';
277
+ } else if (ch === ')') {
278
+ parenDepth = Math.max(0, parenDepth - 1);
279
+ lastNonWs = ')';
280
+ } else if (ch === '{') {
281
+ if (
282
+ isCallable &&
283
+ (parenDepth > 0 ||
284
+ lastNonWs === ':' ||
285
+ lastNonWs === '|' ||
286
+ lastNonWs === '&' ||
287
+ lastNonWs === '<' ||
288
+ lastNonWs === ',' ||
289
+ lastNonWs === '=')
290
+ ) {
291
+ typeBraceDepth = 1;
292
+ } else {
293
+ bodyOpened = true;
294
+ bodyDepth = 1;
295
+ }
296
+ } else if (ch === ';' && parenDepth === 0) {
187
297
  return i + 1;
298
+ } else if (!/\s/.test(ch)) {
299
+ lastNonWs = ch;
300
+ }
301
+ } else {
302
+ if (ch === '{') {
303
+ bodyDepth += 1;
304
+ } else if (ch === '}') {
305
+ bodyDepth -= 1;
306
+ if (bodyDepth <= 0) {
307
+ return i + 1;
308
+ }
188
309
  }
189
310
  }
190
311
  }
191
- if (!opened && line.trim().endsWith(';')) {
192
- return i + 1;
193
- }
194
312
  }
195
313
  return Math.min(lines.length, startIndex + 1);
196
314
  }
@@ -223,6 +341,9 @@ export function foldSourceContentOutline(
223
341
  const ext = path.extname(filePath).toLowerCase();
224
342
  const language = LANGUAGE_BY_EXT[ext] ?? 'text';
225
343
  const lines = content.split(/\r?\n/);
344
+ if (lines.length > 1 && lines[lines.length - 1] === '') {
345
+ lines.pop();
346
+ }
226
347
  const totalLines = lines.length;
227
348
 
228
349
  let importCount = 0;
@@ -255,20 +376,25 @@ export function foldSourceContentOutline(
255
376
  const rawName = m[pat.nameGroup] || m[3] || '';
256
377
  if (!rawName || RESERVED_METHOD_NAMES.has(rawName)) continue;
257
378
 
258
- // For class method pattern, ensure it is either followed by `{` on this/next lines (not a function call ending in `);`)
379
+ // For class method pattern, ensure it is not a bodyless call ending in `;`
259
380
  if (pat.kind === 'method') {
260
381
  const sigCheck = extractCollapsedSignature(lines, i, 'method');
261
- if (sigCheck.endsWith(';') || /=/.test(line)) continue;
382
+ if (sigCheck.endsWith(';')) continue;
262
383
  }
263
384
 
264
385
  const exported = /\bexport\b|\bpub\b/.test(line);
265
386
  const lineStart = i + 1;
266
387
  const lineEnd = language === 'python'
267
388
  ? findIndentBlockEnd(lines, i)
268
- : findBraceBlockEnd(lines, i);
389
+ : findBraceBlockEnd(lines, i, pat.kind);
269
390
  const signature = extractCollapsedSignature(lines, i, pat.kind);
270
391
  const docComment = extractPrecedingDocComment(lines, i);
271
392
 
393
+ // Advance past non-class symbol bodies so statements inside functions/methods aren't misread as methods
394
+ if (pat.kind !== 'class') {
395
+ i = Math.max(i, lineEnd - 1);
396
+ }
397
+
272
398
  if (lowerQuery) {
273
399
  const hay = `${rawName} ${signature} ${docComment ?? ''}`.toLowerCase();
274
400
  if (!hay.includes(lowerQuery)) break;
@@ -283,10 +409,6 @@ export function foldSourceContentOutline(
283
409
  exported,
284
410
  ...(docComment ? { docComment } : {})
285
411
  });
286
- // Advance past multi-line parameter list header if applicable so inner lines aren't misread as methods
287
- if (pat.kind === 'function') {
288
- i = Math.max(i, lineEnd - 1);
289
- }
290
412
  break;
291
413
  }
292
414
  }
@@ -98,7 +98,7 @@ export const memoryRecall = {
98
98
  ? 'No matching episodic observations found.'
99
99
  : [
100
100
  `Found ${res.totalMatches} match(es) (showing ${res.results.length}):`,
101
- ...res.results.map((r) => `${r.id} [${r.type}] (${r.project}) ${r.title}${r.reinforcementCount > 0 ? ` [x${r.reinforcementCount + 1}]` : ''} — score ${r.score}`),
101
+ ...res.results.map((r) => `${r.id} [${r.type}] (${r.project}) ${r.title}${r.reinforcementCount > 0 ? ` [reinforced: ${r.reinforcementCount}]` : ''} — score ${r.score}`),
102
102
  'Next step: call memory_recall with action="timeline" (anchorId) or action="get" (ids) for full details.'
103
103
  ].join('\n');
104
104
  return {
@@ -131,7 +131,7 @@ export const memoryRecall = {
131
131
  : [
132
132
  `Found ${res.totalMatches} match(es) (showing ${res.results.length}):`,
133
133
  ...res.results.map(
134
- (r) => `${r.id} [${r.type}] (${r.project}) ${r.title}${r.reinforcementCount > 0 ? ` [x${r.reinforcementCount + 1}]` : ''} — score ${r.score}`
134
+ (r) => `${r.id} [${r.type}] (${r.project}) ${r.title}${r.reinforcementCount > 0 ? ` [reinforced: ${r.reinforcementCount}]` : ''} — score ${r.score}`
135
135
  ),
136
136
  'Next step: call memory_recall with action="timeline" (anchorId) or action="get" (ids) for full details.'
137
137
  ].join('\n');