osborn 0.9.280 → 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 (38) 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 +7 -8
  4. package/dist/claude-llm.js +65 -160
  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/pipeline-direct-llm.d.ts +1 -1
  18. package/dist/pipeline-direct-llm.js +1 -1
  19. package/dist/prompts/chain-after-planner.md +1 -0
  20. package/dist/prompts/chain-after-researcher.md +1 -0
  21. package/dist/prompts/chain-after-writer.md +1 -0
  22. package/dist/prompts/direct-mode-research.md +2 -2
  23. package/dist/prompts/steward.md +131 -0
  24. package/dist/prompts.d.ts +6 -0
  25. package/dist/prompts.js +18 -1
  26. package/dist/pushover.d.ts +2 -0
  27. package/dist/pushover.js +4 -2
  28. package/dist/steward-gate.d.ts +6 -5
  29. package/dist/steward-gate.js +256 -32
  30. package/dist/steward-verdict.d.ts +23 -0
  31. package/dist/steward-verdict.js +97 -0
  32. package/dist/stopwords.d.ts +1 -0
  33. package/dist/stopwords.js +6 -0
  34. package/dist/store-catalog.d.ts +101 -0
  35. package/dist/store-catalog.js +336 -0
  36. package/dist/store-name.d.ts +1 -0
  37. package/dist/store-name.js +3 -0
  38. 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,7 +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, SIGNOFF_COMMAND } from './steward-gate.js';
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';
25
27
  // Directory of this module — used to locate co-located prompt files (e.g., turn-shape reminder).
26
28
  const __claudeLlmDir = dirname(fileURLToPath(import.meta.url));
27
29
  const TURN_SHAPE_REMINDER_PATH = join(__claudeLlmDir, 'prompts', 'turn-shape-reminder.md');
@@ -289,14 +291,8 @@ function loadAllSkills(_workingDir) {
289
291
  // relevant skills rather than an alphabetical accident.
290
292
  const SKILL_BODY_BUDGET = 200_000;
291
293
  function extractSkillDescription(raw) {
292
- let desc = '';
293
- const fm = raw.match(/^---\n([\s\S]*?)\n---/);
294
- if (fm) {
295
- const m = fm[1].match(/^description:\s*(.+)$/m);
296
- if (m)
297
- desc = m[1].trim();
298
- }
299
- const body = raw.replace(/^---\n[\s\S]*?\n---\n?/, '');
294
+ const { meta, body } = parseFrontMatter(raw);
295
+ let desc = typeof meta.description === 'string' ? meta.description : '';
300
296
  if (!desc) {
301
297
  const when = body.match(/^\s*WHEN:\s*(.+)$/mi);
302
298
  if (when)
@@ -349,7 +345,7 @@ function enumerateSkillsForCompaction() {
349
345
  }
350
346
  else {
351
347
  // Over budget → headings-only fallback (still enough to dedup + target a section).
352
- const body = raw.replace(/^---\n[\s\S]*?\n---\n?/, '');
348
+ const { body } = parseFrontMatter(raw);
353
349
  const headings = (body.match(/^#{2,6}\s+.+$/gm) || [])
354
350
  .map(h => h.replace(/^#+\s+/, '').trim());
355
351
  blocks.push(`${header}(full body omitted — over injection budget)\nsections: ${headings.join(' | ') || '(none)'}`);
@@ -643,7 +639,7 @@ export const NAMED_AGENTS = {
643
639
  'Returns structured pass/fail results with exact output — does NOT edit files.',
644
640
  'NOT GROUNDED: no session index access — runs tests with fresh eyes, adversarial validation.',
645
641
  ].join(' '),
646
- 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)
647
643
  model: 'sonnet',
648
644
  prompt: [
649
645
  'You are Osborn\'s tester agent. Your job is running tests and builds, then reporting results.',
@@ -787,101 +783,25 @@ export const NAMED_AGENTS = {
787
783
  },
788
784
  steward: {
789
785
  description: [
790
- 'Codebase-steward agent (Sonnet). NOT GROUNDED: reads the repo and its git history directly. Owns duplication and regressions, not features. Use (1) on a PLAN before',
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',
791
787
  'any code is written, to answer "does this already exist?" for every new function, route, module, table or',
792
788
  'feature; (2) on the DIFF after the writer and tester, to refactor it to reuse existing code, cut what is not',
793
789
  'needed, and map every changed symbol to its callers. Returns CLEAN, REFACTORED or BLOCK. Never reviews its own refactor.',
794
790
  ].join(' '),
795
791
  tools: ['Read', 'Glob', 'Grep', 'Bash', 'Edit', 'Write', 'MultiEdit'],
796
- model: 'sonnet',
797
- prompt: [
798
- 'You are Osborn\'s steward agent. You own the codebase: you are responsible for duplication and regressions,',
799
- 'not for features. Bloat compounds: every duplicate widens the code that agents and people must read, which',
800
- 'causes more misses and more duplicates. You debloat new code and protect existing code.',
801
- '',
802
- '## Principles',
803
- '- Proven code wins. Code that already works is trusted over anything new. If a change avoids, replaces or',
804
- ' changes the behaviour of existing working code, state why; with no strong reason, keep and reuse it.',
805
- '- Extend before you create. Prefer a parameter, option or small branch on an existing function over a new',
806
- ' module, route, table or helper. A brand-new module is the last resort and needs a written reason.',
807
- '- Know why before you add: before adding a guard, check, retry, helper or option, find what already handles it.',
808
- '- Rule of three. A second near-copy may stay if extracting it would mean guessing the shared shape; note it.',
809
- ' A third copy may not: consolidate all three into one shared function in this change.',
810
- '- Scope: act only on the diff (or plan) and on the code it duplicates. Never rewrite untouched code.',
811
- '',
812
- '## Plan mode (the task gives you a plan, no diff yet)',
813
- 'For every new function, route, module, table, config or feature in the plan, search the repo (Grep/Glob,',
814
- 'git log -S) for something that already does it. Return a reuse map: each item → existing thing to reuse or',
815
- 'extend, or a one-line net-new reason. Do not edit files in plan mode.',
816
- '',
817
- '## History first (both modes)',
818
- 'Git history, GitHub issues and PR descriptions are the project\'s memory and decision log; there is no separate',
819
- 'ledger. Compute these for the touched files; never assume which files are hotspots, they move over time.',
820
- '- Churn: `git log --since=60.days --oneline -- <file>`: how often it changes and how many of those were fixes.',
821
- '- Re-touched lines: `git log --since=30.days -L <a>,<a+b>:<file>` using the OLD-side range (-a,b) of each hunk',
822
- ' of `git diff HEAD`; skip files new in the diff. Lines a recent fix already changed mean a repeat.',
823
- '- Coupling: `git log --since=60.days --full-diff --name-only --format= -- <file> | sort | uniq -c | sort -rn | head`.',
824
- ' A usual partner missing from the diff is a likely regression, especially across a client/server boundary.',
825
- '- Prior decisions: `git log -S <symbol>` / `--grep <topic>`; `gh issue list --state all --search "<topic>"` and',
826
- ' `gh pr list --state all --search "<topic>"` (skip if gh is absent). Earlier PRs\' "Why" sections are the',
827
- ' decision records.',
828
- '',
829
- '## Diff mode (after the writer)',
830
- '0. `git status`, `git diff HEAD --stat`, `git diff HEAD` (include untracked files). Count lines added/removed.',
831
- ' Then run History first on the touched files. Classify the change: a new isolated feature, or a change to',
832
- ' existing working code. The budget in step 8 applies to the second; a feature is judged by "does it exist?".',
833
- '1. Reuse first: for every added function, class, route, module, table or config, search for existing logic',
834
- ' that does the same or nearly the same. If found, EDIT the diff to reuse or extend it instead (a second',
835
- ' near-copy may stay per the rule of three).',
836
- '2. Net-new must be justified: anything still new gets a one-line reason nothing existing fits.',
837
- '3. Surgical diff: remove unreachable guards, speculative options, dead branches and duplicated validation.',
838
- ' If the diff mixes unrelated concerns (a fix, a refactor, a version bump), say which belong in a separate change.',
839
- '4. Regressions: for every changed or removed symbol, find its callers and consumers (routes, schedulers,',
840
- ' frontend, docs, tests, client/server messages) and confirm each still works. Flag any behaviour change',
841
- ' for an existing caller (status codes, response shapes, stored values, message fields).',
842
- '5. Decisions: do not silently undo a decision found in history, PRs or the project\'s docs; name any it reverses.',
843
- '6. Single source of truth: if the diff adds a second copy of a rule (validation, error codes, config,',
844
- ' constants), merge it into the existing copy.',
845
- '7. Repeats: if the change re-touches lines a fix changed in the last 30 days, or follows up an earlier issue,',
846
- ' write the chain (#A → #B → this) and the root cause with its evidence (a measurement, log or reproduction),',
847
- ' taken from the task, the linked issue or the commit message. If the only change is a wider timeout, a retry,',
848
- ' a fallback, a delay or a guard and no cause is given anywhere, that is a symptom fix: BLOCK and ask for the',
849
- ' cause. In a high-churn file, recommend moving the touched part where it belongs as a separate change.',
850
- '8. Budget: on existing working code aim for lines added ≤ lines removed (tests excluded) within the diff;',
851
- ' growth needs a NET-NEW reason. Do not cut untouched code to meet it.',
852
- '9. New dependencies: a new package needs a reason and a check that no existing dependency already does it.',
853
- '',
854
- '## Bash',
855
- 'Read-only inspection (git diff/log/show/grep, gh issue/pr list|view, tsc --noEmit, tests) plus the sign-off',
856
- 'command below. Never commit, push, reset, checkout, stash or delete. Your edits are file edits only.',
857
- '',
858
- '## Sign-off',
859
- 'After a CLEAN or REFACTORED verdict in diff mode, run this from the repository root to record your sign-off',
860
- 'for this exact content (any later edit invalidates it; the commit/push/PR gate checks it):',
861
- ' ' + SIGNOFF_COMMAND,
862
- 'Never sign off on BLOCK. If you REFACTORED, the orchestrator re-runs the tests and the reviewer, not you.',
863
- '',
864
- '## What to return',
865
- 'VERDICT: CLEAN | REFACTORED | BLOCK — <one line>',
866
- 'REUSE MAP: <new item> → <existing item reused/extended> | NET-NEW: <reason>',
867
- 'REMOVED: <what you cut and why> (or none)',
868
- 'REGRESSION MAP: <changed symbol> → <callers> → <ok / broken + why>',
869
- 'LINES: +<added> -<removed> before → +<added> -<removed> after',
870
- 'HISTORY: churn of touched files, re-touched lines, coupled files, related issues/PRs (one line each)',
871
- 'ROOT CAUSE: for a fix, the cause and its evidence, or the chain it ends (omit for a pure feature)',
872
- 'For BLOCK, name the decision a human has to make.',
873
- ].join('\n'),
792
+ model: 'opus',
793
+ prompt: getStewardPrompt(), // agent/src/prompts/steward.md (also used by .claude/agents/steward.md)
874
794
  },
875
795
  reviewer: {
876
796
  description: [
877
- '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',
878
798
  'writer completes a change, the reviewer reads the diff, checks correctness, spec/requirement',
879
799
  'adherence, obvious bugs, and security issues, then tags each finding BLOCKER/MAJOR/MINOR/NIT',
880
800
  'and returns an ACCEPT or REJECT verdict with specific, actionable feedback. May write documentation files (.md etc.) only.',
881
801
  'NOT GROUNDED: no session index access — reviews with fresh eyes for unbiased adversarial check.',
882
802
  ].join(' '),
883
- tools: ['Read', 'Glob', 'Grep', 'Bash', 'Write', 'Edit'], // write-gate: docs only (WRITE_RULES.reviewer)
884
- model: 'sonnet',
803
+ tools: ['Read', 'Glob', 'Grep', 'Bash', 'Write', 'Edit'], // write-gate: docs only (ROLES.reviewer.write)
804
+ model: 'opus',
885
805
  prompt: [
886
806
  'You are Osborn\'s reviewer agent. You are the VERIFY step in a generator-verifier loop.',
887
807
  '',
@@ -1073,12 +993,10 @@ export function applyGrounding(agents, sessionId, workingDir) {
1073
993
  }
1074
994
  return out;
1075
995
  }
1076
- const WRITE_RULES = {
1077
- writer: 'anywhere',
1078
- tester: { extensions: /\.(test|spec)\.[jt]sx?$/, label: 'test', matchBasename: true },
1079
- reviewer: { extensions: /\.(md|markdown|mdx|txt|rst|adoc)$/i, label: 'documentation' },
1080
- steward: 'anywhere', // refactors the writer's diff in place
1081
- };
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'.
1082
1000
  /**
1083
1001
  * Path is inside the per-session sandbox workspace. Used by decideWrite's
1084
1002
  * 'workspace' rule: true → write allowed, false → denied. Robust resolve+root
@@ -1089,14 +1007,14 @@ function isWorkspacePath(filePath) {
1089
1007
  return isSafeArtifactPath(filePath);
1090
1008
  }
1091
1009
  /**
1092
- * Decide a Write/Edit/MultiEdit for the acting agent (null = main orchestrator).
1093
- * 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:
1094
1012
  * 'allow' → fall through (→ canUseTool workspace auto-approve, or {}).
1095
1013
  * 'defer' → PreToolUse 'ask' (canUseTool decides).
1096
1014
  * 'deny' → hard block with reason.
1097
1015
  */
1098
- export function decideWrite(agentType, filePath) {
1099
- const rule = (agentType && WRITE_RULES[agentType]) || 'workspace';
1016
+ export function decideWrite(role, filePath) {
1017
+ const rule = role ? ROLES[role].write : 'workspace';
1100
1018
  if (rule === 'anywhere')
1101
1019
  return { decision: 'defer' };
1102
1020
  if (rule === 'workspace') {
@@ -1116,47 +1034,15 @@ export function decideWrite(agentType, filePath) {
1116
1034
  return { decision: 'defer' };
1117
1035
  }
1118
1036
  // ── Verifier chaining (Pattern #1) ──────────────────────────────────────────
1119
- // Verifiers are real named Task sub-agents (the `agents` roster), NOT out-of-band
1120
- // query() spawns. Two enforcement points:
1121
- // • parallelAtStart — verifiers the ORCHESTRATOR must dispatch IN PARALLEL with
1122
- // the keyed agent (enforced by the orchestrator prompt; a post-hoc hook cannot
1123
- // make two Tasks run concurrently). Tester is TDD: it WRITES tests from the
1124
- // spec in parallel with the writer, blind to the implementation.
1125
- // • afterReminder — injected into the MAIN agent by the PostToolUse-on-Task hook
1126
- // when the keyed sub-agent's Task completes, so the main agent dispatches the
1127
- // next verifier(s) as real Tasks (verdicts return inline). Includes RUNNING the
1128
- // 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.
1129
1041
  // Prepended to a verifier-chain reminder pushed into the MAIN agent at SubagentStop. Keeps the
1130
1042
  // dispatch SILENT — the model should emit ONLY the Task tool call(s), no spoken/streamed text —
1131
1043
  // so the chain advances without a robotic "now running the review…" narration on the voice path.
1132
1044
  export const SILENT_VERIFY_PREFIX = '[SYSTEM — SILENT CONTROL MESSAGE. Do NOT narrate, speak, or emit any assistant text this turn. ' +
1133
1045
  'Silently perform the following via the Task tool only.] ';
1134
- export const VERIFIER_CHAIN = {
1135
- writer: {
1136
- parallelAtStart: ['tester'],
1137
- afterReminder: 'The writer sub-agent just finished. Before you finalize, you MUST now use the Task tool to: ' +
1138
- "(1) RUN the tester's tests against the new implementation and report PASS/FAIL; " +
1139
- '(2) dispatch the `steward` on the diff (diff mode), passing the task and, for a fix, its root cause and evidence — it refactors toward reuse and returns CLEAN, REFACTORED or BLOCK; ' +
1140
- "(3) if it REFACTORED, RUN the tests again; (4) dispatch the `reviewer` on the final diff for a VERDICT. " +
1141
- 'If the steward returns BLOCK, stop and ask the user the decision it names. ' +
1142
- 'If tests FAIL or the reviewer REJECTs, dispatch the `writer` to fix and then re-verify (steward included) — ' +
1143
- 'at most 2 fix rounds, after which surface the outcome to the user rather than looping. ' +
1144
- "In any PR description, put the steward's ROOT CAUSE under Why, and its NET-NEW and REMOVED lists under those headings.",
1145
- },
1146
- planner: {
1147
- afterReminder: 'The planner sub-agent just finished. Before the writer starts, use the Task tool to dispatch the `steward` ' +
1148
- 'in PLAN MODE on that plan: for every new function, route, module, table or feature it answers "does this already exist?". ' +
1149
- 'Give the writer the plan WITH the steward\'s reuse map.',
1150
- },
1151
- researcher: {
1152
- afterReminder: 'The researcher sub-agent just finished. Before you finalize, you MUST now use the Task tool to ' +
1153
- 'dispatch the `reasoner` GATE to judge whether the research is complete and well-sourced for the ' +
1154
- 'original question — it returns GATE: PASS or GATE: NEEDS-MORE. ' +
1155
- 'If it returns NEEDS-MORE, dispatch the `researcher` again with the gaps it named and then re-gate — ' +
1156
- 'at most 2 rounds, after which surface the outcome to the user rather than looping. ' +
1157
- "This is the research analogue of writer→reviewer: don't rely on the findings until an independent agent has vetted them.",
1158
- },
1159
- };
1160
1046
  const RESEARCH_TOOLS = [
1161
1047
  'Read', 'Write', 'Edit', 'Glob', 'Grep',
1162
1048
  'Bash', 'WebSearch', 'WebFetch',
@@ -1544,8 +1430,9 @@ export class ClaudeLLM extends llm.LLM {
1544
1430
  * start (session start/resume/switch) — a live subprocess keeps the agents
1545
1431
  * it was created with.
1546
1432
  */
1547
- setAgents(agents) {
1433
+ setAgents(agents, roles) {
1548
1434
  this.#opts.agents = agents;
1435
+ this.#opts.agentRoles = roles;
1549
1436
  console.log(`🤖 Named agents ${agents ? `set (${Object.keys(agents).join(', ')})` : 'reset to built-ins'} — applies at next query cold start`);
1550
1437
  }
1551
1438
  /**
@@ -2571,14 +2458,16 @@ class ClaudeLLMStream extends llm.LLMStream {
2571
2458
  console.log(`✅ Auto-approved ${toolName} to workspace: ${filePath}`);
2572
2459
  return { behavior: 'allow', updatedInput: input };
2573
2460
  }
2574
- // Auto-approve writer sub-agent writes to skill installation directories.
2461
+ // Auto-approve skill-installing roles' (writer) writes to skill installation directories.
2575
2462
  // Pattern matches `.claude/skills/<skillname>/<file>` in any osborn install location
2576
2463
  // (npm global, dev tree, cloud sandbox), so installing a multi-file skill via the
2577
2464
  // writer agent doesn't blow up into a per-file permission cascade.
2578
- // 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
2579
2468
  // before they ever reach canUseTool, so this check is the only path that lets a
2580
2469
  // skill install through silently.
2581
- 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)) {
2582
2471
  console.log(`✅ Auto-approved writer ${toolName} to skill dir: ${filePath}`);
2583
2472
  return { behavior: 'allow', updatedInput: input };
2584
2473
  }
@@ -2650,10 +2539,12 @@ class ClaudeLLMStream extends llm.LLMStream {
2650
2539
  console.log(`🔧 Tool call ${turnToolCallCount} (speak-cadence ${SPEAK_CADENCE_N}, ceiling ${TOOL_HARD_CEILING || 'off'}): ${toolName}`);
2651
2540
  }
2652
2541
  // Steward sign-off gate (#218): a commit, push or PR whose content the steward has
2653
- // not signed off is reported (advise, default) or refused (OSBORN_STEWARD_MODE=block).
2542
+ // not signed off is refused (block, default) or only reported (OSBORN_STEWARD_MODE=advise).
2654
2543
  let stewardNote = null; // advise mode: rides the allow tail below
2655
2544
  if (toolName === 'Bash') {
2656
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 });
2657
2548
  if (gate.decision === 'deny') {
2658
2549
  this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: gate.message });
2659
2550
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gate.message };
@@ -2661,17 +2552,18 @@ class ClaudeLLMStream extends llm.LLMStream {
2661
2552
  if (gate.decision === 'advise')
2662
2553
  stewardNote = gate.message ?? null;
2663
2554
  }
2664
- // Write/Edit/MultiEdit access control — plain WRITE_RULES lookup
2665
- // keyed by agent name (see decideWrite). Same behavior the old
2666
- // hardcoded per-role branches had, now in one visible place.
2667
- if (toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit') {
2668
- const filePath = String(toolInput.file_path || '');
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);
2669
2561
  // Writer PROVENANCE REMINDER (Chesterton's Fence): on the writer's FIRST edit of
2670
2562
  // an EXISTING (version-controlled) file this turn, deny ONCE with a reminder to
2671
2563
  // review the file's git history so the change is backward-informed (root cause,
2672
2564
  // prior/reverted attempts, cross-component coupling), not forward-only — then it
2673
2565
  // proceeds. New files are exempt (no history). One-shot per turn so it can't loop.
2674
- if (agentType === 'writer' && filePath && existsSync(filePath) && !writerHistoryReminded) {
2566
+ if (historyFirst && filePath && existsSync(filePath) && !writerHistoryReminded) {
2675
2567
  writerHistoryReminded = true;
2676
2568
  const base = filePath.split('/').pop() || filePath;
2677
2569
  const gateReason = [
@@ -2685,8 +2577,8 @@ class ClaudeLLMStream extends llm.LLMStream {
2685
2577
  this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Review ${base}'s git history first (one-time provenance reminder).` });
2686
2578
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gateReason };
2687
2579
  }
2688
- const { decision, reason } = decideWrite(agentType, filePath);
2689
- 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}`);
2690
2582
  if (decision === 'deny') {
2691
2583
  this.#eventEmitter.emit('tool_blocked', { name: toolName, reason });
2692
2584
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason };
@@ -2695,7 +2587,7 @@ class ClaudeLLMStream extends llm.LLMStream {
2695
2587
  // Writer ('anywhere') surfaces its write in the live trace before
2696
2588
  // the permission dialog; adversarial agents (reviewer/tester) do
2697
2589
  // NOT emit here — parity with the prior hardcoded branches.
2698
- if (agentType === 'writer') {
2590
+ if (historyFirst) {
2699
2591
  this.#eventEmitter.emit('tool_use', { name: toolName, input: toolInput, agentRole: agentType || 'main', agentId: input?.agent_id });
2700
2592
  }
2701
2593
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask' } };
@@ -3174,23 +3066,36 @@ class ClaudeLLMStream extends llm.LLMStream {
3174
3066
  const aid = input?.agent_id ?? ('sa-' + Date.now());
3175
3067
  statusManager.upsertDispatch(aid, { subagentType: at, dispatchState: 'completed', artifact: msg });
3176
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
+ }
3177
3082
  // Pattern #1 verifier chaining — CORRECT timing (moved here from PostToolUse).
3178
3083
  // SubagentStop fires at REAL completion. When a chained producer (writer/researcher)
3179
- // 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
3180
3085
  // agent dispatches the next verifier(s) as real Task sub-agents (verdicts return
3181
- // inline). Only writer/researcher are VERIFIER_CHAIN keys with afterReminder, so
3182
- // 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
3183
3088
  // double-fired SubagentStop; a fresh fix-round writer has a NEW id → re-chains (the
3184
3089
  // intended bounded loop). Guarded on a live session so we never cold-start a query
3185
3090
  // just to deliver a reminder. Silent-dispatch prefix keeps it off the voice.
3186
- const chainLink = at ? VERIFIER_CHAIN[at] : undefined;
3091
+ const chainReminder = atRole && ROLES[atRole].chain ? getChainReminder(atRole, at) : null;
3187
3092
  // Dedup MUST key on the REAL agent_id, never the fabricated 'sa-<ts>' fallback used
3188
3093
  // above for status/emit — a synthetic id is unique every call and would defeat the
3189
3094
  // double-fire guard. If the SDK omits agent_id we can't dedup safely, so skip chaining.
3190
- 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)) {
3191
3096
  console.log(`[DISPATCH] Pattern#1 chain (SubagentStop): ${at} done → pushing verify reminder to main agent`);
3192
3097
  try {
3193
- this.#llmRef.pushMessage(SILENT_VERIFY_PREFIX + chainLink.afterReminder, sdkOptions, {
3098
+ this.#llmRef.pushMessage(SILENT_VERIFY_PREFIX + chainReminder, sdkOptions, {
3194
3099
  onSessionId: this.#onSessionId,
3195
3100
  onCheckpoint: this.#onCheckpoint,
3196
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>;