osborn 0.9.271 → 0.9.275

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 (61) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +82 -30
  2. package/.claude/skills/browser-apply/candidate.example.env +16 -0
  3. package/.claude/skills/browser-apply/fill.mjs +294 -0
  4. package/Dockerfile +1 -1
  5. package/dist/claude-auth.d.ts +85 -6
  6. package/dist/claude-auth.js +202 -22
  7. package/dist/claude-llm.d.ts +13 -0
  8. package/dist/claude-llm.js +171 -25
  9. package/dist/compaction-log.d.ts +67 -0
  10. package/dist/compaction-log.js +195 -0
  11. package/dist/config.d.ts +18 -0
  12. package/dist/config.js +122 -65
  13. package/dist/content/transcript-sanitizer.d.ts +20 -6
  14. package/dist/content/transcript-sanitizer.js +66 -11
  15. package/dist/data-sender-auth.d.ts +90 -0
  16. package/dist/data-sender-auth.js +158 -0
  17. package/dist/duck.d.ts +8 -0
  18. package/dist/duck.js +59 -0
  19. package/dist/env-keys.js +11 -0
  20. package/dist/index.js +493 -97
  21. package/dist/lib/safe-artifact-path.d.ts +17 -0
  22. package/dist/lib/safe-artifact-path.js +129 -0
  23. package/dist/meeting-addressing.d.ts +176 -0
  24. package/dist/meeting-addressing.js +288 -0
  25. package/dist/pipeline-direct-llm.d.ts +52 -1
  26. package/dist/pipeline-direct-llm.js +206 -61
  27. package/dist/prompts/direct-mode-fallback.md +1 -1
  28. package/dist/prompts/direct-mode-research.md +2 -2
  29. package/dist/prompts.d.ts +1 -1
  30. package/dist/prompts.js +3 -3
  31. package/dist/pushover.d.ts +77 -0
  32. package/dist/pushover.js +276 -0
  33. package/dist/recall-client.js +21 -2
  34. package/dist/session-store.d.ts +15 -5
  35. package/dist/session-store.js +37 -10
  36. package/dist/transcript-wiring.d.ts +121 -0
  37. package/dist/transcript-wiring.js +252 -0
  38. package/dist/voice-io.d.ts +0 -9
  39. package/dist/voice-io.js +5 -19
  40. package/dist/watch-gateway.d.ts +38 -0
  41. package/dist/watch-gateway.js +205 -0
  42. package/package.json +1 -1
  43. package/scripts/review.ts +1 -1
  44. package/dist/bridge-llm.d.ts +0 -22
  45. package/dist/bridge-llm.js +0 -39
  46. package/dist/codex-handler.d.ts +0 -38
  47. package/dist/codex-handler.js +0 -83
  48. package/dist/codex-llm.d.ts +0 -40
  49. package/dist/codex-llm.js +0 -144
  50. package/dist/fast-brain.d.ts +0 -176
  51. package/dist/fast-brain.js +0 -1887
  52. package/dist/index-3-2-26-legacy.d.ts +0 -1
  53. package/dist/index-3-2-26-legacy.js +0 -2233
  54. package/dist/leagcyprompts2.d.ts +0 -0
  55. package/dist/leagcyprompts2.js +0 -573
  56. package/dist/prompts-2-25-26.d.ts +0 -0
  57. package/dist/prompts-2-25-26.js +0 -518
  58. package/dist/prompts-3-2-26.d.ts +0 -78
  59. package/dist/prompts-3-2-26.js +0 -1319
  60. package/dist/summary-index.d.ts +0 -90
  61. package/dist/summary-index.js +0 -585
@@ -13,8 +13,10 @@ import { saveSessionMetadata, getSessionWorkspace } from './config.js';
13
13
  import { statusManager } from './status-manager.js';
14
14
  import { getResearchSystemPrompt, getDirectModeResearchPrompt, getGroundingBlock, getRecalledContextBlock } from './prompts.js';
15
15
  import { openStore, recall, storeExists, updateSessionStore, getStorePath } from './session-store.js';
16
+ import { appendCompactionRecord, countTranscriptRows } from './compaction-log.js';
16
17
  import { getEmbedder } from './embedder.js';
17
18
  import { launchCompactionLens } from './content/lens-launch.js';
19
+ import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
18
20
  import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
19
21
  import { join, dirname, resolve, basename } from 'node:path';
20
22
  import { fileURLToPath } from 'node:url';
@@ -115,13 +117,33 @@ function logCacheUsage(usage) {
115
117
  }
116
118
  catch { /* observability only */ }
117
119
  }
118
- // ≤5 direct tool call budget per turn. Reset on every UserPromptSubmit (new user message).
119
- // Enforced mechanically in PreToolUse — the model CANNOT exceed this regardless of JSONL history.
120
- // Task/Agent delegations are exempt (delegation is what we WANT). Sub-agent tool calls
121
- // (agent_type !== null) are exempt (they're inside a delegation). Only the main orchestrator
122
- // agent's direct tool calls count against the budget.
120
+ // Spoken-progress CADENCE (not a work cap). The main orchestrator agent may run as many direct
121
+ // tool calls as a turn genuinely needs — we no longer STOP its work. Instead, every
122
+ // SPEAK_CADENCE_N main-agent tool calls we inject a NON-BLOCKING note (PreToolUse
123
+ // additionalContext) nudging it to say ONE short spoken progress line before its next call, then
124
+ // keep going (do it itself or delegate — its choice). Reset on every UserPromptSubmit (new user
125
+ // message). Task/Agent delegations and sub-agent calls (agent_type !== null) do NOT count.
126
+ //
127
+ // TOOL_HARD_CEILING is a pure runaway/crash backstop (heap-OOM history on pathological deep
128
+ // turns), NOT a workflow cap — a healthy turn never approaches it. Env-tunable; set
129
+ // OSBORN_TOOL_HARD_CEILING=0 to disable the backstop entirely.
123
130
  let turnToolCallCount = 0;
124
- const TOOL_CALL_BUDGET = 5;
131
+ const SPEAK_CADENCE_N = 6;
132
+ const TOOL_HARD_CEILING = Number(process.env.OSBORN_TOOL_HARD_CEILING ?? 60);
133
+ // Armed when a cadence boundary is crossed; consumed at the PreToolUse allow/fall-through tail so
134
+ // the spoken-progress note rides the next ACTUALLY-allowed main-agent tool call (even if the exact
135
+ // cadence call was a deferred/denied write).
136
+ let pendingSpeakNudge = false;
137
+ // The cadence nudge text. Framed as a system note so the model never mistakes it for a user turn;
138
+ // asks for exactly ONE short spoken sentence (→ one text block → one tts_say → session.say), says
139
+ // "keep going, your call to do it yourself or delegate" and "do not stop" so it is never read as a
140
+ // turn-ender. Auto-suppressed if the user is mid-utterance (index.ts output gate) and routed
141
+ // correctly into meetings.
142
+ const speakProgressNudge = (n) => `[SPOKEN PROGRESS CADENCE — system note, not from the user] You've run ${n} tool calls on this ` +
143
+ `turn without checking in. Before your next tool call, say ONE short spoken sentence to the ` +
144
+ `user: plainly, what you just found or did and what you're doing next (~15 words, no question, ` +
145
+ `no menu). Then keep working — do it yourself or delegate via Task, your call. Do not stop, ` +
146
+ `wait, or ask permission; this is a nudge to stay audible, not to end the turn.`;
125
147
  // Writer PROVENANCE REMINDER (Chesterton's Fence): before the writer mutates a
126
148
  // version-controlled file it should review that file's git history so the edit is
127
149
  // backward-informed (root cause / prior + reverted attempts / cross-component coupling),
@@ -882,6 +904,31 @@ export const FAST_MODEL = 'haiku';
882
904
  // alternatives: 'qwen/qwen3-coder' (a hair faster), 'moonshotai/kimi-k2.6',
883
905
  // 'deepseek/deepseek-chat' (needs proxy — thinking mode breaks the tool loop)
884
906
  export const FALLBACK_MODEL = 'minimax/minimax-m3'; // OpenRouter tier baseline
907
+ // ── Deferred restart after an auth-backend change ──
908
+ // The persistent SDK subprocess inherits process.env (ANTHROPIC_BASE_URL /
909
+ // AUTH_TOKEN / model overrides) once, at spawn. When the auth backend changes
910
+ // mid-session (on-demand Claude sign-in replaces the z.ai/OpenRouter fallback),
911
+ // a live subprocess would keep routing to the fallback. requestAuthRestart()
912
+ // bumps a generation counter; each ClaudeLLM remembers the generation its
913
+ // subprocess was spawned under and, at the START of its next turn (pushMessage,
914
+ // only when no turn is streaming), closes the stale subprocess and cold-starts
915
+ // with `resume: <same sessionId>`. Nothing is aborted at request time — a turn
916
+ // that is currently streaming finishes normally on the old backend.
917
+ let authEnvGeneration = 0;
918
+ export function requestAuthRestart() {
919
+ authEnvGeneration++;
920
+ console.log(`🔑 Auth backend changed — persistent sessions will restart before their next turn (gen ${authEnvGeneration})`);
921
+ return authEnvGeneration;
922
+ }
923
+ export function getAuthEnvGeneration() { return authEnvGeneration; }
924
+ /**
925
+ * Pure decision: restart a live persistent subprocess before pushing the next
926
+ * message? Only when it was spawned under an older auth generation AND it is
927
+ * idle (no turn streaming, no interrupt settling).
928
+ */
929
+ export function shouldRestartForAuth(spawnGen, currentGen, turnsInFlight, interruptPending) {
930
+ return spawnGen !== currentGen && turnsInFlight <= 0 && !interruptPending;
931
+ }
885
932
  /**
886
933
  * Apply turbo override to an agents roster.
887
934
  * When turbo is true returns a DEEP COPY with every agent's model set to
@@ -943,11 +990,14 @@ const WRITE_RULES = {
943
990
  tester: { extensions: /\.(test|spec)\.[jt]sx?$/, label: 'test', matchBasename: true },
944
991
  reviewer: { extensions: /\.(md|markdown|mdx|txt|rst|adoc)$/i, label: 'documentation' },
945
992
  };
946
- /** Path is inside the per-session sandbox workspace. */
993
+ /**
994
+ * Path is inside the per-session sandbox workspace. Used by decideWrite's
995
+ * 'workspace' rule: true → write allowed, false → denied. Robust resolve+root
996
+ * check (NOT a substring) so a `..` traversal path like `…/osb/../../etc/foo`
997
+ * can't masquerade as a workspace path and widen the allow surface.
998
+ */
947
999
  function isWorkspacePath(filePath) {
948
- return !!filePath && (filePath.includes('/osb/') ||
949
- filePath.includes('.osborn/sessions/') ||
950
- filePath.includes('.osborn/research/'));
1000
+ return isSafeArtifactPath(filePath);
951
1001
  }
952
1002
  /**
953
1003
  * Decide a Write/Edit/MultiEdit for the acting agent (null = main orchestrator).
@@ -1179,6 +1229,15 @@ export class ClaudeLLM extends llm.LLM {
1179
1229
  // settles, so an enriched [INTERRUPTED] message can never land inside the
1180
1230
  // turn being aborted (a fold-in-flight message dies with that turn).
1181
1231
  #pendingInterrupt = null;
1232
+ // Auth generation the persistent subprocess was spawned under, and the number
1233
+ // of pushed user messages whose turn has not produced a `result` yet. Together
1234
+ // they drive the deferred restart (see requestAuthRestart()).
1235
+ #spawnAuthGen = authEnvGeneration;
1236
+ #turnsInFlight = 0;
1237
+ /** True when the live subprocess predates the latest auth-backend change. */
1238
+ get authRestartPending() {
1239
+ return !!this.#persistentQuery && this.#spawnAuthGen !== authEnvGeneration;
1240
+ }
1182
1241
  // Dedup guard — prevents double-firing reviewer/gate if SubagentStop fires
1183
1242
  // more than once for the same agent_id (e.g. retry edge cases).
1184
1243
  #dispatchedFor = new Set();
@@ -1842,6 +1901,7 @@ export class ClaudeLLM extends llm.LLM {
1842
1901
  this.#toolUseByAgentId.clear();
1843
1902
  this.#typeByAgentId.clear();
1844
1903
  this.#pendingInterrupt = null;
1904
+ this.#turnsInFlight = 0;
1845
1905
  console.log('🔒 Persistent session closed');
1846
1906
  }
1847
1907
  /**
@@ -1873,6 +1933,7 @@ export class ClaudeLLM extends llm.LLM {
1873
1933
  return;
1874
1934
  }
1875
1935
  console.log('🔥 primeResume: eager cold-start — resume replay overlaps connect (no user message)');
1936
+ this.#spawnAuthGen = authEnvGeneration;
1876
1937
  this.#messageChannel = new MessageChannel();
1877
1938
  this.#persistentQuery = query({ prompt: this.#messageChannel, options: sdkOptions });
1878
1939
  this.#activeQueries.add(this.#persistentQuery);
@@ -1910,6 +1971,17 @@ export class ClaudeLLM extends llm.LLM {
1910
1971
  session_id: this.#sessionId || '',
1911
1972
  ...(pushOpts?.priority && { priority: pushOpts.priority }),
1912
1973
  };
1974
+ // Deferred auth restart: the subprocess was spawned under a fallback backend
1975
+ // that has since been replaced (Claude sign-in). Close it at this turn
1976
+ // boundary — only when idle, so a streaming turn is never aborted — and fall
1977
+ // through to the cold start, which resumes the same session (sdkOptions
1978
+ // carries resume: this.#sessionId) on the new env.
1979
+ if (this.#persistentQuery && this.#messageChannel && !this.#messageChannel.closed
1980
+ && shouldRestartForAuth(this.#spawnAuthGen, authEnvGeneration, this.#turnsInFlight, !!this.#pendingInterrupt)) {
1981
+ console.log('🔑 Auth backend changed since spawn — restarting persistent session before this turn');
1982
+ this.closeSession();
1983
+ }
1984
+ this.#turnsInFlight++;
1913
1985
  if (this.#persistentQuery && this.#messageChannel && !this.#messageChannel.closed) {
1914
1986
  // Fast path — push to existing subprocess (no cold start).
1915
1987
  // If an interrupt is in flight, order the push AFTER it settles: a message
@@ -1940,6 +2012,7 @@ export class ClaudeLLM extends llm.LLM {
1940
2012
  }
1941
2013
  // Cold start — create channel, push first message, start query + background consumer
1942
2014
  console.log('🔄 Persistent session: cold start (first message, JSONL replay)');
2015
+ this.#spawnAuthGen = authEnvGeneration;
1943
2016
  this.#messageChannel = new MessageChannel();
1944
2017
  this.#messageChannel.push(userMessage);
1945
2018
  this.#persistentQuery = query({ prompt: this.#messageChannel, options: sdkOptions });
@@ -2081,6 +2154,8 @@ export class ClaudeLLM extends llm.LLM {
2081
2154
  // Result — marks end of a turn (but we keep consuming for next turn)
2082
2155
  if (msg.type === 'result') {
2083
2156
  logCacheUsage(msg.usage); // per-turn cache reads/writes (main loop only)
2157
+ if (this.#turnsInFlight > 0)
2158
+ this.#turnsInFlight--;
2084
2159
  const turnMessageId = this.#currentTurnMessageId;
2085
2160
  const turnChunks = [...this.#currentTurnChunks];
2086
2161
  if (msg.result) {
@@ -2118,10 +2193,15 @@ export class ClaudeLLM extends llm.LLM {
2118
2193
  }
2119
2194
  }
2120
2195
  finally {
2121
- this.#backgroundConsumerRunning = false;
2122
2196
  this.#activeQueries.delete(pq);
2123
- this.#persistentQuery = null;
2124
- this.#messageChannel = null;
2197
+ // Only tear down session fields this loop still owns. If closeSession() ran and a
2198
+ // newer query (+ consumer) was started before this stale loop drained, the fields
2199
+ // now belong to that newer query — nulling them would orphan its subprocess.
2200
+ if (this.#persistentQuery === pq) {
2201
+ this.#backgroundConsumerRunning = false;
2202
+ this.#persistentQuery = null;
2203
+ this.#messageChannel = null;
2204
+ }
2125
2205
  console.log('🔒 Persistent session background consumer exited');
2126
2206
  }
2127
2207
  }
@@ -2163,6 +2243,9 @@ export class ClaudeLLM extends llm.LLM {
2163
2243
  class ClaudeLLMStream extends llm.LLMStream {
2164
2244
  #opts;
2165
2245
  #sessionId;
2246
+ // Trigger rides the PreCompact event; PostCompact (where the durable record is
2247
+ // written) needs it, so it's stashed here between the two hooks.
2248
+ #lastCompactTrigger = undefined;
2166
2249
  #onSessionId;
2167
2250
  #eventEmitter;
2168
2251
  #onPermissionRequest;
@@ -2236,6 +2319,22 @@ class ClaudeLLMStream extends llm.LLMStream {
2236
2319
  ? getSessionWorkspace(this.#opts.workingDirectory, sessionId)
2237
2320
  : null;
2238
2321
  const allowedTools = this.#opts.allowedTools || [];
2322
+ // Ensure the project working directory exists before handing it to the SDK as cwd.
2323
+ // The dashboard "new project" flow passes {base}/{slug} (e.g. /workspace/kachi) as the
2324
+ // working directory but nothing in the client → /api/token → agent chain ever creates
2325
+ // the folder. A brand-new project therefore ran on a non-existent cwd: tools silently
2326
+ // operated on the wrong path and nothing landed in the project (the "Kachi" bug —
2327
+ // session saved, folder absent). Guarded + recursive; also recreates a folder that was
2328
+ // recycled between resumes. Skipped when workingDirectory is unset (SDK → process.cwd()).
2329
+ if (this.#opts.workingDirectory && !existsSync(this.#opts.workingDirectory)) {
2330
+ try {
2331
+ mkdirSync(this.#opts.workingDirectory, { recursive: true });
2332
+ console.log(`📁 Created project working directory: ${this.#opts.workingDirectory}`);
2333
+ }
2334
+ catch (err) {
2335
+ console.log(`⚠️ Failed to create working directory ${this.#opts.workingDirectory}:`, err);
2336
+ }
2337
+ }
2239
2338
  const sdkOptions = {
2240
2339
  cwd: this.#opts.workingDirectory,
2241
2340
  permissionMode: this.#opts.permissionMode,
@@ -2287,7 +2386,11 @@ class ClaudeLLMStream extends llm.LLMStream {
2287
2386
  console.log('input,', input, 'input.file_path', filePath, 'agent_type', agentType);
2288
2387
  console.log(`🔍 canUseTool: ${toolName} filePath="${filePath}" keys=${Object.keys(input || {}).join(',')}`);
2289
2388
  console.log(`🔍 canUseTool _options keys=[${Object.keys(_options || {}).join(', ')}] title="${_options?.title || ''}" decisionReason="${_options?.decisionReason || ''}" blockedPath="${_options?.blockedPath || ''}"`);
2290
- if (filePath.includes('/osb/') || filePath.includes('.osborn/sessions/') || filePath.includes('.osborn/research/')) {
2389
+ if (isSafeArtifactPath(filePath)) {
2390
+ // Robust resolve+root check (not a substring): `..` traversal can no
2391
+ // longer trick the workspace auto-approve into clearing a write that
2392
+ // lands outside the session workspace. Legit absolute workspace
2393
+ // writes (~/.claude/projects/<slug>/osb/…) still auto-approve.
2291
2394
  // Block writes to spec.md — the fast brain manages it
2292
2395
  const fileName = filePath.split('/').pop() || '';
2293
2396
  if (fileName === 'spec.md') {
@@ -2352,21 +2455,28 @@ class ClaudeLLMStream extends llm.LLMStream {
2352
2455
  const toolInput = input?.tool_input || {};
2353
2456
  const agentType = input?.agent_type || null;
2354
2457
  console.log(`🔍 PreToolUse: toolName=${toolName} agent_type=${agentType} agent_id=${input?.agent_id || 'none'} all_keys=[${Object.keys(input || {}).join(', ')}]`);
2355
- // ≤3 direct tool call budget enforcement.
2356
- // Only counts calls from the MAIN orchestrator agent (agent_type === null).
2357
- // Task/Agent delegations are exempt — delegation is the desired behavior.
2358
- // Sub-agent tool calls are exempt — they're inside a delegation.
2458
+ // Spoken-progress cadence + runaway backstop (main orchestrator only).
2459
+ // Only the MAIN agent's direct tool calls count (agent_type === null).
2460
+ // Task/Agent delegations and sub-agent calls are exempt.
2359
2461
  if (!agentType && toolName !== 'Task' && toolName !== 'Agent') {
2360
2462
  turnToolCallCount++;
2361
- if (turnToolCallCount > TOOL_CALL_BUDGET) {
2362
- console.log(`🛑 Tool budget exceeded (${turnToolCallCount}/${TOOL_CALL_BUDGET}) — DENYING ${toolName}. Must delegate via Task.`);
2363
- this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Tool call budget exceeded (${turnToolCallCount}/${TOOL_CALL_BUDGET}). Delegate via Task.` });
2463
+ // Runaway/crash backstop ONLY (not a workflow cap) — a healthy turn never
2464
+ // reaches it. Disabled when OSBORN_TOOL_HARD_CEILING=0.
2465
+ if (TOOL_HARD_CEILING > 0 && turnToolCallCount > TOOL_HARD_CEILING) {
2466
+ console.log(`🛑 Runaway safety limit (${turnToolCallCount}/${TOOL_HARD_CEILING}) — DENYING ${toolName}.`);
2467
+ this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Runaway safety limit (${turnToolCallCount} tool calls this turn). Wrap up or delegate remaining work via Task.` });
2364
2468
  return {
2365
2469
  hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' },
2366
- reason: `Hard limit: maximum ${TOOL_CALL_BUDGET} direct tool calls per turn (you are at ${turnToolCallCount}). Delegate the remaining work to a sub-agent via Task(subagent_type=\'researcher\'|\'writer\'|\'reasoner\', run_in_background: true). This is a system-enforced limit.`,
2470
+ reason: `Runaway safety limit reached (${turnToolCallCount} direct tool calls this turn). This is a crash-safety backstop, not a normal cap — finish the current thread of work, summarize to the user, or push remaining work into a Task sub-agent.`,
2367
2471
  };
2368
2472
  }
2369
- console.log(`🔧 Tool call ${turnToolCallCount}/${TOOL_CALL_BUDGET}: ${toolName}`);
2473
+ // At each Nth main-agent tool call, arm a non-blocking spoken-progress nudge
2474
+ // (consumed at the allow tail below) so the agent stays audible without ever
2475
+ // having its work stopped.
2476
+ if (turnToolCallCount % SPEAK_CADENCE_N === 0) {
2477
+ pendingSpeakNudge = true;
2478
+ }
2479
+ console.log(`🔧 Tool call ${turnToolCallCount} (speak-cadence ${SPEAK_CADENCE_N}, ceiling ${TOOL_HARD_CEILING || 'off'}): ${toolName}`);
2370
2480
  }
2371
2481
  // Write/Edit/MultiEdit access control — plain WRITE_RULES lookup
2372
2482
  // keyed by agent name (see decideWrite). Same behavior the old
@@ -2423,6 +2533,13 @@ class ClaudeLLMStream extends llm.LLMStream {
2423
2533
  this.#llmRef.noteTaskDispatch(input?.tool_use_id, st || undefined);
2424
2534
  }
2425
2535
  this.#eventEmitter.emit('tool_use', { name: toolName, input: toolInput, agentRole: agentType || 'main', agentId: input?.agent_id });
2536
+ // Consume an armed spoken-progress nudge on this allowed main-agent tool call:
2537
+ // inject it as NON-BLOCKING additionalContext (the model reads it; the tool still
2538
+ // runs). Riding the allow tail guarantees one clean, non-deny injection site.
2539
+ if (pendingSpeakNudge && !agentType) {
2540
+ pendingSpeakNudge = false;
2541
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: speakProgressNudge(turnToolCallCount) } };
2542
+ }
2426
2543
  return {};
2427
2544
  }]
2428
2545
  }],
@@ -2465,6 +2582,8 @@ class ClaudeLLMStream extends llm.LLMStream {
2465
2582
  turnToolCallCount = 0;
2466
2583
  // Reset the writer provenance-reminder flag for the new turn.
2467
2584
  writerHistoryReminded = false;
2585
+ // Re-arm the spoken-progress cadence for the new turn.
2586
+ pendingSpeakNudge = false;
2468
2587
  const reminder = readFileSync(TURN_SHAPE_REMINDER_PATH, 'utf-8');
2469
2588
  const promptPreview = String(input?.prompt || '').substring(0, 60).replace(/\n/g, ' ');
2470
2589
  // Reliable recall: retrieve prior messages relevant to THIS prompt and inject
@@ -2506,7 +2625,7 @@ class ClaudeLLMStream extends llm.LLMStream {
2506
2625
  // prefix, but ordering volatile content last keeps any future
2507
2626
  // cache_control breakpoint inside this block useful too.
2508
2627
  const additionalContext = [reminder, recalled, machineNudge].filter(Boolean).join('\n\n');
2509
- console.log(`📌 UserPromptSubmit: injected turn-shape reminder (${reminder.length} chars)${recalled ? ` + recall (${recalled.length} chars)` : ''}${machineNudge ? ` + machine(${machineNudge.includes('⚠️') ? 'HOT' : 'ok'})` : ''} for prompt="${promptPreview}..." [tool budget reset to 0/${TOOL_CALL_BUDGET}]`);
2628
+ console.log(`📌 UserPromptSubmit: injected turn-shape reminder (${reminder.length} chars)${recalled ? ` + recall (${recalled.length} chars)` : ''}${machineNudge ? ` + machine(${machineNudge.includes('⚠️') ? 'HOT' : 'ok'})` : ''} for prompt="${promptPreview}..." [counters reset; speak-cadence ${SPEAK_CADENCE_N}]`);
2510
2629
  return {
2511
2630
  hookSpecificOutput: {
2512
2631
  hookEventName: 'UserPromptSubmit',
@@ -2528,6 +2647,7 @@ class ClaudeLLMStream extends llm.LLMStream {
2528
2647
  matcher: '.*',
2529
2648
  hooks: [async (input) => {
2530
2649
  try {
2650
+ this.#lastCompactTrigger = typeof input?.trigger === 'string' ? input.trigger : undefined;
2531
2651
  this.#opts.onCompactionEvent?.({ type: 'compaction_started', trigger: input?.trigger });
2532
2652
  const instructionPath = join(__claudeLlmDir, 'prompts', 'compact-learnings-instruction.md');
2533
2653
  const instructionRaw = existsSync(instructionPath) ? readFileSync(instructionPath, 'utf-8') : '';
@@ -2791,7 +2911,33 @@ class ClaudeLLMStream extends llm.LLMStream {
2791
2911
  catch (clErr) {
2792
2912
  console.error('⚠️ PostCompact: CONTENT_LENS launch failed:', clErr instanceof Error ? clErr.message : clErr);
2793
2913
  }
2794
- this.#opts.onCompactionEvent?.({ type: 'compaction_complete', skillsWritten, skillNames });
2914
+ // ── Durable persistence + integrity self-check ──
2915
+ // Write the compaction as one JSONL line in a sidecar next to the
2916
+ // recall store so resume/export read it back and the UI rebuilds
2917
+ // the marker at its real transcript position (compaction-log.ts).
2918
+ // The same enriched payload (at/trigger/transcriptRows/warning) is
2919
+ // emitted live, so the live marker and the reconstructed one match.
2920
+ const at = new Date().toISOString();
2921
+ let transcriptRows = 0;
2922
+ let integrityWarning;
2923
+ try {
2924
+ const sid = this.#sessionId;
2925
+ const wd = this.#opts.workingDirectory;
2926
+ if (sid && wd) {
2927
+ transcriptRows = countTranscriptRows(sid, wd);
2928
+ const rec = appendCompactionRecord(sid, wd, {
2929
+ at, trigger: this.#lastCompactTrigger, skillsWritten, skillNames, transcriptRows,
2930
+ });
2931
+ integrityWarning = rec.integrityWarning;
2932
+ if (integrityWarning) {
2933
+ console.warn(`⚠️ Compaction integrity: ${integrityWarning} (session ${sid.substring(0, 8)})`);
2934
+ }
2935
+ }
2936
+ }
2937
+ catch (persistErr) {
2938
+ console.error('⚠️ PostCompact: durable compaction record failed:', persistErr instanceof Error ? persistErr.message : persistErr);
2939
+ }
2940
+ this.#opts.onCompactionEvent?.({ type: 'compaction_complete', skillsWritten, skillNames, trigger: this.#lastCompactTrigger, at, transcriptRows, integrityWarning });
2795
2941
  console.log(`🧠 PostCompact: complete — ${skillsWritten} skill file(s) written: [${skillNames.join(', ')}]`);
2796
2942
  }
2797
2943
  catch (err) {
@@ -0,0 +1,67 @@
1
+ /** One persisted compaction. `at` is ISO-8601; `v` guards the line format. */
2
+ export interface CompactionRecord {
3
+ v: 1;
4
+ /** ISO-8601 timestamp of compaction completion. */
5
+ at: string;
6
+ /** What kicked off compaction (e.g. 'auto', 'manual'); carried from PreCompact. */
7
+ trigger?: string;
8
+ /** How many durable skill/memory files this compaction wrote. */
9
+ skillsWritten: number;
10
+ /** The names of those durable memories/skills (what was kept). */
11
+ skillNames: string[];
12
+ /** Recall-store row count at compaction time — the append-only high-water mark. */
13
+ transcriptRows: number;
14
+ /** Set when the integrity self-check detected that content may have been lost. */
15
+ integrityWarning?: string;
16
+ }
17
+ /** The marker shape the frontend consumes (store internals omitted). */
18
+ export interface CompactionMarkerWire {
19
+ at: string;
20
+ trigger?: string;
21
+ skillNames: string[];
22
+ skillsWritten: number;
23
+ integrityWarning?: string;
24
+ }
25
+ /** Serialize one record to a single JSONL line (no trailing newline). */
26
+ export declare function serializeCompactionRecord(rec: CompactionRecord): string;
27
+ /**
28
+ * Parse a compactions.jsonl blob into records, chronological by `at`.
29
+ * Tolerant: blank/unparseable/malformed lines are skipped (a half-written tail
30
+ * line from a crash never breaks the read). Equal timestamps keep file order.
31
+ */
32
+ export declare function parseCompactionLog(text: string): CompactionRecord[];
33
+ /**
34
+ * Integrity self-check across a compaction boundary. The recall store is
35
+ * append-only, so `nextRows` (this compaction) must be >= the previous
36
+ * compaction's `transcriptRows`. A shrink means transcript content was dropped
37
+ * (bad rebuild, truncation, JSONL corruption) — return a human-readable warning;
38
+ * otherwise undefined.
39
+ */
40
+ export declare function checkCompactionIntegrity(prev: CompactionRecord | undefined, nextRows: number): string | undefined;
41
+ /** Project a stored record onto the minimal marker the frontend needs. */
42
+ export declare function toCompactionMarker(rec: CompactionRecord): CompactionMarkerWire;
43
+ /** Sidecar path for a session: next to session.db in the osb dir. */
44
+ export declare function getCompactionLogPath(sessionId: string, workingDir: string): string;
45
+ /** Read + parse the sidecar for a session. Missing file → []. */
46
+ export declare function readCompactionRecords(sessionId: string, workingDir: string): CompactionRecord[];
47
+ /** Marker list for the wire (chronological). */
48
+ export declare function readCompactionMarkers(sessionId: string, workingDir: string): CompactionMarkerWire[];
49
+ /**
50
+ * Count durable transcript rows in the recall store — the append-only
51
+ * high-water mark used by the integrity check. No store yet → 0.
52
+ */
53
+ export declare function countTranscriptRows(sessionId: string, workingDir: string): number;
54
+ /**
55
+ * Append one completed compaction to the sidecar and return the full record
56
+ * (with any integrity warning filled in). Runs the append-only self-check
57
+ * against the last existing record first. Never throws out — a persistence
58
+ * failure must not break the compaction pipeline, so IO errors are swallowed
59
+ * after logging by the caller (which also owns emitting the live event).
60
+ */
61
+ export declare function appendCompactionRecord(sessionId: string, workingDir: string, input: {
62
+ at?: string;
63
+ trigger?: string;
64
+ skillsWritten: number;
65
+ skillNames: string[];
66
+ transcriptRows: number;
67
+ }): CompactionRecord;
@@ -0,0 +1,195 @@
1
+ /**
2
+ * compaction-log.ts — durable, append-only record of every context compaction.
3
+ *
4
+ * WHY: the frontend's "Conversation compacted · N memories saved" transcript
5
+ * marker (PR #35) was driven by LIVE `compaction_*` data-channel events only, so
6
+ * on resume/reload every past marker vanished — compaction became invisible again.
7
+ * This persists each completed compaction as one JSON line in a SIDECAR next to
8
+ * the session's recall store, so resume/export read the markers back and the UI
9
+ * reconstructs them at their real transcript position.
10
+ *
11
+ * WHERE: `{osbDir}/compactions.jsonl`, i.e. the SAME directory as session.db
12
+ * (~/.claude/projects/{slug}/osb/{sessionId}/). This matters for two reasons:
13
+ * 1. The recall store (session.db) is a RE-DERIVABLE cache of the JSONL —
14
+ * openStore() DROPs and rebuilds its tables on a version/dim/model bump — so
15
+ * a marker written INTO session.db would be wiped. A sidecar is not derived
16
+ * from anything and survives rebuilds.
17
+ * 2. `/sessions/export` tars all of ~/.claude/projects/, so the sidecar travels
18
+ * with the session automatically (no export change needed).
19
+ *
20
+ * INTEGRITY: the recall store is append-only, so its total row count is
21
+ * monotonically non-decreasing across the life of a session. Each record stamps
22
+ * `transcriptRows` (the store's row count at compaction time); if a later
23
+ * compaction sees FEWER rows than an earlier one, transcript content was dropped
24
+ * between them — checkCompactionIntegrity() flags it and the warning rides the
25
+ * record + event all the way to the marker card.
26
+ *
27
+ * Pure helpers (serialize/parse/integrity/toMarker) take no filesystem or DB and
28
+ * are unit-tested directly (compaction-log.test.ts) — the IO wrappers only add
29
+ * path resolution + append/read.
30
+ */
31
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'fs';
32
+ import { dirname, join } from 'path';
33
+ import { getStorePath, storeExists, openStore } from './session-store.js';
34
+ /** True when `v` is a valid CompactionRecord-ish object (lenient on optionals). */
35
+ function isRecordish(o) {
36
+ return (o && typeof o === 'object' &&
37
+ o.v === 1 &&
38
+ typeof o.at === 'string' && o.at.length > 0 &&
39
+ typeof o.skillsWritten === 'number' &&
40
+ Array.isArray(o.skillNames));
41
+ }
42
+ /** Serialize one record to a single JSONL line (no trailing newline). */
43
+ export function serializeCompactionRecord(rec) {
44
+ return JSON.stringify(rec);
45
+ }
46
+ /**
47
+ * Parse a compactions.jsonl blob into records, chronological by `at`.
48
+ * Tolerant: blank/unparseable/malformed lines are skipped (a half-written tail
49
+ * line from a crash never breaks the read). Equal timestamps keep file order.
50
+ */
51
+ export function parseCompactionLog(text) {
52
+ if (!text)
53
+ return [];
54
+ const out = [];
55
+ const lines = text.split('\n');
56
+ for (let i = 0; i < lines.length; i++) {
57
+ const line = lines[i].trim();
58
+ if (!line)
59
+ continue;
60
+ try {
61
+ const obj = JSON.parse(line);
62
+ if (isRecordish(obj)) {
63
+ // Build minimally — undefined optionals are OMITTED (not set to undefined)
64
+ // so a parse(serialize(rec)) round-trips to the same key set.
65
+ const rec = {
66
+ v: 1,
67
+ at: obj.at,
68
+ skillsWritten: obj.skillsWritten,
69
+ skillNames: obj.skillNames.filter((s) => typeof s === 'string'),
70
+ transcriptRows: typeof obj.transcriptRows === 'number' ? obj.transcriptRows : 0,
71
+ };
72
+ if (typeof obj.trigger === 'string')
73
+ rec.trigger = obj.trigger;
74
+ if (typeof obj.integrityWarning === 'string')
75
+ rec.integrityWarning = obj.integrityWarning;
76
+ out.push({ rec, idx: i });
77
+ }
78
+ }
79
+ catch {
80
+ // skip unparseable line (e.g. a torn final line)
81
+ }
82
+ }
83
+ out.sort((a, b) => {
84
+ const ta = Date.parse(a.rec.at);
85
+ const tb = Date.parse(b.rec.at);
86
+ const na = Number.isNaN(ta), nb = Number.isNaN(tb);
87
+ if (na && nb)
88
+ return a.idx - b.idx;
89
+ if (na)
90
+ return 1;
91
+ if (nb)
92
+ return -1;
93
+ if (ta !== tb)
94
+ return ta - tb;
95
+ return a.idx - b.idx;
96
+ });
97
+ return out.map((x) => x.rec);
98
+ }
99
+ /**
100
+ * Integrity self-check across a compaction boundary. The recall store is
101
+ * append-only, so `nextRows` (this compaction) must be >= the previous
102
+ * compaction's `transcriptRows`. A shrink means transcript content was dropped
103
+ * (bad rebuild, truncation, JSONL corruption) — return a human-readable warning;
104
+ * otherwise undefined.
105
+ */
106
+ export function checkCompactionIntegrity(prev, nextRows) {
107
+ if (!prev)
108
+ return undefined;
109
+ if (typeof prev.transcriptRows !== 'number')
110
+ return undefined;
111
+ if (nextRows < prev.transcriptRows) {
112
+ return `transcript rows dropped ${prev.transcriptRows}→${nextRows} since the previous compaction — earlier content may have been lost`;
113
+ }
114
+ return undefined;
115
+ }
116
+ /** Project a stored record onto the minimal marker the frontend needs. */
117
+ export function toCompactionMarker(rec) {
118
+ return {
119
+ at: rec.at,
120
+ trigger: rec.trigger,
121
+ skillNames: rec.skillNames,
122
+ skillsWritten: rec.skillsWritten,
123
+ integrityWarning: rec.integrityWarning,
124
+ };
125
+ }
126
+ // ── IO wrappers (path resolution + append/read) ─────────────────────────────
127
+ /** Sidecar path for a session: next to session.db in the osb dir. */
128
+ export function getCompactionLogPath(sessionId, workingDir) {
129
+ return join(dirname(getStorePath(sessionId, workingDir)), 'compactions.jsonl');
130
+ }
131
+ /** Read + parse the sidecar for a session. Missing file → []. */
132
+ export function readCompactionRecords(sessionId, workingDir) {
133
+ const p = getCompactionLogPath(sessionId, workingDir);
134
+ if (!existsSync(p))
135
+ return [];
136
+ try {
137
+ return parseCompactionLog(readFileSync(p, 'utf-8'));
138
+ }
139
+ catch {
140
+ return [];
141
+ }
142
+ }
143
+ /** Marker list for the wire (chronological). */
144
+ export function readCompactionMarkers(sessionId, workingDir) {
145
+ return readCompactionRecords(sessionId, workingDir).map(toCompactionMarker);
146
+ }
147
+ /**
148
+ * Count durable transcript rows in the recall store — the append-only
149
+ * high-water mark used by the integrity check. No store yet → 0.
150
+ */
151
+ export function countTranscriptRows(sessionId, workingDir) {
152
+ const dbPath = storeExists(sessionId, workingDir);
153
+ if (!dbPath)
154
+ return 0;
155
+ let db;
156
+ try {
157
+ db = openStore(dbPath, { readonly: true });
158
+ const row = db.prepare('SELECT COUNT(*) AS c FROM content').get();
159
+ return row?.c ?? 0;
160
+ }
161
+ catch {
162
+ return 0;
163
+ }
164
+ finally {
165
+ try {
166
+ db?.close();
167
+ }
168
+ catch { /* already closed */ }
169
+ }
170
+ }
171
+ /**
172
+ * Append one completed compaction to the sidecar and return the full record
173
+ * (with any integrity warning filled in). Runs the append-only self-check
174
+ * against the last existing record first. Never throws out — a persistence
175
+ * failure must not break the compaction pipeline, so IO errors are swallowed
176
+ * after logging by the caller (which also owns emitting the live event).
177
+ */
178
+ export function appendCompactionRecord(sessionId, workingDir, input) {
179
+ const existing = readCompactionRecords(sessionId, workingDir);
180
+ const prev = existing.length ? existing[existing.length - 1] : undefined;
181
+ const integrityWarning = checkCompactionIntegrity(prev, input.transcriptRows);
182
+ const rec = {
183
+ v: 1,
184
+ at: input.at || new Date().toISOString(),
185
+ trigger: input.trigger,
186
+ skillsWritten: input.skillsWritten,
187
+ skillNames: input.skillNames.filter((s) => typeof s === 'string'),
188
+ transcriptRows: input.transcriptRows,
189
+ ...(integrityWarning ? { integrityWarning } : {}),
190
+ };
191
+ const p = getCompactionLogPath(sessionId, workingDir);
192
+ mkdirSync(dirname(p), { recursive: true });
193
+ appendFileSync(p, serializeCompactionRecord(rec) + '\n', 'utf-8');
194
+ return rec;
195
+ }
package/dist/config.d.ts CHANGED
@@ -110,6 +110,8 @@ export interface SessionInfo {
110
110
  projectPath: string;
111
111
  timestamp: Date;
112
112
  lastMessage?: string;
113
+ /** Clean session topic: Claude Code's ai-title if present, else the first real user turn. */
114
+ title?: string;
113
115
  messageCount: number;
114
116
  filePath: string;
115
117
  }
@@ -125,6 +127,19 @@ export declare function getSessionDir(projectPath: string): string;
125
127
  * List all available sessions for the current project
126
128
  */
127
129
  export declare function listSessions(projectPath?: string): Promise<SessionInfo[]>;
130
+ /** Preview fields derived from a session JSONL (see getSessionPreview). */
131
+ export interface SessionPreview {
132
+ /** Last real user turn, sanitized THEN truncated to 100 chars. */
133
+ lastMessage?: string;
134
+ /** ai-title if present, else the first real user turn (sanitized, 120 chars). */
135
+ title?: string;
136
+ /** Conversation turns: user turns with real text + assistant messages with text. */
137
+ messageCount: number;
138
+ /** Timestamp of the first record carrying one. */
139
+ firstTs?: string;
140
+ /** Timestamp of the last REAL user/assistant turn (not file mtime). */
141
+ lastActivityAt?: string;
142
+ }
128
143
  /**
129
144
  * Get the most recent session ID for the current project
130
145
  */
@@ -140,7 +155,10 @@ export interface ClaudeSessionEntry {
140
155
  cwd: string;
141
156
  timestamp: Date;
142
157
  lastMessage?: string;
158
+ title?: string;
143
159
  messageCount: number;
160
+ firstTs?: string;
161
+ lastActivityAt?: string;
144
162
  filePath: string;
145
163
  fileSize: number;
146
164
  }