osborn 0.9.290 → 0.9.292

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 (86) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +5 -4
  2. package/.claude/skills/browser-apply/candidate.example.env +4 -1
  3. package/.claude/skills/browser-apply/fill.mjs +13 -2
  4. package/.claude/skills/meetings/SKILL.md +26 -7
  5. package/.env.example +6 -0
  6. package/dist/agent-store.d.ts +6 -0
  7. package/dist/agent-store.js +36 -6
  8. package/dist/approval-policy.d.ts +99 -0
  9. package/dist/approval-policy.js +196 -0
  10. package/dist/claude-llm.d.ts +6 -2
  11. package/dist/claude-llm.js +68 -20
  12. package/dist/config.d.ts +12 -16
  13. package/dist/config.js +75 -21
  14. package/dist/content/compaction-lens-worker.d.ts +5 -0
  15. package/dist/content/compaction-lens-worker.js +78 -7
  16. package/dist/content/content-llm.d.ts +14 -3
  17. package/dist/content/content-llm.js +33 -142
  18. package/dist/content/lens-db.d.ts +16 -5
  19. package/dist/content/lens-db.js +58 -11
  20. package/dist/content/lens-ingest.d.ts +1 -0
  21. package/dist/content/lens-ingest.js +1 -1
  22. package/dist/content/lens-launch.d.ts +42 -1
  23. package/dist/content/lens-launch.js +202 -40
  24. package/dist/content/lens-library-digest.d.ts +85 -0
  25. package/dist/content/lens-library-digest.js +305 -0
  26. package/dist/content/lens-library-index.d.ts +14 -3
  27. package/dist/content/lens-library-index.js +35 -8
  28. package/dist/content/lens-library-select.d.ts +1 -1
  29. package/dist/content/lens-library-select.js +1 -1
  30. package/dist/content/lens-library-sweep.d.ts +36 -0
  31. package/dist/content/lens-library-sweep.js +331 -0
  32. package/dist/content/lens-library.d.ts +29 -0
  33. package/dist/content/lens-library.js +130 -20
  34. package/dist/content/lens-model.d.ts +4 -0
  35. package/dist/content/lens-model.js +5 -0
  36. package/dist/content/lens-paths.d.ts +72 -0
  37. package/dist/content/lens-paths.js +248 -5
  38. package/dist/content/period-run.js +2 -2
  39. package/dist/content/secret-rules.d.ts +51 -0
  40. package/dist/content/secret-rules.js +185 -0
  41. package/dist/content/transcript-sanitizer.d.ts +1 -41
  42. package/dist/content/transcript-sanitizer.js +4 -171
  43. package/dist/data-sender-auth.d.ts +112 -3
  44. package/dist/data-sender-auth.js +165 -39
  45. package/dist/env-keys.d.ts +10 -2
  46. package/dist/env-keys.js +26 -5
  47. package/dist/index.js +616 -109
  48. package/dist/phone-code.d.ts +76 -0
  49. package/dist/phone-code.js +124 -0
  50. package/dist/phone-voice-actions.d.ts +132 -0
  51. package/dist/phone-voice-actions.js +223 -0
  52. package/dist/pipeline-direct-llm.d.ts +8 -1
  53. package/dist/pipeline-direct-llm.js +13 -1
  54. package/dist/prompts/library-digest.md +11 -0
  55. package/dist/prompts.d.ts +4 -0
  56. package/dist/prompts.js +6 -2
  57. package/dist/pushover.d.ts +2 -1
  58. package/dist/pushover.js +7 -6
  59. package/dist/risk-tier.d.ts +14 -0
  60. package/dist/risk-tier.js +140 -0
  61. package/dist/session-store.d.ts +1 -0
  62. package/dist/session-store.js +3 -2
  63. package/dist/session-switch.d.ts +22 -7
  64. package/dist/session-switch.js +58 -24
  65. package/dist/steward-verdict.d.ts +16 -3
  66. package/dist/steward-verdict.js +37 -18
  67. package/dist/watch-gateway.js +3 -1
  68. package/package.json +1 -1
  69. package/dist/bridge-llm.d.ts +0 -22
  70. package/dist/bridge-llm.js +0 -39
  71. package/dist/codex-handler.d.ts +0 -38
  72. package/dist/codex-handler.js +0 -83
  73. package/dist/codex-llm.d.ts +0 -40
  74. package/dist/codex-llm.js +0 -144
  75. package/dist/fast-brain.d.ts +0 -176
  76. package/dist/fast-brain.js +0 -1887
  77. package/dist/index-3-2-26-legacy.d.ts +0 -1
  78. package/dist/index-3-2-26-legacy.js +0 -2233
  79. package/dist/leagcyprompts2.d.ts +0 -0
  80. package/dist/leagcyprompts2.js +0 -573
  81. package/dist/prompts-2-25-26.d.ts +0 -0
  82. package/dist/prompts-2-25-26.js +0 -518
  83. package/dist/prompts-3-2-26.d.ts +0 -78
  84. package/dist/prompts-3-2-26.js +0 -1319
  85. package/dist/summary-index.d.ts +0 -90
  86. package/dist/summary-index.js +0 -585
@@ -11,18 +11,19 @@ import { query } from '@anthropic-ai/claude-agent-sdk';
11
11
  import { EventEmitter } from 'events';
12
12
  import { saveSessionMetadata, getSessionWorkspace } from './config.js';
13
13
  import { statusManager } from './status-manager.js';
14
- import { getResearchSystemPrompt, getDirectModeResearchPrompt, getStewardPrompt, getChainReminder, getGroundingBlock, getRecalledContextBlock } from './prompts.js';
14
+ import { getResearchSystemPrompt, getDirectModeResearchPrompt, getStewardPrompt, getChainReminder, getGroundingBlock, getRecalledContextBlock, PHONE_TOOLS_DENIED } from './prompts.js';
15
+ import { phoneToolPolicy } from './data-sender-auth.js';
15
16
  import { openStore, recall, storeExists, updateSessionStore, getStorePath } from './session-store.js';
16
17
  import { appendCompactionRecord, countTranscriptRows } from './compaction-log.js';
17
18
  import { getEmbedder } from './embedder.js';
18
- import { launchCompactionLens } from './content/lens-launch.js';
19
+ import { launchCompactionLensWithRetry } from './content/lens-launch.js';
19
20
  import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
20
21
  import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
21
22
  import { join, dirname, resolve, basename } from 'node:path';
22
23
  import { fileURLToPath } from 'node:url';
23
24
  import { homedir, loadavg, totalmem, freemem, cpus } from 'node:os';
24
25
  import { stewardGate } from './steward-gate.js';
25
- import { parseStewardVerdict, appendStewardVerdict } from './steward-verdict.js';
26
+ import { parseStewardVerdict, appendStewardRecord } from './steward-verdict.js';
26
27
  import { ROLES, EDIT_TOOLS, roleOf, coreRole, installsSkillsSilently, parseFrontMatter } from './agent-store.js';
27
28
  // Directory of this module — used to locate co-located prompt files (e.g., turn-shape reminder).
28
29
  const __claudeLlmDir = dirname(fileURLToPath(import.meta.url));
@@ -1241,9 +1242,13 @@ export class ClaudeLLM extends llm.LLM {
1241
1242
  // the FULL source set — main JSONL + every sub-agent JSONL — exactly like the flat
1242
1243
  // index. Incremental (byte-offset resume) + fire-and-forget, so it never blocks a turn.
1243
1244
  #storeUpdating = false;
1245
+ #storeUpdateAgain = null;
1244
1246
  // Turbo mode — when true, every spawned agent (main + sub-agents) runs on
1245
1247
  // FAST_MODEL regardless of individual model config. Default off = no-op.
1246
1248
  #turbo = false;
1249
+ // Phone call — when true, the PreToolUse hook denies every tool (talk-only
1250
+ // call, see PHONE_TOOLS_ENABLED). Read at each tool call, so it applies mid-session.
1251
+ #phoneCall = false;
1247
1252
  constructor(opts = {}) {
1248
1253
  super();
1249
1254
  // Session resume/continue options
@@ -1299,7 +1304,10 @@ export class ClaudeLLM extends llm.LLM {
1299
1304
  * Respond to a pending permission request
1300
1305
  * Call this after receiving 'permission_request' event
1301
1306
  */
1302
- respondToPermission(allow, message) {
1307
+ respondToPermission(allow, message, requestId) {
1308
+ // An answer meant for another request (a late click, a parked brain) never settles this one.
1309
+ if (requestId !== undefined && this.#pendingPermission?.requestId !== requestId)
1310
+ return false;
1303
1311
  if (this.#pendingPermission) {
1304
1312
  const input = this.#pendingPermission.input;
1305
1313
  if (allow) {
@@ -1315,7 +1323,9 @@ export class ClaudeLLM extends llm.LLM {
1315
1323
  });
1316
1324
  }
1317
1325
  this.#pendingPermission = null;
1326
+ return true;
1318
1327
  }
1328
+ return false;
1319
1329
  }
1320
1330
  /**
1321
1331
  * Check if there's a pending permission request
@@ -1328,7 +1338,8 @@ export class ClaudeLLM extends llm.LLM {
1328
1338
  */
1329
1339
  getPendingPermission() {
1330
1340
  if (this.#pendingPermission) {
1331
- return { toolName: this.#pendingPermission.toolName, input: this.#pendingPermission.input };
1341
+ const { toolName, input, requestId } = this.#pendingPermission;
1342
+ return { toolName, input, requestId };
1332
1343
  }
1333
1344
  return null;
1334
1345
  }
@@ -1342,16 +1353,22 @@ export class ClaudeLLM extends llm.LLM {
1342
1353
  * The guard lives here (on the long-lived ClaudeLLM, not the per-turn stream) so a slow
1343
1354
  * write can't overlap the next turn's write. Never throws; never blocks the caller.
1344
1355
  */
1345
- triggerStoreUpdate(sessionId, workingDir) {
1346
- if (this.#storeUpdating || !sessionId || sessionId === 'pending' || !workingDir)
1356
+ triggerStoreUpdate(sessionId, workingDir, mainOnly = false) {
1357
+ if (!sessionId || sessionId === 'pending' || !workingDir)
1347
1358
  return;
1348
1359
  if (process.env.OSBORN_STORE === '0')
1349
1360
  return;
1361
+ // A request during a sweep runs once after it (a full sweep if any request was full),
1362
+ // so the turn-end sweep is never lost.
1363
+ if (this.#storeUpdating) {
1364
+ this.#storeUpdateAgain = { sessionId, workingDir, mainOnly: mainOnly && (this.#storeUpdateAgain?.mainOnly ?? true) };
1365
+ return;
1366
+ }
1350
1367
  this.#storeUpdating = true;
1351
1368
  (async () => {
1352
1369
  try {
1353
1370
  const embed = process.env.OSBORN_EMBED === '0' ? undefined : (await getEmbedder()) ?? undefined;
1354
- const stats = await updateSessionStore(sessionId, workingDir, { embed });
1371
+ const stats = await updateSessionStore(sessionId, workingDir, { embed, mainOnly });
1355
1372
  if (stats.newRows > 0)
1356
1373
  console.log(`🗄️ [store] +${stats.newRows} rows (${stats.totalRows} total, embedded=${stats.embeddedRows}) across main+subagents`);
1357
1374
  }
@@ -1360,6 +1377,10 @@ export class ClaudeLLM extends llm.LLM {
1360
1377
  }
1361
1378
  finally {
1362
1379
  this.#storeUpdating = false;
1380
+ const again = this.#storeUpdateAgain;
1381
+ this.#storeUpdateAgain = null;
1382
+ if (again)
1383
+ this.triggerStoreUpdate(again.sessionId, again.workingDir, again.mainOnly);
1363
1384
  }
1364
1385
  })();
1365
1386
  }
@@ -1445,6 +1466,13 @@ export class ClaudeLLM extends llm.LLM {
1445
1466
  }
1446
1467
  /** Read-only accessor used by ClaudeLLMStream (private fields are class-scoped). */
1447
1468
  get turbo() { return this.#turbo; }
1469
+ /** A phone caller holds this session (index.ts sets it per voice session): tools are denied. */
1470
+ setPhoneCall(on) {
1471
+ if (this.#phoneCall !== on)
1472
+ console.log(`📞 Phone call ${on ? 'ON: tools denied' : 'OFF'}`);
1473
+ this.#phoneCall = on;
1474
+ }
1475
+ get phoneCall() { return this.#phoneCall; }
1448
1476
  // Steer-priority suppression state (adversarial findings #1/#8): a 'now'
1449
1477
  // message aborts the running turn, so never stamp it while that turn is
1450
1478
  // parked on a permission dialog (the user's spoken "yes, allow it" would
@@ -2225,6 +2253,12 @@ export class ClaudeLLM extends llm.LLM {
2225
2253
  // errored, or its turn aborted) — drop it so it can't poison the next
2226
2254
  // agent_id pairing of the same type.
2227
2255
  this.#pendingToolUseByType.clear();
2256
+ // Ingest the finished reply now: the submit-time sweep ran before it was
2257
+ // written, so /session-messages would lack it until the next turn (#153).
2258
+ // Main JSONL only; the next submit-time sweep picks up sub-agents.
2259
+ const sid = msg.session_id || this.#sessionId;
2260
+ if (sid && this.#opts.workingDirectory)
2261
+ this.triggerStoreUpdate(sid, this.#opts.workingDirectory, true);
2228
2262
  console.log('✅ Claude turn complete (persistent session stays alive)');
2229
2263
  }
2230
2264
  }
@@ -2287,9 +2321,10 @@ export class ClaudeLLM extends llm.LLM {
2287
2321
  // Pass permission handler for canUseTool callback
2288
2322
  onPermissionRequest: (toolName, input) => {
2289
2323
  return new Promise((resolve) => {
2290
- this.#pendingPermission = { toolName, input, resolve };
2291
- console.log(`⚠️ Permission request: ${toolName}`);
2292
- this.#eventEmitter.emit('permission_request', { toolName, input });
2324
+ const requestId = crypto.randomUUID();
2325
+ this.#pendingPermission = { toolName, input, requestId, resolve };
2326
+ console.log(`⚠️ Permission request: ${toolName} (${requestId.slice(0, 8)})`);
2327
+ this.#eventEmitter.emit('permission_request', { toolName, input, requestId });
2293
2328
  });
2294
2329
  },
2295
2330
  });
@@ -2320,6 +2355,16 @@ class ClaudeLLMStream extends llm.LLMStream {
2320
2355
  // SubagentStart can label the Running row with WHAT the sub-agent is doing even if the
2321
2356
  // SDK hook input omits the prompt. Cleared when consumed by the matching start.
2322
2357
  #pendingTaskByType = new Map();
2358
+ // Steward verdicts and gate events go to the session's sidecar (steward.jsonl) so a reload rebuilds them.
2359
+ #recordSteward(rec) {
2360
+ try {
2361
+ if (this.#sessionId && this.#opts.workingDirectory)
2362
+ appendStewardRecord(this.#sessionId, this.#opts.workingDirectory, rec);
2363
+ }
2364
+ catch (e) {
2365
+ console.warn('steward record persist failed:', e instanceof Error ? e.message : e);
2366
+ }
2367
+ }
2323
2368
  constructor(llmInstance, { chatCtx, toolCtx, connOptions, opts, sessionId, onSessionId, eventEmitter, onCheckpoint, onPermissionRequest, abortController, primeOnly, }) {
2324
2369
  super(llmInstance, { chatCtx, toolCtx, connOptions });
2325
2370
  this.#llmRef = llmInstance;
@@ -2515,6 +2560,13 @@ class ClaudeLLMStream extends llm.LLMStream {
2515
2560
  const toolInput = input?.tool_input || {};
2516
2561
  const agentType = input?.agent_type || null;
2517
2562
  console.log(`🔍 PreToolUse: toolName=${toolName} agent_type=${agentType} agent_id=${input?.agent_id || 'none'} all_keys=[${Object.keys(input || {}).join(', ')}]`);
2563
+ // Phone call: talk-only. Runs before allowedTools, so it also stops the
2564
+ // auto-approved tools, sub-agent dispatch and MCP tools.
2565
+ if (phoneToolPolicy(this.#llmRef.phoneCall) === 'deny') {
2566
+ console.log(`📞 Phone call: denied ${toolName} (phone tools are off)`);
2567
+ this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: 'Tools are off on a phone call.', agent: agentType ?? 'main' });
2568
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: PHONE_TOOLS_DENIED };
2569
+ }
2518
2570
  // Spoken-progress cadence + runaway backstop (main orchestrator only).
2519
2571
  // Only the MAIN agent's direct tool calls count (agent_type === null).
2520
2572
  // Task/Agent delegations and sub-agent calls are exempt.
@@ -2543,8 +2595,10 @@ class ClaudeLLMStream extends llm.LLMStream {
2543
2595
  let stewardNote = null; // advise mode: rides the allow tail below
2544
2596
  if (toolName === 'Bash') {
2545
2597
  const gate = await stewardGate(String(toolInput.command || ''), this.#opts.workingDirectory || process.cwd());
2546
- if (gate.decision !== 'allow')
2598
+ if (gate.decision !== 'allow') {
2599
+ this.#recordSteward({ gate: gate.decision, message: gate.message ?? '', at: new Date().toISOString() });
2547
2600
  this.#eventEmitter.emit('steward_gate', { decision: gate.decision, message: gate.message });
2601
+ }
2548
2602
  if (gate.decision === 'deny') {
2549
2603
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gate.message };
2550
2604
  }
@@ -2980,7 +3034,7 @@ class ClaudeLLMStream extends llm.LLMStream {
2980
3034
  // ON by default; OSBORN_CONTENT_LENS=0|off|false|no disables. Spawn is sync + unref'd: never awaited.
2981
3035
  try {
2982
3036
  if (!['0', 'off', 'false', 'no'].includes((process.env.OSBORN_CONTENT_LENS || '').trim().toLowerCase())) {
2983
- const cl = launchCompactionLens({ sessionId: input?.session_id || sessionId, transcriptPath: input?.transcript_path, cwd: this.#opts.workingDirectory });
3037
+ const cl = launchCompactionLensWithRetry({ sessionId: input?.session_id || sessionId, transcriptPath: input?.transcript_path, cwd: this.#opts.workingDirectory });
2984
3038
  progress('Content lens', cl.status === 'spawned' ? 'background worker started' : cl.status);
2985
3039
  }
2986
3040
  }
@@ -3069,13 +3123,7 @@ class ClaudeLLMStream extends llm.LLMStream {
3069
3123
  const atRole = roleOf(at, this.#opts.agentRoles, NAMED_AGENTS);
3070
3124
  const verdict = atRole && ROLES[atRole].verdict ? parseStewardVerdict(msg) : null;
3071
3125
  if (verdict) {
3072
- try {
3073
- if (this.#sessionId && this.#opts.workingDirectory)
3074
- appendStewardVerdict(this.#sessionId, this.#opts.workingDirectory, verdict);
3075
- }
3076
- catch (e) {
3077
- console.warn('steward verdict persist failed:', e instanceof Error ? e.message : e);
3078
- }
3126
+ this.#recordSteward(verdict);
3079
3127
  this.#eventEmitter.emit('steward_verdict', verdict);
3080
3128
  }
3081
3129
  // Pattern #1 verifier chaining — CORRECT timing (moved here from PostToolUse).
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { McpServerConfig } from './claude-handler.js';
2
+ import { type ApprovalMode } from './approval-policy.js';
2
3
  export type VoiceMode = 'pipeline';
3
4
  export type EditMode = 'read-only' | 'edit';
4
5
  export type AgentMode = 'plan' | 'execute' | 'research';
@@ -26,7 +27,18 @@ export interface OsbornConfig {
26
27
  voiceMode?: VoiceMode;
27
28
  direct?: DirectConfig;
28
29
  inference?: InferenceConfig;
30
+ approvalMode?: ApprovalMode;
29
31
  }
32
+ /** The saved approval mode (config.yaml `approvalMode`); 'ask' when unset or unreadable. */
33
+ export declare function readApprovalMode(file?: string): ApprovalMode;
34
+ /**
35
+ * Saves the approval mode into config.yaml. The YAML document is edited in
36
+ * place, so every other key and its comments survive, and the file keeps its
37
+ * permissions. Written to a temp file and renamed, so a crash never leaves a
38
+ * half-written config. Refuses (false) when the existing file cannot be
39
+ * parsed or is not a mapping, rather than overwrite it.
40
+ */
41
+ export declare function writeApprovalMode(mode: ApprovalMode, configFile?: string): boolean;
30
42
  interface McpServerConfigYaml {
31
43
  enabled?: boolean;
32
44
  command?: string;
@@ -180,22 +192,6 @@ export interface ClaudeSessionEntry {
180
192
  * the JSONL file. This function is only reached when that fails.
181
193
  */
182
194
  export declare function slugToPath(slug: string): string;
183
- /**
184
- * Extract cwd from the first JSONL entry that carries a `cwd` field.
185
- *
186
- * Previously: read only the first 8KB and only accepted `type === 'user'`. That
187
- * broke for sessions whose first JSONL entry was larger than 8KB — e.g. a
188
- * `queue-operation` containing pasted email/page text. readline never emits the
189
- * `line` event for an incomplete final chunk, so the scan finds nothing,
190
- * `listAllClaudeSessions` falls through to the lossy `slugToPath` reverse, and
191
- * the mangled path ends up as a `cwd` passed to `child_process.spawn`, producing
192
- * the misleading "Claude Code executable not found" error (see MEMORY bug #11).
193
- *
194
- * Now: stream line-by-line with no byte cap, short-circuit on the first entry
195
- * with a `cwd` field regardless of `type` (every `user` / `attachment` /
196
- * `assistant` / `system` entry in a Claude JSONL session carries `cwd`, so the
197
- * scan finishes in the first few KB of any normal session).
198
- */
199
195
  export declare function extractCwd(filePath: string): Promise<string>;
200
196
  export declare function invalidateSessionListCache(): void;
201
197
  /**
package/dist/config.js CHANGED
@@ -1,11 +1,67 @@
1
- import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync } from 'fs';
1
+ import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, chmodSync, realpathSync, lstatSync, readlinkSync } from 'fs';
2
2
  import { homedir } from 'os';
3
- import { join } from 'path';
4
- import { parse, stringify } from 'yaml';
3
+ import { dirname, join, resolve } from 'path';
4
+ import { Document, isMap, parse, parseDocument, stringify } from 'yaml';
5
5
  import { cleanTurnText } from './content/transcript-sanitizer.js';
6
+ import { projectPathToSlug } from './session-access.js';
7
+ import { DEFAULT_APPROVAL_MODE, isApprovalMode } from './approval-policy.js';
6
8
  // Config file paths
7
9
  const CONFIG_DIR = join(homedir(), '.osborn');
8
10
  const CONFIG_FILE = join(CONFIG_DIR, 'config.yaml');
11
+ /** The saved approval mode (config.yaml `approvalMode`); 'ask' when unset or unreadable. */
12
+ export function readApprovalMode(file = CONFIG_FILE) {
13
+ try {
14
+ const mode = parse(readFileSync(file, 'utf-8'))?.approvalMode;
15
+ return isApprovalMode(mode) ? mode : DEFAULT_APPROVAL_MODE;
16
+ }
17
+ catch {
18
+ return DEFAULT_APPROVAL_MODE;
19
+ }
20
+ }
21
+ /**
22
+ * Saves the approval mode into config.yaml. The YAML document is edited in
23
+ * place, so every other key and its comments survive, and the file keeps its
24
+ * permissions. Written to a temp file and renamed, so a crash never leaves a
25
+ * half-written config. Refuses (false) when the existing file cannot be
26
+ * parsed or is not a mapping, rather than overwrite it.
27
+ */
28
+ export function writeApprovalMode(mode, configFile = CONFIG_FILE) {
29
+ try {
30
+ // A symlinked config (dotfiles repo) is written through to its target; the link stays.
31
+ let file = configFile;
32
+ try {
33
+ if (lstatSync(configFile).isSymbolicLink()) {
34
+ file = existsSync(configFile) ? realpathSync(configFile) : resolve(dirname(configFile), readlinkSync(configFile));
35
+ }
36
+ }
37
+ catch { /* no file yet */ }
38
+ let doc = new Document({});
39
+ let fileMode = 0o600;
40
+ if (existsSync(file)) {
41
+ doc = parseDocument(readFileSync(file, 'utf-8'));
42
+ if (doc.errors.length)
43
+ return false;
44
+ if (doc.contents !== null && !isMap(doc.contents))
45
+ return false;
46
+ if (doc.contents === null)
47
+ doc.contents = doc.createNode({});
48
+ fileMode = statSync(file).mode & 0o777;
49
+ }
50
+ else {
51
+ mkdirSync(dirname(file), { recursive: true });
52
+ }
53
+ doc.set('approvalMode', mode);
54
+ const tmp = `${file}.tmp-${process.pid}`;
55
+ writeFileSync(tmp, String(doc), { encoding: 'utf-8', mode: fileMode });
56
+ chmodSync(tmp, fileMode);
57
+ renameSync(tmp, file);
58
+ return true;
59
+ }
60
+ catch (err) {
61
+ console.error(`❌ Failed to save approval mode: ${err.message}`);
62
+ return false;
63
+ }
64
+ }
9
65
  export const MCP_CATALOG = [
10
66
  // ── Cloud-hosted via Smithery Connect (no local install) ──────
11
67
  // URLs are Smithery proxy endpoints: api.smithery.ai/connect/{namespace}/{connectionId}/mcp
@@ -411,18 +467,11 @@ import { createReadStream, statSync, readdirSync, openSync, readSync, closeSync
411
467
  export function getClaudeProjectsDir() {
412
468
  return join(homedir(), '.claude', 'projects');
413
469
  }
414
- /**
415
- * Convert a project path to the .claude folder naming format
416
- * e.g., /Users/foo/bar -> -Users-foo-bar
417
- */
418
- function projectPathToClaudeFolderName(projectPath) {
419
- return projectPath.replace(/\//g, '-');
420
- }
421
470
  /**
422
471
  * Get the session storage directory for a specific project
423
472
  */
424
473
  export function getSessionDir(projectPath) {
425
- const claudeFolderName = projectPathToClaudeFolderName(projectPath);
474
+ const claudeFolderName = projectPathToSlug(projectPath);
426
475
  return join(getClaudeProjectsDir(), claudeFolderName);
427
476
  }
428
477
  /**
@@ -561,9 +610,9 @@ function scanPreviewLines(text, skipFirstPartial) {
561
610
  * gate and (b) the LAST user message. So: small files are read whole (exact);
562
611
  * large files read a bounded HEAD (gate + density sample + first turn/title) +
563
612
  * TAIL (last user message, last activity), turning a hundreds-of-MB parse into
564
- * ~192KB. messageCount becomes an estimate for large files — it's display-only,
565
- * and is derived from BOTH samples because a compacted transcript can have no
566
- * countable turn in the head at all.
613
+ * ~192KB. messageCount becomes a lower bound for large files (the turns in
614
+ * both samples) — it's display-only, and counts BOTH samples because a
615
+ * compacted transcript can have no countable turn in the head at all.
567
616
  */
568
617
  async function getSessionPreview(filePath, fileSize) {
569
618
  const HEAD = 64 * 1024;
@@ -604,10 +653,8 @@ async function getSessionPreview(filePath, fileSize) {
604
653
  const head = scanPreviewLines(headBuf.toString('utf8', 0, hn), false);
605
654
  const tail = scanPreviewLines(tailBuf.toString('utf8', 0, tn), true);
606
655
  const lastMessage = tail.lastUser ?? head.lastUser;
607
- // Density from BOTH samples: a compacted transcript opens with a
608
- // compact_boundary plus tool records, so head.count alone can be 0.
609
- const sampled = head.count + tail.count;
610
- const messageCount = sampled > 0 ? Math.max(3, Math.round(size * sampled / (hn + tn))) : 3;
656
+ // A lower bound: the turns in both samples, floored at 3 to clear the list gate.
657
+ const messageCount = Math.max(3, head.count + tail.count);
611
658
  return {
612
659
  lastMessage,
613
660
  title: tail.aiTitle ?? head.aiTitle ?? head.firstUser,
@@ -684,11 +731,13 @@ const UUID_JSONL_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]
684
731
  * `assistant` / `system` entry in a Claude JSONL session carries `cwd`, so the
685
732
  * scan finishes in the first few KB of any normal session).
686
733
  */
734
+ const EXTRACT_CWD_MAX_LINES = 50;
687
735
  export async function extractCwd(filePath) {
688
736
  return new Promise((resolve) => {
689
737
  const fileStream = createReadStream(filePath);
690
738
  const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
691
739
  let resolved = false;
740
+ let lines = 0;
692
741
  const done = (value) => {
693
742
  if (resolved)
694
743
  return;
@@ -706,6 +755,9 @@ export async function extractCwd(filePath) {
706
755
  rl.on('line', (line) => {
707
756
  if (resolved)
708
757
  return;
758
+ // Capped: an old JSONL with no cwd must not stream whole on connect.
759
+ if (++lines > EXTRACT_CWD_MAX_LINES)
760
+ return done('');
709
761
  if (!line.trim())
710
762
  return;
711
763
  try {
@@ -729,7 +781,8 @@ export function invalidateSessionListCache() {
729
781
  }
730
782
  // Older manifests are discarded on load. v2: sanitized preview fields. v3: the
731
783
  // large-file messageCount estimate changed, and unchanged files are never re-read.
732
- const SESSION_MANIFEST_VERSION = 3;
784
+ // v4: the large-file count is the sampled lower bound.
785
+ const SESSION_MANIFEST_VERSION = 4;
733
786
  function sessionManifestPath() {
734
787
  return join(homedir(), '.claude', 'session-manifest.json');
735
788
  }
@@ -902,7 +955,8 @@ export async function listAllClaudeSessions(limit = 1000, includeSubagents = fal
902
955
  sessionId: c.sessionId,
903
956
  projectSlug: c.slug,
904
957
  projectPath: cwd || slugPath, // display / group key (original cwd)
905
- cwd: slugPath || cwd, // resume routing (file location)
958
+ // The recorded cwd when it encodes to this slug: the lossy decode can name another project (#181).
959
+ cwd: (cwd && projectPathToSlug(cwd) === c.slug ? cwd : '') || slugPath || cwd, // resume routing (file location)
906
960
  timestamp: c.mtime,
907
961
  lastMessage: preview.lastMessage,
908
962
  title: preview.title,
@@ -1147,7 +1201,7 @@ export async function cleanupOrphanedMetadata(projectPath) {
1147
1201
  */
1148
1202
  export function getSessionWorkspace(workingDir, sessionId) {
1149
1203
  const claudeDir = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
1150
- const slug = projectPathToClaudeFolderName(workingDir);
1204
+ const slug = projectPathToSlug(workingDir);
1151
1205
  return join(claudeDir, 'projects', slug, 'osb', sessionId);
1152
1206
  }
1153
1207
  export function ensureSessionWorkspace(workingDir, sessionId) {
@@ -13,6 +13,11 @@
13
13
  * copy to <path> instead of content-profile.md and leaves the HWM alone.
14
14
  * node compaction-lens-worker.js --library <sessionId> [--cwd <dir>] [--dry] [--out-dir <dir>]
15
15
  * LIBRARY step only (manual / dry run). Takes the per-project lock itself.
16
+ * node compaction-lens-worker.js --sweep [--exclude <id,id>] [--dry] [--max N]
17
+ * CATCH-UP SWEEP only (lens-library-sweep.ts): the Library backlog of every session on the
18
+ * machine plus the daily digests, newest first, capped. Takes the machine-wide sweep lock.
19
+ * The agent also launches it shortly after start (argfile { sweep }) and after each
20
+ * session-end run (the session-end argfile carries { sweep }; it runs after the steps).
16
21
  * node compaction-lens-worker.js --content <sessionId> [--cwd <dir>] [--dry] [--research-refresh]
17
22
  * CONTENT step (Stage A) only: manual / the per-project "Refresh research"
18
23
  * backend. --dry = no ingest (still spends, capped). Takes the per-project lock.
@@ -13,6 +13,11 @@
13
13
  * copy to <path> instead of content-profile.md and leaves the HWM alone.
14
14
  * node compaction-lens-worker.js --library <sessionId> [--cwd <dir>] [--dry] [--out-dir <dir>]
15
15
  * LIBRARY step only (manual / dry run). Takes the per-project lock itself.
16
+ * node compaction-lens-worker.js --sweep [--exclude <id,id>] [--dry] [--max N]
17
+ * CATCH-UP SWEEP only (lens-library-sweep.ts): the Library backlog of every session on the
18
+ * machine plus the daily digests, newest first, capped. Takes the machine-wide sweep lock.
19
+ * The agent also launches it shortly after start (argfile { sweep }) and after each
20
+ * session-end run (the session-end argfile carries { sweep }; it runs after the steps).
16
21
  * node compaction-lens-worker.js --content <sessionId> [--cwd <dir>] [--dry] [--research-refresh]
17
22
  * CONTENT step (Stage A) only: manual / the per-project "Refresh research"
18
23
  * backend. --dry = no ingest (still spends, capped). Takes the per-project lock.
@@ -25,13 +30,14 @@
25
30
  * Fully self-contained: top-level try/catch, redacted log in the project dir,
26
31
  * refreshes + releases the per-project lock, always exits.
27
32
  */
28
- import { readFileSync, rmSync } from 'node:fs';
33
+ import { mkdirSync, readFileSync, rmSync } from 'node:fs';
29
34
  import { dirname } from 'node:path';
30
35
  import { runCompactionLens } from './compaction-lens.js';
31
36
  import { resolveSessionDb } from './lens-db.js';
32
- import { acquireLock, refuseOutPath, releaseLock, resolveProjectDir, touchLock } from './lens-paths.js';
37
+ import { acquireLock, libraryHomeDir, readSweepStatus, refuseOutPath, releaseLock, resolveProjectDir, touchLock, writeSweepStatus } from './lens-paths.js';
33
38
  import { logLine } from './lens-profile.js';
34
39
  import { runLibraryStep } from './lens-library.js';
40
+ import { errorLine, runLibrarySweep } from './lens-library-sweep.js';
35
41
  import { runContentStep } from './content-run.js';
36
42
  // ≤2 big windows + reduce at ≤6 min/call, then the library step (1 call ≤6 min + model meta),
37
43
  // then the content step (Stage A: ~10-18 small calls, ≤4 min each, capped in $).
@@ -39,11 +45,25 @@ const INCREMENTAL_TIMEOUT_MS = 45 * 60_000;
39
45
  const BACKFILL_TIMEOUT_MS = 3 * 60 * 60_000;
40
46
  const LIBRARY_TIMEOUT_MS = 15 * 60_000;
41
47
  const CONTENT_TIMEOUT_MS = 20 * 60_000;
48
+ // The sweep stops starting pages after SWEEP_BUDGET_MS (60 min); one page call is ≤6 min.
49
+ const SWEEP_TIMEOUT_MS = 80 * 60_000;
42
50
  function argVal(argv, flag) {
43
51
  const i = argv.indexOf(flag);
44
52
  return i >= 0 ? argv[i + 1] : undefined;
45
53
  }
46
54
  function parseJob(argv) {
55
+ if (argv[0] === '--sweep') {
56
+ const max = Number(argVal(argv, '--max'));
57
+ const exclude = (argVal(argv, '--exclude') ?? '').split(',').map(s => s.trim()).filter(Boolean);
58
+ return {
59
+ opts: { sessionId: '', mode: 'incremental' },
60
+ kind: 'sweep',
61
+ sweep: { exclude, trigger: 'manual', dry: argv.includes('--dry'), max: Number.isFinite(max) && max > 0 ? max : undefined, print: true },
62
+ lockDir: null,
63
+ logDir: libraryHomeDir(),
64
+ timeoutMs: SWEEP_TIMEOUT_MS,
65
+ };
66
+ }
47
67
  if (argv[0] === '--content') {
48
68
  const sessionId = argv[1];
49
69
  if (!sessionId || sessionId.startsWith('--'))
@@ -124,6 +144,11 @@ function parseJob(argv) {
124
144
  /* ignore */
125
145
  }
126
146
  }
147
+ const sweep = payload.sweep && Array.isArray(payload.sweep.exclude) ? { exclude: payload.sweep.exclude.map(String), trigger: String(payload.sweep.trigger ?? 'launch') } : undefined;
148
+ if (sweep && !payload.sessionId) {
149
+ // Standalone sweep (agent start, or a session end whose project was busy).
150
+ return { opts: { sessionId: '', mode: 'incremental' }, kind: 'sweep', sweep, sweepLockHeld: payload.sweepLockHeld === true, lockDir: null, logDir: libraryHomeDir(), timeoutMs: SWEEP_TIMEOUT_MS };
151
+ }
127
152
  const lockDir = payload.lockDir || null;
128
153
  const logDir = lockDir || resolveProjectDir(payload.transcriptPath, payload.cwd);
129
154
  if (!payload.sessionId)
@@ -131,11 +156,14 @@ function parseJob(argv) {
131
156
  return {
132
157
  opts: { sessionId: payload.sessionId, transcriptPath: payload.transcriptPath, cwd: payload.cwd, mode: 'incremental' },
133
158
  skipLens: payload.skipLens === true,
159
+ sweep,
134
160
  lockDir,
135
161
  logDir,
136
- timeoutMs: INCREMENTAL_TIMEOUT_MS,
162
+ timeoutMs: INCREMENTAL_TIMEOUT_MS + (sweep ? SWEEP_TIMEOUT_MS : 0),
137
163
  };
138
164
  }
165
+ /** Set while this worker holds the machine-wide sweep lock. */
166
+ let sweepHome = null;
139
167
  async function main() {
140
168
  let job = null;
141
169
  let logDir = null;
@@ -151,18 +179,23 @@ async function main() {
151
179
  }
152
180
  lockDir = job.lockDir;
153
181
  logDir = job.logDir;
154
- const sid = job.opts.sessionId.substring(0, 8);
182
+ const sid = job.opts.sessionId.substring(0, 8) || 'sweep';
183
+ const steps = job.kind !== 'sweep';
155
184
  const killer = setTimeout(() => {
156
185
  logLine(logDir, `session ${sid}: hard timeout — exiting`);
157
186
  if (lockDir)
158
187
  releaseLock(lockDir);
188
+ if (sweepHome) {
189
+ writeSweepStatus({ status: 'timeout', finishedAt: new Date().toISOString(), errors: [...(readSweepStatus(sweepHome)?.errors ?? []), { kind: 'timeout' }] }, sweepHome);
190
+ releaseLock(sweepHome);
191
+ }
159
192
  process.exit(2);
160
193
  }, job.timeoutMs);
161
194
  killer.unref();
162
195
  const t0 = Date.now();
163
196
  let lensErr = null;
164
197
  // Step 1 — content lens (skipped by the --library entry).
165
- if (job.kind !== 'library' && job.kind !== 'content' && !job.skipLens) {
198
+ if (steps && job.kind !== 'library' && job.kind !== 'content' && !job.skipLens) {
166
199
  try {
167
200
  const r = await runCompactionLens({
168
201
  ...job.opts,
@@ -183,7 +216,7 @@ async function main() {
183
216
  // Step 2 — library page for the period that just ended (per-compaction + --library only; never backfill).
184
217
  // runLibraryStep never throws; any failure is logged and the worker still exits cleanly.
185
218
  let libPeriod = null;
186
- if (job.opts.mode === 'incremental' && job.kind !== 'content') {
219
+ if (steps && job.opts.mode === 'incremental' && job.kind !== 'content') {
187
220
  if (lockDir)
188
221
  touchLock(lockDir);
189
222
  const lib = await runLibraryStep({
@@ -199,10 +232,17 @@ async function main() {
199
232
  process.stdout.write(`${JSON.stringify({ status: lib.status, page: lib.page, index: lib.index, period: lib.period, cost: lib.costUsd, errors: lib.errors })}\n`);
200
233
  if (lib.status === 'written')
201
234
  libPeriod = lib.period;
235
+ // The step's real outcome, on /health (the worker's own output goes nowhere).
236
+ if (job.kind !== 'library') {
237
+ writeSweepStatus({ lastStep: { at: new Date().toISOString(), session: sid, status: lib.status, ...(lib.period ? { period: lib.period.index } : {}), costUsd: lib.costUsd } });
238
+ }
239
+ if (lib.status === 'failed' || lib.status === 'model-error') {
240
+ writeSweepStatus({ workerError: { at: new Date().toISOString(), kind: `library-${lib.status}`, ref: sid, message: errorLine(lib.errors.join('; ')) } });
241
+ }
202
242
  }
203
243
  // Step 3 — content plan (Stage A) for the period (per-compaction + --content; never backfill / --library).
204
244
  // runContentStep never throws; the try is belt and braces so nothing here can fail the worker.
205
- if (job.opts.mode === 'incremental' && job.kind !== 'library') {
245
+ if (steps && job.opts.mode === 'incremental' && job.kind !== 'library') {
206
246
  try {
207
247
  if (lockDir)
208
248
  touchLock(lockDir);
@@ -224,17 +264,48 @@ async function main() {
224
264
  logLine(logDir, `content step error (ignored): ${err instanceof Error ? err.message : String(err)}`);
225
265
  }
226
266
  }
267
+ // Step 4 — catch-up sweep (agent start, after a session end, or --sweep). Never two at once:
268
+ // the machine-wide sweep lock is either handed over by the launcher or taken here.
269
+ if (job.sweep) {
270
+ const home = libraryHomeDir();
271
+ mkdirSync(home, { recursive: true });
272
+ // This session's steps are done: free its project for the next compaction run; the sweep
273
+ // takes each project's lock only while it writes a page there.
274
+ if (lockDir)
275
+ releaseLock(lockDir);
276
+ lockDir = null;
277
+ if (job.sweepLockHeld || acquireLock(home)) {
278
+ sweepHome = home;
279
+ // A manual --sweep (print) is never held back by the cooldown.
280
+ const s = await runLibrarySweep({ exclude: job.sweep.exclude, trigger: job.sweep.trigger, dry: job.sweep.dry, maxPages: job.sweep.max, ...(job.sweep.print ? { cooldownMs: 0 } : {}) });
281
+ logLine(logDir, `session ${sid}: sweep status=${s.status} pages=${s.pagesWritten} digests=${s.digestsWritten} calls=${s.modelCalls} cost=$${s.costUsd.toFixed(4)} errors=${s.errors.length}`);
282
+ if (job.sweep.print)
283
+ process.stdout.write(`${JSON.stringify(s)}\n`);
284
+ }
285
+ else {
286
+ logLine(logDir, `session ${sid}: sweep skipped (another sweep is running)`);
287
+ if (job.sweep.print)
288
+ process.stderr.write('sweep: another sweep is running\n');
289
+ }
290
+ }
227
291
  return lensErr ? 1 : 0;
228
292
  }
229
293
  catch (err) {
230
294
  logLine(logDir, `worker error: ${err instanceof Error ? err.stack || err.message : String(err)}`);
231
295
  if (err instanceof Error && /^(backfill|library|content):/.test(err.message))
232
296
  process.stderr.write(`${err.message}\n`);
297
+ // Visible on /health: a crashed worker no longer disappears into stdio 'ignore'.
298
+ writeSweepStatus({
299
+ ...(sweepHome ? { status: 'error', finishedAt: new Date().toISOString() } : {}),
300
+ workerError: { at: new Date().toISOString(), kind: job?.kind ?? 'worker', message: errorLine(err) },
301
+ });
233
302
  return 1;
234
303
  }
235
304
  finally {
236
305
  if (lockDir)
237
306
  releaseLock(lockDir);
307
+ if (sweepHome)
308
+ releaseLock(sweepHome);
238
309
  }
239
310
  }
240
311
  main()