osborn 0.9.271 → 0.9.274

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 (55) 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-llm.d.ts +3 -0
  6. package/dist/claude-llm.js +100 -17
  7. package/dist/compaction-log.d.ts +67 -0
  8. package/dist/compaction-log.js +195 -0
  9. package/dist/config.d.ts +18 -0
  10. package/dist/config.js +122 -65
  11. package/dist/content/transcript-sanitizer.d.ts +20 -6
  12. package/dist/content/transcript-sanitizer.js +66 -11
  13. package/dist/data-sender-auth.d.ts +90 -0
  14. package/dist/data-sender-auth.js +157 -0
  15. package/dist/env-keys.js +11 -0
  16. package/dist/index.js +411 -92
  17. package/dist/meeting-addressing.d.ts +176 -0
  18. package/dist/meeting-addressing.js +288 -0
  19. package/dist/pipeline-direct-llm.d.ts +27 -0
  20. package/dist/pipeline-direct-llm.js +117 -37
  21. package/dist/prompts/direct-mode-fallback.md +1 -1
  22. package/dist/prompts/direct-mode-research.md +2 -2
  23. package/dist/prompts.d.ts +1 -1
  24. package/dist/prompts.js +3 -3
  25. package/dist/pushover.d.ts +77 -0
  26. package/dist/pushover.js +276 -0
  27. package/dist/recall-client.js +21 -2
  28. package/dist/session-store.d.ts +15 -5
  29. package/dist/session-store.js +37 -10
  30. package/dist/transcript-wiring.d.ts +121 -0
  31. package/dist/transcript-wiring.js +252 -0
  32. package/dist/voice-io.d.ts +0 -9
  33. package/dist/voice-io.js +5 -19
  34. package/dist/watch-gateway.d.ts +38 -0
  35. package/dist/watch-gateway.js +205 -0
  36. package/package.json +1 -1
  37. package/scripts/review.ts +1 -1
  38. package/dist/bridge-llm.d.ts +0 -22
  39. package/dist/bridge-llm.js +0 -39
  40. package/dist/codex-handler.d.ts +0 -38
  41. package/dist/codex-handler.js +0 -83
  42. package/dist/codex-llm.d.ts +0 -40
  43. package/dist/codex-llm.js +0 -144
  44. package/dist/fast-brain.d.ts +0 -176
  45. package/dist/fast-brain.js +0 -1887
  46. package/dist/index-3-2-26-legacy.d.ts +0 -1
  47. package/dist/index-3-2-26-legacy.js +0 -2233
  48. package/dist/leagcyprompts2.d.ts +0 -0
  49. package/dist/leagcyprompts2.js +0 -573
  50. package/dist/prompts-2-25-26.d.ts +0 -0
  51. package/dist/prompts-2-25-26.js +0 -518
  52. package/dist/prompts-3-2-26.d.ts +0 -78
  53. package/dist/prompts-3-2-26.js +0 -1319
  54. package/dist/summary-index.d.ts +0 -90
  55. package/dist/summary-index.js +0 -585
@@ -13,6 +13,7 @@ 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';
18
19
  import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
@@ -115,13 +116,33 @@ function logCacheUsage(usage) {
115
116
  }
116
117
  catch { /* observability only */ }
117
118
  }
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.
119
+ // Spoken-progress CADENCE (not a work cap). The main orchestrator agent may run as many direct
120
+ // tool calls as a turn genuinely needs — we no longer STOP its work. Instead, every
121
+ // SPEAK_CADENCE_N main-agent tool calls we inject a NON-BLOCKING note (PreToolUse
122
+ // additionalContext) nudging it to say ONE short spoken progress line before its next call, then
123
+ // keep going (do it itself or delegate — its choice). Reset on every UserPromptSubmit (new user
124
+ // message). Task/Agent delegations and sub-agent calls (agent_type !== null) do NOT count.
125
+ //
126
+ // TOOL_HARD_CEILING is a pure runaway/crash backstop (heap-OOM history on pathological deep
127
+ // turns), NOT a workflow cap — a healthy turn never approaches it. Env-tunable; set
128
+ // OSBORN_TOOL_HARD_CEILING=0 to disable the backstop entirely.
123
129
  let turnToolCallCount = 0;
124
- const TOOL_CALL_BUDGET = 5;
130
+ const SPEAK_CADENCE_N = 6;
131
+ const TOOL_HARD_CEILING = Number(process.env.OSBORN_TOOL_HARD_CEILING ?? 60);
132
+ // Armed when a cadence boundary is crossed; consumed at the PreToolUse allow/fall-through tail so
133
+ // the spoken-progress note rides the next ACTUALLY-allowed main-agent tool call (even if the exact
134
+ // cadence call was a deferred/denied write).
135
+ let pendingSpeakNudge = false;
136
+ // The cadence nudge text. Framed as a system note so the model never mistakes it for a user turn;
137
+ // asks for exactly ONE short spoken sentence (→ one text block → one tts_say → session.say), says
138
+ // "keep going, your call to do it yourself or delegate" and "do not stop" so it is never read as a
139
+ // turn-ender. Auto-suppressed if the user is mid-utterance (index.ts output gate) and routed
140
+ // correctly into meetings.
141
+ const speakProgressNudge = (n) => `[SPOKEN PROGRESS CADENCE — system note, not from the user] You've run ${n} tool calls on this ` +
142
+ `turn without checking in. Before your next tool call, say ONE short spoken sentence to the ` +
143
+ `user: plainly, what you just found or did and what you're doing next (~15 words, no question, ` +
144
+ `no menu). Then keep working — do it yourself or delegate via Task, your call. Do not stop, ` +
145
+ `wait, or ask permission; this is a nudge to stay audible, not to end the turn.`;
125
146
  // Writer PROVENANCE REMINDER (Chesterton's Fence): before the writer mutates a
126
147
  // version-controlled file it should review that file's git history so the edit is
127
148
  // backward-informed (root cause / prior + reverted attempts / cross-component coupling),
@@ -2163,6 +2184,9 @@ export class ClaudeLLM extends llm.LLM {
2163
2184
  class ClaudeLLMStream extends llm.LLMStream {
2164
2185
  #opts;
2165
2186
  #sessionId;
2187
+ // Trigger rides the PreCompact event; PostCompact (where the durable record is
2188
+ // written) needs it, so it's stashed here between the two hooks.
2189
+ #lastCompactTrigger = undefined;
2166
2190
  #onSessionId;
2167
2191
  #eventEmitter;
2168
2192
  #onPermissionRequest;
@@ -2236,6 +2260,22 @@ class ClaudeLLMStream extends llm.LLMStream {
2236
2260
  ? getSessionWorkspace(this.#opts.workingDirectory, sessionId)
2237
2261
  : null;
2238
2262
  const allowedTools = this.#opts.allowedTools || [];
2263
+ // Ensure the project working directory exists before handing it to the SDK as cwd.
2264
+ // The dashboard "new project" flow passes {base}/{slug} (e.g. /workspace/kachi) as the
2265
+ // working directory but nothing in the client → /api/token → agent chain ever creates
2266
+ // the folder. A brand-new project therefore ran on a non-existent cwd: tools silently
2267
+ // operated on the wrong path and nothing landed in the project (the "Kachi" bug —
2268
+ // session saved, folder absent). Guarded + recursive; also recreates a folder that was
2269
+ // recycled between resumes. Skipped when workingDirectory is unset (SDK → process.cwd()).
2270
+ if (this.#opts.workingDirectory && !existsSync(this.#opts.workingDirectory)) {
2271
+ try {
2272
+ mkdirSync(this.#opts.workingDirectory, { recursive: true });
2273
+ console.log(`📁 Created project working directory: ${this.#opts.workingDirectory}`);
2274
+ }
2275
+ catch (err) {
2276
+ console.log(`⚠️ Failed to create working directory ${this.#opts.workingDirectory}:`, err);
2277
+ }
2278
+ }
2239
2279
  const sdkOptions = {
2240
2280
  cwd: this.#opts.workingDirectory,
2241
2281
  permissionMode: this.#opts.permissionMode,
@@ -2352,21 +2392,28 @@ class ClaudeLLMStream extends llm.LLMStream {
2352
2392
  const toolInput = input?.tool_input || {};
2353
2393
  const agentType = input?.agent_type || null;
2354
2394
  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.
2395
+ // Spoken-progress cadence + runaway backstop (main orchestrator only).
2396
+ // Only the MAIN agent's direct tool calls count (agent_type === null).
2397
+ // Task/Agent delegations and sub-agent calls are exempt.
2359
2398
  if (!agentType && toolName !== 'Task' && toolName !== 'Agent') {
2360
2399
  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.` });
2400
+ // Runaway/crash backstop ONLY (not a workflow cap) — a healthy turn never
2401
+ // reaches it. Disabled when OSBORN_TOOL_HARD_CEILING=0.
2402
+ if (TOOL_HARD_CEILING > 0 && turnToolCallCount > TOOL_HARD_CEILING) {
2403
+ console.log(`🛑 Runaway safety limit (${turnToolCallCount}/${TOOL_HARD_CEILING}) — DENYING ${toolName}.`);
2404
+ 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
2405
  return {
2365
2406
  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.`,
2407
+ 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
2408
  };
2368
2409
  }
2369
- console.log(`🔧 Tool call ${turnToolCallCount}/${TOOL_CALL_BUDGET}: ${toolName}`);
2410
+ // At each Nth main-agent tool call, arm a non-blocking spoken-progress nudge
2411
+ // (consumed at the allow tail below) so the agent stays audible without ever
2412
+ // having its work stopped.
2413
+ if (turnToolCallCount % SPEAK_CADENCE_N === 0) {
2414
+ pendingSpeakNudge = true;
2415
+ }
2416
+ console.log(`🔧 Tool call ${turnToolCallCount} (speak-cadence ${SPEAK_CADENCE_N}, ceiling ${TOOL_HARD_CEILING || 'off'}): ${toolName}`);
2370
2417
  }
2371
2418
  // Write/Edit/MultiEdit access control — plain WRITE_RULES lookup
2372
2419
  // keyed by agent name (see decideWrite). Same behavior the old
@@ -2423,6 +2470,13 @@ class ClaudeLLMStream extends llm.LLMStream {
2423
2470
  this.#llmRef.noteTaskDispatch(input?.tool_use_id, st || undefined);
2424
2471
  }
2425
2472
  this.#eventEmitter.emit('tool_use', { name: toolName, input: toolInput, agentRole: agentType || 'main', agentId: input?.agent_id });
2473
+ // Consume an armed spoken-progress nudge on this allowed main-agent tool call:
2474
+ // inject it as NON-BLOCKING additionalContext (the model reads it; the tool still
2475
+ // runs). Riding the allow tail guarantees one clean, non-deny injection site.
2476
+ if (pendingSpeakNudge && !agentType) {
2477
+ pendingSpeakNudge = false;
2478
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: speakProgressNudge(turnToolCallCount) } };
2479
+ }
2426
2480
  return {};
2427
2481
  }]
2428
2482
  }],
@@ -2465,6 +2519,8 @@ class ClaudeLLMStream extends llm.LLMStream {
2465
2519
  turnToolCallCount = 0;
2466
2520
  // Reset the writer provenance-reminder flag for the new turn.
2467
2521
  writerHistoryReminded = false;
2522
+ // Re-arm the spoken-progress cadence for the new turn.
2523
+ pendingSpeakNudge = false;
2468
2524
  const reminder = readFileSync(TURN_SHAPE_REMINDER_PATH, 'utf-8');
2469
2525
  const promptPreview = String(input?.prompt || '').substring(0, 60).replace(/\n/g, ' ');
2470
2526
  // Reliable recall: retrieve prior messages relevant to THIS prompt and inject
@@ -2506,7 +2562,7 @@ class ClaudeLLMStream extends llm.LLMStream {
2506
2562
  // prefix, but ordering volatile content last keeps any future
2507
2563
  // cache_control breakpoint inside this block useful too.
2508
2564
  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}]`);
2565
+ 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
2566
  return {
2511
2567
  hookSpecificOutput: {
2512
2568
  hookEventName: 'UserPromptSubmit',
@@ -2528,6 +2584,7 @@ class ClaudeLLMStream extends llm.LLMStream {
2528
2584
  matcher: '.*',
2529
2585
  hooks: [async (input) => {
2530
2586
  try {
2587
+ this.#lastCompactTrigger = typeof input?.trigger === 'string' ? input.trigger : undefined;
2531
2588
  this.#opts.onCompactionEvent?.({ type: 'compaction_started', trigger: input?.trigger });
2532
2589
  const instructionPath = join(__claudeLlmDir, 'prompts', 'compact-learnings-instruction.md');
2533
2590
  const instructionRaw = existsSync(instructionPath) ? readFileSync(instructionPath, 'utf-8') : '';
@@ -2791,7 +2848,33 @@ class ClaudeLLMStream extends llm.LLMStream {
2791
2848
  catch (clErr) {
2792
2849
  console.error('⚠️ PostCompact: CONTENT_LENS launch failed:', clErr instanceof Error ? clErr.message : clErr);
2793
2850
  }
2794
- this.#opts.onCompactionEvent?.({ type: 'compaction_complete', skillsWritten, skillNames });
2851
+ // ── Durable persistence + integrity self-check ──
2852
+ // Write the compaction as one JSONL line in a sidecar next to the
2853
+ // recall store so resume/export read it back and the UI rebuilds
2854
+ // the marker at its real transcript position (compaction-log.ts).
2855
+ // The same enriched payload (at/trigger/transcriptRows/warning) is
2856
+ // emitted live, so the live marker and the reconstructed one match.
2857
+ const at = new Date().toISOString();
2858
+ let transcriptRows = 0;
2859
+ let integrityWarning;
2860
+ try {
2861
+ const sid = this.#sessionId;
2862
+ const wd = this.#opts.workingDirectory;
2863
+ if (sid && wd) {
2864
+ transcriptRows = countTranscriptRows(sid, wd);
2865
+ const rec = appendCompactionRecord(sid, wd, {
2866
+ at, trigger: this.#lastCompactTrigger, skillsWritten, skillNames, transcriptRows,
2867
+ });
2868
+ integrityWarning = rec.integrityWarning;
2869
+ if (integrityWarning) {
2870
+ console.warn(`⚠️ Compaction integrity: ${integrityWarning} (session ${sid.substring(0, 8)})`);
2871
+ }
2872
+ }
2873
+ }
2874
+ catch (persistErr) {
2875
+ console.error('⚠️ PostCompact: durable compaction record failed:', persistErr instanceof Error ? persistErr.message : persistErr);
2876
+ }
2877
+ this.#opts.onCompactionEvent?.({ type: 'compaction_complete', skillsWritten, skillNames, trigger: this.#lastCompactTrigger, at, transcriptRows, integrityWarning });
2795
2878
  console.log(`🧠 PostCompact: complete — ${skillsWritten} skill file(s) written: [${skillNames.join(', ')}]`);
2796
2879
  }
2797
2880
  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
  }