osborn 0.9.279 → 0.9.281

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 (40) hide show
  1. package/dist/agent-store.d.ts +162 -0
  2. package/dist/agent-store.js +300 -0
  3. package/dist/claude-llm.d.ts +13 -8
  4. package/dist/claude-llm.js +89 -73
  5. package/dist/content/compaction-lens-worker.js +2 -1
  6. package/dist/content/content-run.js +9 -9
  7. package/dist/content/lens-clip-window.js +7 -6
  8. package/dist/content/lens-launch.d.ts +11 -0
  9. package/dist/content/lens-launch.js +11 -0
  10. package/dist/content/lens-library-select.d.ts +7 -5
  11. package/dist/content/lens-library-select.js +7 -6
  12. package/dist/content/lens-library.d.ts +7 -1
  13. package/dist/content/lens-library.js +29 -6
  14. package/dist/data-sender-auth.d.ts +3 -2
  15. package/dist/data-sender-auth.js +6 -3
  16. package/dist/index.js +241 -158
  17. package/dist/meeting-addressing.d.ts +1 -1
  18. package/dist/meeting-addressing.js +1 -0
  19. package/dist/pipeline-direct-llm.d.ts +1 -1
  20. package/dist/pipeline-direct-llm.js +1 -1
  21. package/dist/prompts/chain-after-planner.md +1 -0
  22. package/dist/prompts/chain-after-researcher.md +1 -0
  23. package/dist/prompts/chain-after-writer.md +1 -0
  24. package/dist/prompts/direct-mode-research.md +5 -4
  25. package/dist/prompts/steward.md +131 -0
  26. package/dist/prompts.d.ts +6 -0
  27. package/dist/prompts.js +20 -3
  28. package/dist/pushover.d.ts +2 -0
  29. package/dist/pushover.js +4 -2
  30. package/dist/steward-gate.d.ts +18 -0
  31. package/dist/steward-gate.js +299 -0
  32. package/dist/steward-verdict.d.ts +23 -0
  33. package/dist/steward-verdict.js +97 -0
  34. package/dist/stopwords.d.ts +1 -0
  35. package/dist/stopwords.js +6 -0
  36. package/dist/store-catalog.d.ts +101 -0
  37. package/dist/store-catalog.js +336 -0
  38. package/dist/store-name.d.ts +1 -0
  39. package/dist/store-name.js +3 -0
  40. package/package.json +1 -1
@@ -11,7 +11,7 @@ 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, getGroundingBlock, getRecalledContextBlock } from './prompts.js';
14
+ import { getResearchSystemPrompt, getDirectModeResearchPrompt, getStewardPrompt, getChainReminder, getGroundingBlock, getRecalledContextBlock } from './prompts.js';
15
15
  import { openStore, recall, storeExists, updateSessionStore, getStorePath } from './session-store.js';
16
16
  import { appendCompactionRecord, countTranscriptRows } from './compaction-log.js';
17
17
  import { getEmbedder } from './embedder.js';
@@ -21,6 +21,9 @@ import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, statSy
21
21
  import { join, dirname, resolve, basename } from 'node:path';
22
22
  import { fileURLToPath } from 'node:url';
23
23
  import { homedir, loadavg, totalmem, freemem, cpus } from 'node:os';
24
+ import { stewardGate } from './steward-gate.js';
25
+ import { parseStewardVerdict, appendStewardVerdict } from './steward-verdict.js';
26
+ import { ROLES, EDIT_TOOLS, roleOf, coreRole, installsSkillsSilently, parseFrontMatter } from './agent-store.js';
24
27
  // Directory of this module — used to locate co-located prompt files (e.g., turn-shape reminder).
25
28
  const __claudeLlmDir = dirname(fileURLToPath(import.meta.url));
26
29
  const TURN_SHAPE_REMINDER_PATH = join(__claudeLlmDir, 'prompts', 'turn-shape-reminder.md');
@@ -288,14 +291,8 @@ function loadAllSkills(_workingDir) {
288
291
  // relevant skills rather than an alphabetical accident.
289
292
  const SKILL_BODY_BUDGET = 200_000;
290
293
  function extractSkillDescription(raw) {
291
- let desc = '';
292
- const fm = raw.match(/^---\n([\s\S]*?)\n---/);
293
- if (fm) {
294
- const m = fm[1].match(/^description:\s*(.+)$/m);
295
- if (m)
296
- desc = m[1].trim();
297
- }
298
- const body = raw.replace(/^---\n[\s\S]*?\n---\n?/, '');
294
+ const { meta, body } = parseFrontMatter(raw);
295
+ let desc = typeof meta.description === 'string' ? meta.description : '';
299
296
  if (!desc) {
300
297
  const when = body.match(/^\s*WHEN:\s*(.+)$/mi);
301
298
  if (when)
@@ -348,7 +345,7 @@ function enumerateSkillsForCompaction() {
348
345
  }
349
346
  else {
350
347
  // Over budget → headings-only fallback (still enough to dedup + target a section).
351
- const body = raw.replace(/^---\n[\s\S]*?\n---\n?/, '');
348
+ const { body } = parseFrontMatter(raw);
352
349
  const headings = (body.match(/^#{2,6}\s+.+$/gm) || [])
353
350
  .map(h => h.replace(/^#+\s+/, '').trim());
354
351
  blocks.push(`${header}(full body omitted — over injection budget)\nsections: ${headings.join(' | ') || '(none)'}`);
@@ -642,7 +639,7 @@ export const NAMED_AGENTS = {
642
639
  'Returns structured pass/fail results with exact output — does NOT edit files.',
643
640
  'NOT GROUNDED: no session index access — runs tests with fresh eyes, adversarial validation.',
644
641
  ].join(' '),
645
- tools: ['Bash', 'Read', 'Glob', 'Grep', 'Write', 'Edit'], // write-gate: test files only (WRITE_RULES.tester)
642
+ tools: ['Bash', 'Read', 'Glob', 'Grep', 'Write', 'Edit'], // write-gate: test files only (ROLES.tester.write)
646
643
  model: 'sonnet',
647
644
  prompt: [
648
645
  'You are Osborn\'s tester agent. Your job is running tests and builds, then reporting results.',
@@ -784,16 +781,27 @@ export const NAMED_AGENTS = {
784
781
  'Return a self-contained brief; the orchestrator passes it directly to the writer.',
785
782
  ].join('\n'),
786
783
  },
784
+ steward: {
785
+ description: [
786
+ 'Codebase-steward agent (Opus). NOT GROUNDED: reads the repo and its git history directly. Owns duplication and regressions, not features. Use (1) on a PLAN before',
787
+ 'any code is written, to answer "does this already exist?" for every new function, route, module, table or',
788
+ 'feature; (2) on the DIFF after the writer and tester, to refactor it to reuse existing code, cut what is not',
789
+ 'needed, and map every changed symbol to its callers. Returns CLEAN, REFACTORED or BLOCK. Never reviews its own refactor.',
790
+ ].join(' '),
791
+ tools: ['Read', 'Glob', 'Grep', 'Bash', 'Edit', 'Write', 'MultiEdit'],
792
+ model: 'opus',
793
+ prompt: getStewardPrompt(), // agent/src/prompts/steward.md (also used by .claude/agents/steward.md)
794
+ },
787
795
  reviewer: {
788
796
  description: [
789
- 'Code-review agent (Sonnet). Use for: the VERIFY step in a generator-verifier loop — after the',
797
+ 'Code-review agent (Opus). Use for: the VERIFY step in a generator-verifier loop — after the',
790
798
  'writer completes a change, the reviewer reads the diff, checks correctness, spec/requirement',
791
799
  'adherence, obvious bugs, and security issues, then tags each finding BLOCKER/MAJOR/MINOR/NIT',
792
800
  'and returns an ACCEPT or REJECT verdict with specific, actionable feedback. May write documentation files (.md etc.) only.',
793
801
  'NOT GROUNDED: no session index access — reviews with fresh eyes for unbiased adversarial check.',
794
802
  ].join(' '),
795
- tools: ['Read', 'Glob', 'Grep', 'Bash', 'Write', 'Edit'], // write-gate: docs only (WRITE_RULES.reviewer)
796
- model: 'sonnet',
803
+ tools: ['Read', 'Glob', 'Grep', 'Bash', 'Write', 'Edit'], // write-gate: docs only (ROLES.reviewer.write)
804
+ model: 'opus',
797
805
  prompt: [
798
806
  'You are Osborn\'s reviewer agent. You are the VERIFY step in a generator-verifier loop.',
799
807
  '',
@@ -985,11 +993,10 @@ export function applyGrounding(agents, sessionId, workingDir) {
985
993
  }
986
994
  return out;
987
995
  }
988
- const WRITE_RULES = {
989
- writer: 'anywhere',
990
- tester: { extensions: /\.(test|spec)\.[jt]sx?$/, label: 'test', matchBasename: true },
991
- reviewer: { extensions: /\.(md|markdown|mdx|txt|rst|adoc)$/i, label: 'documentation' },
992
- };
996
+ // ── Write gate ──────────────────────────────────────────────────────────────
997
+ // Keyed by the acting agent's ROLE (agent-store.ts ROLES), not its name, so a
998
+ // fork or an imported agent carries the rule of the role it holds. No role
999
+ // (main orchestrator, unknown agent) → 'workspace'.
993
1000
  /**
994
1001
  * Path is inside the per-session sandbox workspace. Used by decideWrite's
995
1002
  * 'workspace' rule: true → write allowed, false → denied. Robust resolve+root
@@ -1000,14 +1007,14 @@ function isWorkspacePath(filePath) {
1000
1007
  return isSafeArtifactPath(filePath);
1001
1008
  }
1002
1009
  /**
1003
- * Decide a Write/Edit/MultiEdit for the acting agent (null = main orchestrator).
1004
- * Pure lookup against WRITE_RULES. Returns:
1010
+ * Decide a Write/Edit/MultiEdit for the acting agent's role (null = main
1011
+ * orchestrator or an unknown agent). Returns:
1005
1012
  * 'allow' → fall through (→ canUseTool workspace auto-approve, or {}).
1006
1013
  * 'defer' → PreToolUse 'ask' (canUseTool decides).
1007
1014
  * 'deny' → hard block with reason.
1008
1015
  */
1009
- export function decideWrite(agentType, filePath) {
1010
- const rule = (agentType && WRITE_RULES[agentType]) || 'workspace';
1016
+ export function decideWrite(role, filePath) {
1017
+ const rule = role ? ROLES[role].write : 'workspace';
1011
1018
  if (rule === 'anywhere')
1012
1019
  return { decision: 'defer' };
1013
1020
  if (rule === 'workspace') {
@@ -1027,39 +1034,15 @@ export function decideWrite(agentType, filePath) {
1027
1034
  return { decision: 'defer' };
1028
1035
  }
1029
1036
  // ── Verifier chaining (Pattern #1) ──────────────────────────────────────────
1030
- // Verifiers are real named Task sub-agents (the `agents` roster), NOT out-of-band
1031
- // query() spawns. Two enforcement points:
1032
- // • parallelAtStart — verifiers the ORCHESTRATOR must dispatch IN PARALLEL with
1033
- // the keyed agent (enforced by the orchestrator prompt; a post-hoc hook cannot
1034
- // make two Tasks run concurrently). Tester is TDD: it WRITES tests from the
1035
- // spec in parallel with the writer, blind to the implementation.
1036
- // • afterReminder — injected into the MAIN agent by the PostToolUse-on-Task hook
1037
- // when the keyed sub-agent's Task completes, so the main agent dispatches the
1038
- // next verifier(s) as real Tasks (verdicts return inline). Includes RUNNING the
1039
- // tester's tests against the finished code. Any agent not listed chains to nothing.
1037
+ // Verifiers are real named Task sub-agents. The chain is a role property
1038
+ // (agent-store.ts ROLES[role].chain): its prompts/chain-after-<role>.md reminder,
1039
+ // naming the agent that finished, is pushed into the MAIN agent at SubagentStop
1040
+ // so it dispatches the next verifier(s) as real Tasks.
1040
1041
  // Prepended to a verifier-chain reminder pushed into the MAIN agent at SubagentStop. Keeps the
1041
1042
  // dispatch SILENT — the model should emit ONLY the Task tool call(s), no spoken/streamed text —
1042
1043
  // so the chain advances without a robotic "now running the review…" narration on the voice path.
1043
1044
  export const SILENT_VERIFY_PREFIX = '[SYSTEM — SILENT CONTROL MESSAGE. Do NOT narrate, speak, or emit any assistant text this turn. ' +
1044
1045
  'Silently perform the following via the Task tool only.] ';
1045
- export const VERIFIER_CHAIN = {
1046
- writer: {
1047
- parallelAtStart: ['tester'],
1048
- afterReminder: 'The writer sub-agent just finished. Before you finalize, you MUST now use the Task tool to: ' +
1049
- "(1) RUN the tester's tests against the new implementation and report PASS/FAIL; " +
1050
- '(2) dispatch the `reviewer` on the diff for a VERDICT. ' +
1051
- 'If tests FAIL or the reviewer REJECTs, dispatch the `writer` to fix and then re-verify — ' +
1052
- 'at most 2 fix rounds, after which surface the outcome to the user rather than looping.',
1053
- },
1054
- researcher: {
1055
- afterReminder: 'The researcher sub-agent just finished. Before you finalize, you MUST now use the Task tool to ' +
1056
- 'dispatch the `reasoner` GATE to judge whether the research is complete and well-sourced for the ' +
1057
- 'original question — it returns GATE: PASS or GATE: NEEDS-MORE. ' +
1058
- 'If it returns NEEDS-MORE, dispatch the `researcher` again with the gaps it named and then re-gate — ' +
1059
- 'at most 2 rounds, after which surface the outcome to the user rather than looping. ' +
1060
- "This is the research analogue of writer→reviewer: don't rely on the findings until an independent agent has vetted them.",
1061
- },
1062
- };
1063
1046
  const RESEARCH_TOOLS = [
1064
1047
  'Read', 'Write', 'Edit', 'Glob', 'Grep',
1065
1048
  'Bash', 'WebSearch', 'WebFetch',
@@ -1447,8 +1430,9 @@ export class ClaudeLLM extends llm.LLM {
1447
1430
  * start (session start/resume/switch) — a live subprocess keeps the agents
1448
1431
  * it was created with.
1449
1432
  */
1450
- setAgents(agents) {
1433
+ setAgents(agents, roles) {
1451
1434
  this.#opts.agents = agents;
1435
+ this.#opts.agentRoles = roles;
1452
1436
  console.log(`🤖 Named agents ${agents ? `set (${Object.keys(agents).join(', ')})` : 'reset to built-ins'} — applies at next query cold start`);
1453
1437
  }
1454
1438
  /**
@@ -2474,14 +2458,16 @@ class ClaudeLLMStream extends llm.LLMStream {
2474
2458
  console.log(`✅ Auto-approved ${toolName} to workspace: ${filePath}`);
2475
2459
  return { behavior: 'allow', updatedInput: input };
2476
2460
  }
2477
- // Auto-approve writer sub-agent writes to skill installation directories.
2461
+ // Auto-approve skill-installing roles' (writer) writes to skill installation directories.
2478
2462
  // Pattern matches `.claude/skills/<skillname>/<file>` in any osborn install location
2479
2463
  // (npm global, dev tree, cloud sandbox), so installing a multi-file skill via the
2480
2464
  // writer agent doesn't blow up into a per-file permission cascade.
2481
- // Requires agent_type === 'writer' — main/researcher/reasoner are blocked by PreToolUse
2465
+ // Requires a role with skillInstall (writer) on a BUILT-IN agent: a user or catalog agent with
2466
+ // the writer role still writes, but each skill file goes through the approval dialog.
2467
+ // Workspace-only roles are blocked by PreToolUse
2482
2468
  // before they ever reach canUseTool, so this check is the only path that lets a
2483
2469
  // skill install through silently.
2484
- if (agentType === 'writer' && /\/\.claude\/skills\/[^/]+\//.test(filePath)) {
2470
+ if (installsSkillsSilently(roleOf(agentType, this.#opts.agentRoles, NAMED_AGENTS), !!coreRole(agentType, NAMED_AGENTS)) && /\/\.claude\/skills\/[^/]+\//.test(filePath)) {
2485
2471
  console.log(`✅ Auto-approved writer ${toolName} to skill dir: ${filePath}`);
2486
2472
  return { behavior: 'allow', updatedInput: input };
2487
2473
  }
@@ -2552,17 +2538,32 @@ class ClaudeLLMStream extends llm.LLMStream {
2552
2538
  }
2553
2539
  console.log(`🔧 Tool call ${turnToolCallCount} (speak-cadence ${SPEAK_CADENCE_N}, ceiling ${TOOL_HARD_CEILING || 'off'}): ${toolName}`);
2554
2540
  }
2555
- // Write/Edit/MultiEdit access control — plain WRITE_RULES lookup
2556
- // keyed by agent name (see decideWrite). Same behavior the old
2557
- // hardcoded per-role branches had, now in one visible place.
2558
- if (toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit') {
2559
- const filePath = String(toolInput.file_path || '');
2541
+ // Steward sign-off gate (#218): a commit, push or PR whose content the steward has
2542
+ // not signed off is refused (block, default) or only reported (OSBORN_STEWARD_MODE=advise).
2543
+ let stewardNote = null; // advise mode: rides the allow tail below
2544
+ if (toolName === 'Bash') {
2545
+ const gate = await stewardGate(String(toolInput.command || ''), this.#opts.workingDirectory || process.cwd());
2546
+ if (gate.decision !== 'allow')
2547
+ this.#eventEmitter.emit('steward_gate', { decision: gate.decision, message: gate.message });
2548
+ if (gate.decision === 'deny') {
2549
+ this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: gate.message });
2550
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gate.message };
2551
+ }
2552
+ if (gate.decision === 'advise')
2553
+ stewardNote = gate.message ?? null;
2554
+ }
2555
+ // File-edit access control (agent-store.ts EDIT_TOOLS) — keyed by the agent's ROLE
2556
+ // (agent-store.ts ROLES), so forks and imports keep their role's rule.
2557
+ if (EDIT_TOOLS.has(toolName)) {
2558
+ const filePath = String(toolInput.file_path || toolInput.notebook_path || '');
2559
+ const role = roleOf(agentType, this.#opts.agentRoles, NAMED_AGENTS);
2560
+ const historyFirst = !!(role && ROLES[role].historyFirst);
2560
2561
  // Writer PROVENANCE REMINDER (Chesterton's Fence): on the writer's FIRST edit of
2561
2562
  // an EXISTING (version-controlled) file this turn, deny ONCE with a reminder to
2562
2563
  // review the file's git history so the change is backward-informed (root cause,
2563
2564
  // prior/reverted attempts, cross-component coupling), not forward-only — then it
2564
2565
  // proceeds. New files are exempt (no history). One-shot per turn so it can't loop.
2565
- if (agentType === 'writer' && filePath && existsSync(filePath) && !writerHistoryReminded) {
2566
+ if (historyFirst && filePath && existsSync(filePath) && !writerHistoryReminded) {
2566
2567
  writerHistoryReminded = true;
2567
2568
  const base = filePath.split('/').pop() || filePath;
2568
2569
  const gateReason = [
@@ -2576,8 +2577,8 @@ class ClaudeLLMStream extends llm.LLMStream {
2576
2577
  this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Review ${base}'s git history first (one-time provenance reminder).` });
2577
2578
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gateReason };
2578
2579
  }
2579
- const { decision, reason } = decideWrite(agentType, filePath);
2580
- console.log(`🔎 Write gate: agent=${agentType ?? 'main'} path="${filePath || '(none)'}" → ${decision}`);
2580
+ const { decision, reason } = decideWrite(role, filePath);
2581
+ console.log(`🔎 Write gate: agent=${agentType ?? 'main'} role=${role ?? '-'} path="${filePath || '(none)'}" → ${decision}`);
2581
2582
  if (decision === 'deny') {
2582
2583
  this.#eventEmitter.emit('tool_blocked', { name: toolName, reason });
2583
2584
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason };
@@ -2586,7 +2587,7 @@ class ClaudeLLMStream extends llm.LLMStream {
2586
2587
  // Writer ('anywhere') surfaces its write in the live trace before
2587
2588
  // the permission dialog; adversarial agents (reviewer/tester) do
2588
2589
  // NOT emit here — parity with the prior hardcoded branches.
2589
- if (agentType === 'writer') {
2590
+ if (historyFirst) {
2590
2591
  this.#eventEmitter.emit('tool_use', { name: toolName, input: toolInput, agentRole: agentType || 'main', agentId: input?.agent_id });
2591
2592
  }
2592
2593
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask' } };
@@ -2610,10 +2611,12 @@ class ClaudeLLMStream extends llm.LLMStream {
2610
2611
  // Consume an armed spoken-progress nudge on this allowed main-agent tool call:
2611
2612
  // inject it as NON-BLOCKING additionalContext (the model reads it; the tool still
2612
2613
  // runs). Riding the allow tail guarantees one clean, non-deny injection site.
2613
- if (pendingSpeakNudge && !agentType) {
2614
+ const nudge = pendingSpeakNudge && !agentType ? speakProgressNudge(turnToolCallCount) : null;
2615
+ if (nudge)
2614
2616
  pendingSpeakNudge = false;
2615
- return { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: speakProgressNudge(turnToolCallCount) } };
2616
- }
2617
+ const context = [stewardNote, nudge].filter(Boolean).join('\n\n');
2618
+ if (context)
2619
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: context } };
2617
2620
  return {};
2618
2621
  }]
2619
2622
  }],
@@ -3063,23 +3066,36 @@ class ClaudeLLMStream extends llm.LLMStream {
3063
3066
  const aid = input?.agent_id ?? ('sa-' + Date.now());
3064
3067
  statusManager.upsertDispatch(aid, { subagentType: at, dispatchState: 'completed', artifact: msg });
3065
3068
  this.#eventEmitter.emit('task_completed', { agent_type: at, agent_id: aid, last_assistant_message: String(msg).slice(0, 400) });
3069
+ // Steward verdict card (#221): parsed, kept in the session's sidecar, sent to the chat.
3070
+ const atRole = roleOf(at, this.#opts.agentRoles, NAMED_AGENTS);
3071
+ const verdict = atRole && ROLES[atRole].verdict ? parseStewardVerdict(msg) : null;
3072
+ if (verdict) {
3073
+ try {
3074
+ if (this.#sessionId && this.#opts.workingDirectory)
3075
+ appendStewardVerdict(this.#sessionId, this.#opts.workingDirectory, verdict);
3076
+ }
3077
+ catch (e) {
3078
+ console.warn('steward verdict persist failed:', e instanceof Error ? e.message : e);
3079
+ }
3080
+ this.#eventEmitter.emit('steward_verdict', verdict);
3081
+ }
3066
3082
  // Pattern #1 verifier chaining — CORRECT timing (moved here from PostToolUse).
3067
3083
  // SubagentStop fires at REAL completion. When a chained producer (writer/researcher)
3068
- // finishes, push its afterReminder into the MAIN agent's streaming input so the main
3084
+ // finishes, push its chain reminder (prompts/chain-after-<role>.md) into the MAIN agent's streaming input so the main
3069
3085
  // agent dispatches the next verifier(s) as real Task sub-agents (verdicts return
3070
- // inline). Only writer/researcher are VERIFIER_CHAIN keys with afterReminder, so
3071
- // verifiers (reviewer/tester/reasoner) never re-chain. Dedup on agent_id guards a
3086
+ // inline). Only roles with a chain (writer/planner/researcher) push a reminder, so
3087
+ // verifiers (reviewer/tester/reasoner/steward) never re-chain. Dedup on agent_id guards a
3072
3088
  // double-fired SubagentStop; a fresh fix-round writer has a NEW id → re-chains (the
3073
3089
  // intended bounded loop). Guarded on a live session so we never cold-start a query
3074
3090
  // just to deliver a reminder. Silent-dispatch prefix keeps it off the voice.
3075
- const chainLink = at ? VERIFIER_CHAIN[at] : undefined;
3091
+ const chainReminder = atRole && ROLES[atRole].chain ? getChainReminder(atRole, at) : null;
3076
3092
  // Dedup MUST key on the REAL agent_id, never the fabricated 'sa-<ts>' fallback used
3077
3093
  // above for status/emit — a synthetic id is unique every call and would defeat the
3078
3094
  // double-fire guard. If the SDK omits agent_id we can't dedup safely, so skip chaining.
3079
- if (chainLink?.afterReminder && input?.agent_id && this.#llmRef.hasSession() && this.#llmRef.markChainDispatched(input.agent_id)) {
3095
+ if (chainReminder && input?.agent_id && this.#llmRef.hasSession() && this.#llmRef.markChainDispatched(input.agent_id)) {
3080
3096
  console.log(`[DISPATCH] Pattern#1 chain (SubagentStop): ${at} done → pushing verify reminder to main agent`);
3081
3097
  try {
3082
- this.#llmRef.pushMessage(SILENT_VERIFY_PREFIX + chainLink.afterReminder, sdkOptions, {
3098
+ this.#llmRef.pushMessage(SILENT_VERIFY_PREFIX + chainReminder, sdkOptions, {
3083
3099
  onSessionId: this.#onSessionId,
3084
3100
  onCheckpoint: this.#onCheckpoint,
3085
3101
  eventEmitter: this.#eventEmitter,
@@ -130,6 +130,7 @@ function parseJob(argv) {
130
130
  throw Object.assign(new Error('payload missing sessionId'), { lockDir, logDir });
131
131
  return {
132
132
  opts: { sessionId: payload.sessionId, transcriptPath: payload.transcriptPath, cwd: payload.cwd, mode: 'incremental' },
133
+ skipLens: payload.skipLens === true,
133
134
  lockDir,
134
135
  logDir,
135
136
  timeoutMs: INCREMENTAL_TIMEOUT_MS,
@@ -161,7 +162,7 @@ async function main() {
161
162
  const t0 = Date.now();
162
163
  let lensErr = null;
163
164
  // Step 1 — content lens (skipped by the --library entry).
164
- if (job.kind !== 'library' && job.kind !== 'content') {
165
+ if (job.kind !== 'library' && job.kind !== 'content' && !job.skipLens) {
165
166
  try {
166
167
  const r = await runCompactionLens({
167
168
  ...job.opts,
@@ -18,9 +18,8 @@ import { existsSync, mkdirSync, readFileSync } from 'node:fs';
18
18
  import { basename, dirname, join } from 'node:path';
19
19
  import Database from 'better-sqlite3';
20
20
  import { loadConversationRows, recordView, resolveSessionDb } from './lens-db.js';
21
- import { readCompactionBoundaries } from './lens-period-boundaries.js';
22
- import { pageFileName, segmentPeriods } from './lens-library-select.js';
23
- import { libraryDirFor, readManifest } from './lens-library.js';
21
+ import { pageFileName } from './lens-library-select.js';
22
+ import { libraryDirFor, librarySegments, readManifest } from './lens-library.js';
24
23
  import { CapError, contentCaps, daySpent, genModel, isContentPipelineEnabled, isContentStrict, SpendGuard } from './content-llm.js';
25
24
  import { makeScrubber } from './content-redact.js';
26
25
  import { CONTENT_DIR, isPieceSettled, periodDirName, periodStatusFor, readContentManifest, writeAtomic, writeContentManifest, } from './content-manifest.js';
@@ -41,15 +40,16 @@ const PAGE_RANGE_RE = /Rows in block: #(\d+)[–-]#(\d+)/;
41
40
  */
42
41
  export function pickContentPeriod(db, sessionId, dir, m, handoff) {
43
42
  const isDone = (start) => ['done', 'no-pieces'].includes(m.periods[String(start)]?.status ?? '');
44
- const hasPage = (p) => existsSync(join(dir, pageFileName(p)));
43
+ const lib = readManifest(dir, sessionId);
44
+ // A written page's file comes from its manifest entry (written pages are frozen), else the scheme.
45
+ const fileOf = (p) => lib.periods[String(p.startRowId)]?.file ?? pageFileName(p);
46
+ const hasPage = (p) => existsSync(join(dir, fileOf(p)));
45
47
  if (handoff) {
46
48
  if (!hasPage(handoff))
47
49
  return { period: null, reason: 'no-page' };
48
- return isDone(handoff.startRowId) ? { period: null, reason: 'already-done' } : { period: handoff, page: pageFileName(handoff) };
50
+ return isDone(handoff.startRowId) ? { period: null, reason: 'already-done' } : { period: handoff, page: fileOf(handoff) };
49
51
  }
50
- const rows = loadConversationRows(db, 0).records.map(r => ({ id: r.id, timestamp: r.timestamp }));
51
- const seg = segmentPeriods(rows, readCompactionBoundaries(db));
52
- const lib = readManifest(dir, sessionId);
52
+ const seg = librarySegments(db, lib);
53
53
  const recent = [...(seg.tail ? [seg.tail] : []), ...[...seg.closed].reverse()].slice(0, 3);
54
54
  let done = false;
55
55
  for (const p of recent) {
@@ -57,7 +57,7 @@ export function pickContentPeriod(db, sessionId, dir, m, handoff) {
57
57
  if ((le && le.status !== 'ok') || !hasPage(p))
58
58
  continue;
59
59
  if (!isDone(p.startRowId))
60
- return { period: p, page: pageFileName(p) };
60
+ return { period: p, page: fileOf(p) };
61
61
  done = true;
62
62
  }
63
63
  return { period: null, reason: done ? 'already-done' : 'no-page' };
@@ -11,12 +11,13 @@
11
11
  * (callers pass 25% of the model's context).
12
12
  */
13
13
  import { recordView, estimateTokens } from './lens-db.js';
14
- const STOP = new Set(('the and for that this with you your are was were have has had not but just like what when then them they there ' +
15
- 'their about from into would could should will can its it\'s i\'m don\'t that\'s okay yeah yes so um uh know ' +
16
- 'mean really actually basically right going gonna wanna want need let\'s lets thing things also well even still ' +
17
- 'here more some only very much make made does did doing done been being which where while because since each ' +
18
- 'other than over our out all any one two who how why way get got see say said sure think now back time ' +
19
- 'kind sort something maybe stuff look looks good same work working').split(/\s+/));
14
+ import { STOPWORDS } from '../stopwords.js';
15
+ // Shared English stopwords plus what speech transcripts are full of (fillers, contractions, vague nouns).
16
+ const STOP = new Set([
17
+ ...STOPWORDS,
18
+ ...("it's i'm don't that's okay yeah yes um uh know mean really actually basically right going gonna wanna let's lets " +
19
+ 'thing things sure think time kind sort something maybe stuff look looks good same work working').split(/\s+/),
20
+ ]);
20
21
  /** Lower-cased content terms (3+ chars, no stopwords). Keeps tokens like x-forwarded-host, 1006, 0.9.153. */
21
22
  export function terms(text) {
22
23
  const out = new Set();
@@ -10,6 +10,8 @@ export interface LensLaunchPayload {
10
10
  sessionId: string;
11
11
  transcriptPath?: string;
12
12
  cwd?: string;
13
+ /** Session-end runs: Library + content steps only, not the profile lens (step 1). */
14
+ skipLens?: boolean;
13
15
  }
14
16
  export type LensLaunchResult = {
15
17
  status: 'disabled';
@@ -44,3 +46,12 @@ export declare function resolveWorkerCommand(): {
44
46
  } | null;
45
47
  /** Fire-and-forget. Returns synchronously; the worker is never awaited. */
46
48
  export declare function launchCompactionLens(payload: LensLaunchPayload): LensLaunchResult;
49
+ type LastRun = {
50
+ at: string;
51
+ session: string;
52
+ reason: string;
53
+ status: LensLaunchResult['status'];
54
+ };
55
+ export declare const lastLibraryRun: () => LastRun;
56
+ export declare function launchLibraryOnSessionEnd(sessionId: string | null | undefined, cwd: string | undefined, reason: string): LastRun | null;
57
+ export {};
@@ -78,6 +78,7 @@ export function launchCompactionLens(payload) {
78
78
  sessionId: payload.sessionId,
79
79
  transcriptPath: payload.transcriptPath,
80
80
  cwd: payload.cwd,
81
+ skipLens: !!payload.skipLens,
81
82
  lockDir: lockHeld ? projectDir : null,
82
83
  }), { mode: 0o600, flag: 'wx' });
83
84
  {
@@ -109,3 +110,13 @@ export function launchCompactionLens(payload) {
109
110
  return { status: 'error', error: msg };
110
111
  }
111
112
  }
113
+ let lastRun = null;
114
+ export const lastLibraryRun = () => lastRun;
115
+ export function launchLibraryOnSessionEnd(sessionId, cwd, reason) {
116
+ if (!sessionId)
117
+ return null;
118
+ const r = launchCompactionLens({ sessionId, cwd, skipLens: true });
119
+ lastRun = { at: new Date().toISOString(), session: sessionId.slice(0, 8), reason, status: r.status };
120
+ console.log(`📚 library on session end (${reason}): ${lastRun.session} → ${r.status}`);
121
+ return lastRun;
122
+ }
@@ -1,22 +1,23 @@
1
1
  /**
2
- * lens-library-select.ts — which PERIOD a compaction just ended. Pure + deterministic.
2
+ * lens-library-select.ts — which PERIOD just ended. Pure + deterministic.
3
3
  *
4
- * A period runs from one compaction seam (lens-period-boundaries) to the row
5
- * before the next seam. Seams come in clusters (several re-compactions within
4
+ * A period runs from one seam to the row before the next. Seams are compactions
5
+ * (lens-period-boundaries) and the end of each page already written
6
+ * (librarySegments), so a session that never compacts still gets new periods. Seams come in clusters (several re-compactions within
6
7
  * minutes), so short periods are merged FORWARD: walking the seams in order, a
7
8
  * group only closes at a seam once it spans >= minSpanMs of conversation. The
8
9
  * walk depends only on earlier rows, so a later seam never re-numbers an earlier
9
10
  * group. That makes the group's OPENING boundary row (startRowId) a stable key:
10
11
  * the same period always gets the same key, index and file name.
11
12
  *
12
- * Timing: the worker runs at PostCompact, usually BEFORE the recall store has
13
+ * Timing: the worker runs at PostCompact (and when a session ends); at PostCompact it is usually BEFORE the recall store has
13
14
  * ingested the seam this compaction will produce. So the db's TAIL (last seam →
14
15
  * last row) is the period that just ended; it is treated as closed by "this
15
16
  * compaction" when it spans >= minSpanMs, else it is deferred (merged into the
16
17
  * next one). If the new seam is already ingested, the tail is tiny and the last
17
18
  * seam-closed group is the one that just ended.
18
19
  */
19
- export declare const DEFAULT_MIN_SPAN_MS: number;
20
+ export declare const DEFAULT_MIN_SPAN_MS = 3600000;
20
21
  export interface RowStamp {
21
22
  id: number;
22
23
  timestamp: string;
@@ -40,6 +41,7 @@ export interface Segmentation {
40
41
  closed: LibraryPeriod[];
41
42
  tail: LibraryPeriod | null;
42
43
  }
44
+ export declare function period(index: number, start: number, end: number, closedBy: number | null, recs: RowStamp[]): LibraryPeriod;
43
45
  /** Split records (ascending id) into greedy forward-merged periods at the given seams. */
44
46
  export declare function segmentPeriods(records: RowStamp[], boundaries: number[], minSpanMs?: number): Segmentation;
45
47
  export type PickResult = {
@@ -1,22 +1,23 @@
1
1
  /**
2
- * lens-library-select.ts — which PERIOD a compaction just ended. Pure + deterministic.
2
+ * lens-library-select.ts — which PERIOD just ended. Pure + deterministic.
3
3
  *
4
- * A period runs from one compaction seam (lens-period-boundaries) to the row
5
- * before the next seam. Seams come in clusters (several re-compactions within
4
+ * A period runs from one seam to the row before the next. Seams are compactions
5
+ * (lens-period-boundaries) and the end of each page already written
6
+ * (librarySegments), so a session that never compacts still gets new periods. Seams come in clusters (several re-compactions within
6
7
  * minutes), so short periods are merged FORWARD: walking the seams in order, a
7
8
  * group only closes at a seam once it spans >= minSpanMs of conversation. The
8
9
  * walk depends only on earlier rows, so a later seam never re-numbers an earlier
9
10
  * group. That makes the group's OPENING boundary row (startRowId) a stable key:
10
11
  * the same period always gets the same key, index and file name.
11
12
  *
12
- * Timing: the worker runs at PostCompact, usually BEFORE the recall store has
13
+ * Timing: the worker runs at PostCompact (and when a session ends); at PostCompact it is usually BEFORE the recall store has
13
14
  * ingested the seam this compaction will produce. So the db's TAIL (last seam →
14
15
  * last row) is the period that just ended; it is treated as closed by "this
15
16
  * compaction" when it spans >= minSpanMs, else it is deferred (merged into the
16
17
  * next one). If the new seam is already ingested, the tail is tiny and the last
17
18
  * seam-closed group is the one that just ended.
18
19
  */
19
- export const DEFAULT_MIN_SPAN_MS = 4 * 3_600_000;
20
+ export const DEFAULT_MIN_SPAN_MS = 3_600_000;
20
21
  function span(recs) {
21
22
  if (recs.length < 2)
22
23
  return 0;
@@ -24,7 +25,7 @@ function span(recs) {
24
25
  const b = Date.parse(recs[recs.length - 1].timestamp);
25
26
  return Number.isFinite(a) && Number.isFinite(b) ? Math.max(0, b - a) : 0;
26
27
  }
27
- function period(index, start, end, closedBy, recs) {
28
+ export function period(index, start, end, closedBy, recs) {
28
29
  return {
29
30
  index, startRowId: start, endRowId: end, closedBy, rows: recs.length,
30
31
  fromTs: recs[0]?.timestamp ?? '', toTs: recs[recs.length - 1]?.timestamp ?? '', spanMs: span(recs),
@@ -14,7 +14,7 @@
14
14
  * is retried next time. Fail-open: never throws; the caller just logs the result.
15
15
  * Opt-out: OSBORN_CONTENT_LENS=0 (same switch as the launcher).
16
16
  */
17
- import { type LibraryPeriod } from './lens-library-select.js';
17
+ import { type LibraryPeriod, type Segmentation } from './lens-library-select.js';
18
18
  import { type IngestOptions, type IngestState } from './lens-ingest.js';
19
19
  export declare const MANIFEST_FILE = ".library-manifest.json";
20
20
  export interface ManifestEntry {
@@ -88,5 +88,11 @@ export declare function ingestPendingPages(dir: string, m: Manifest, o?: IngestO
88
88
  export declare function libraryDirFor(dbPath: string, sessionId: string): string;
89
89
  export declare function readManifest(dir: string, sessionId: string): Manifest;
90
90
  export declare function writeManifest(dir: string, m: Manifest): void;
91
+ /**
92
+ * The session's periods as the library writes them (shared with the content step): compaction
93
+ * seams plus the end of every written page, so without a compaction the tail moves on past a
94
+ * written page instead of keeping its start row forever.
95
+ */
96
+ export declare function librarySegments(db: string, manifest: Manifest, minSpanMs?: number): Segmentation;
91
97
  /** Run the library step once. Never throws. */
92
98
  export declare function runLibraryStep(o: LibraryStepOptions): Promise<LibraryStepResult>;
@@ -22,7 +22,7 @@ import { readCompactionBoundaries } from './lens-period-boundaries.js';
22
22
  import { loadClientRedactor } from './lens-redact.js';
23
23
  import { redactSecrets } from './transcript-sanitizer.js';
24
24
  import { runPeriodMap } from './period-run.js';
25
- import { DEFAULT_MIN_SPAN_MS, pageFileName, pickLibraryPeriod, segmentPeriods } from './lens-library-select.js';
25
+ import { DEFAULT_MIN_SPAN_MS, pageFileName, period, pickLibraryPeriod, segmentPeriods } from './lens-library-select.js';
26
26
  import { rebuildIndex } from './lens-library-index.js';
27
27
  import { contentHashFor, ingestPage, needsIngest, resolveIngestConfig } from './lens-ingest.js';
28
28
  export const MANIFEST_FILE = '.library-manifest.json';
@@ -96,6 +96,27 @@ const envNum = (k) => {
96
96
  const n = Number(process.env[k]);
97
97
  return Number.isFinite(n) && n > 0 ? n : undefined;
98
98
  };
99
+ /**
100
+ * The session's periods as the library writes them (shared with the content step): compaction
101
+ * seams plus the end of every written page, so without a compaction the tail moves on past a
102
+ * written page instead of keeping its start row forever.
103
+ */
104
+ export function librarySegments(db, manifest, minSpanMs = libraryMinSpanMs()) {
105
+ const rows = loadConversationRows(db, 0).records.map(r => ({ id: r.id, timestamp: r.timestamp }));
106
+ // Written pages are frozen: they keep their rows, index and file whatever the period
107
+ // length is now. Only rows after the last written page are segmented, numbered on.
108
+ const written = Object.values(manifest.periods).filter(e => e.status === 'ok').sort((a, b) => a.startRowId - b.startRowId);
109
+ const lastEnd = written.length ? Math.max(...written.map(e => e.endRowId)) : 0;
110
+ const lastIndex = written.length ? Math.max(...written.map(e => e.index)) : 0;
111
+ const frozen = written.map(e => period(e.index, e.startRowId, e.endRowId, typeof e.closedBy === 'number' ? e.closedBy : null, rows.filter(r => r.id >= e.startRowId && r.id <= e.endRowId)));
112
+ const rest = segmentPeriods(rows.filter(r => r.id > lastEnd), readCompactionBoundaries(db), minSpanMs);
113
+ const renumber = (p) => ({ ...p, index: p.index + lastIndex });
114
+ return { closed: [...frozen, ...rest.closed.map(renumber)], tail: rest.tail ? renumber(rest.tail) : null };
115
+ }
116
+ function libraryMinSpanMs() {
117
+ const envH = envNum('OSBORN_LIBRARY_MIN_PERIOD_H');
118
+ return envH ? envH * 3_600_000 : DEFAULT_MIN_SPAN_MS;
119
+ }
99
120
  /** Run the library step once. Never throws. */
100
121
  export async function runLibraryStep(o) {
101
122
  const log = o.log ?? (() => { });
@@ -111,13 +132,10 @@ export async function runLibraryStep(o) {
111
132
  if (!db)
112
133
  return { ...res, status: 'no-db' };
113
134
  const projectDir = dirname(dirname(dirname(db)));
114
- const envH = envNum('OSBORN_LIBRARY_MIN_PERIOD_H');
115
- const minSpan = o.minSpanMs ?? (envH ? envH * 3_600_000 : DEFAULT_MIN_SPAN_MS);
116
135
  const dir = (res.libraryDir = o.outDir ?? libraryDirFor(db, o.sessionId));
117
- // Segment the whole session at its compaction seams (ids + timestamps only).
118
- const rows = loadConversationRows(db, 0).records.map(r => ({ id: r.id, timestamp: r.timestamp }));
119
- const seg = segmentPeriods(rows, readCompactionBoundaries(db), minSpan);
120
136
  const manifest = readManifest(dir, o.sessionId);
137
+ const minSpan = o.minSpanMs ?? libraryMinSpanMs();
138
+ const seg = librarySegments(db, manifest, minSpan);
121
139
  const pick = pickLibraryPeriod(seg, start => manifest.periods[String(start)]?.status === 'ok', minSpan);
122
140
  log(`library: ${seg.closed.length} closed period(s), tail ${seg.tail ? `#${seg.tail.startRowId}–#${seg.tail.endRowId} (${(seg.tail.spanMs / 3_600_000).toFixed(1)}h)` : 'none'} → ${pick.reason}`);
123
141
  const red = loadClientRedactor(projectDir);
@@ -131,6 +149,11 @@ export async function runLibraryStep(o) {
131
149
  const p = (res.period = pick.period);
132
150
  const key = String(p.startRowId);
133
151
  const file = pageFileName(p);
152
+ // Never overwrite a page this manifest did not write (e.g. a manual backfill page).
153
+ if (!o.outDir && existsSync(join(dir, file)) && !Object.values(manifest.periods).some(e => e.file === file)) {
154
+ log(`library: ${file} exists and is not ours — not overwritten`);
155
+ return { ...res, status: 'already-written' };
156
+ }
134
157
  // Period map on exactly this row range, staged first; published only when a map came back.
135
158
  mkdirSync(join(dir, STAGING_DIR), { recursive: true });
136
159
  const staged = join(dir, STAGING_DIR, file);