osborn 0.9.280 → 0.9.282
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.
- package/dist/agent-store.d.ts +164 -0
- package/dist/agent-store.js +302 -0
- package/dist/claude-llm.d.ts +7 -8
- package/dist/claude-llm.js +75 -171
- package/dist/content/compaction-lens-worker.js +2 -1
- package/dist/content/content-run.js +9 -9
- package/dist/content/lens-clip-window.js +7 -6
- package/dist/content/lens-launch.d.ts +11 -0
- package/dist/content/lens-launch.js +11 -0
- package/dist/content/lens-library-select.d.ts +7 -5
- package/dist/content/lens-library-select.js +7 -6
- package/dist/content/lens-library.d.ts +7 -1
- package/dist/content/lens-library.js +29 -6
- package/dist/data-sender-auth.d.ts +3 -2
- package/dist/data-sender-auth.js +10 -3
- package/dist/index.js +376 -190
- package/dist/pipeline-direct-llm.d.ts +1 -1
- package/dist/pipeline-direct-llm.js +1 -1
- package/dist/prompts/chain-after-planner.md +1 -0
- package/dist/prompts/chain-after-researcher.md +1 -0
- package/dist/prompts/chain-after-writer.md +1 -0
- package/dist/prompts/direct-mode-research.md +2 -2
- package/dist/prompts/steward.md +131 -0
- package/dist/prompts.d.ts +6 -0
- package/dist/prompts.js +18 -1
- package/dist/pushover.d.ts +7 -0
- package/dist/pushover.js +45 -42
- package/dist/steward-gate.d.ts +6 -5
- package/dist/steward-gate.js +256 -32
- package/dist/steward-verdict.d.ts +23 -0
- package/dist/steward-verdict.js +97 -0
- package/dist/stopwords.d.ts +1 -0
- package/dist/stopwords.js +6 -0
- package/dist/store-catalog.d.ts +106 -0
- package/dist/store-catalog.js +356 -0
- package/dist/store-name.d.ts +1 -0
- package/dist/store-name.js +7 -0
- package/package.json +1 -1
package/dist/claude-llm.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
293
|
-
|
|
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
|
|
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 (
|
|
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 (
|
|
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: '
|
|
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 (
|
|
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 (
|
|
884
|
-
model: '
|
|
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
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
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,74 +1007,42 @@ function isWorkspacePath(filePath) {
|
|
|
1089
1007
|
return isSafeArtifactPath(filePath);
|
|
1090
1008
|
}
|
|
1091
1009
|
/**
|
|
1092
|
-
* Decide a Write/Edit/MultiEdit for the acting agent (null = main
|
|
1093
|
-
*
|
|
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(
|
|
1099
|
-
const rule =
|
|
1016
|
+
export function decideWrite(role, filePath) {
|
|
1017
|
+
const rule = role ? ROLES[role].write : 'workspace';
|
|
1100
1018
|
if (rule === 'anywhere')
|
|
1101
1019
|
return { decision: 'defer' };
|
|
1020
|
+
// Fail closed for every limited role: an edit with no path is denied.
|
|
1021
|
+
if (!filePath)
|
|
1022
|
+
return { decision: 'deny', reason: 'Write denied: could not determine target file path. Failing closed.' };
|
|
1102
1023
|
if (rule === 'workspace') {
|
|
1103
|
-
if (
|
|
1024
|
+
if (!isWorkspacePath(filePath)) {
|
|
1104
1025
|
return { decision: 'deny', reason: 'Research mode: writes restricted to session workspace.' };
|
|
1105
1026
|
}
|
|
1106
1027
|
return { decision: 'allow' };
|
|
1107
1028
|
}
|
|
1108
|
-
// Extension whitelist
|
|
1109
|
-
const target = rule.matchBasename ?
|
|
1110
|
-
if (!
|
|
1111
|
-
|
|
1112
|
-
? `Write denied: ${filePath} is not a ${rule.label} file. This agent may only write ${rule.label} files.`
|
|
1113
|
-
: 'Write denied: could not determine target file path. Failing closed.';
|
|
1114
|
-
return { decision: 'deny', reason };
|
|
1029
|
+
// Extension whitelist.
|
|
1030
|
+
const target = rule.matchBasename ? basename(resolve(filePath)) : filePath;
|
|
1031
|
+
if (!rule.extensions.test(target)) {
|
|
1032
|
+
return { decision: 'deny', reason: `Write denied: ${filePath} is not a ${rule.label} file. This agent may only write ${rule.label} files.` };
|
|
1115
1033
|
}
|
|
1116
1034
|
return { decision: 'defer' };
|
|
1117
1035
|
}
|
|
1118
1036
|
// ── Verifier chaining (Pattern #1) ──────────────────────────────────────────
|
|
1119
|
-
// Verifiers are real named Task sub-agents
|
|
1120
|
-
//
|
|
1121
|
-
//
|
|
1122
|
-
//
|
|
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
|
|
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
|
|
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
|
|
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,28 +2539,30 @@ 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
|
|
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
|
-
this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: gate.message });
|
|
2659
2549
|
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gate.message };
|
|
2660
2550
|
}
|
|
2661
2551
|
if (gate.decision === 'advise')
|
|
2662
2552
|
stewardNote = gate.message ?? null;
|
|
2663
2553
|
}
|
|
2664
|
-
//
|
|
2665
|
-
//
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
const
|
|
2554
|
+
// File-edit access control (agent-store.ts EDIT_TOOLS) — keyed by the agent's ROLE
|
|
2555
|
+
// (agent-store.ts ROLES), so forks and imports keep their role's rule.
|
|
2556
|
+
if (EDIT_TOOLS.has(toolName)) {
|
|
2557
|
+
const filePath = String(toolInput.file_path || toolInput.notebook_path || '');
|
|
2558
|
+
const role = roleOf(agentType, this.#opts.agentRoles, NAMED_AGENTS);
|
|
2559
|
+
const historyFirst = !!(role && ROLES[role].historyFirst);
|
|
2669
2560
|
// Writer PROVENANCE REMINDER (Chesterton's Fence): on the writer's FIRST edit of
|
|
2670
2561
|
// an EXISTING (version-controlled) file this turn, deny ONCE with a reminder to
|
|
2671
2562
|
// review the file's git history so the change is backward-informed (root cause,
|
|
2672
2563
|
// prior/reverted attempts, cross-component coupling), not forward-only — then it
|
|
2673
2564
|
// proceeds. New files are exempt (no history). One-shot per turn so it can't loop.
|
|
2674
|
-
if (
|
|
2565
|
+
if (historyFirst && filePath && existsSync(filePath) && !writerHistoryReminded) {
|
|
2675
2566
|
writerHistoryReminded = true;
|
|
2676
2567
|
const base = filePath.split('/').pop() || filePath;
|
|
2677
2568
|
const gateReason = [
|
|
@@ -2682,20 +2573,20 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2682
2573
|
`Then re-attempt this edit. (One-time reminder this turn; new files are exempt.)`,
|
|
2683
2574
|
].join('\n');
|
|
2684
2575
|
console.log(`🏛️ Writer provenance reminder: nudging before ${base} (first edit of an existing file this turn)`);
|
|
2685
|
-
this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Review ${base}'s git history first (one-time provenance reminder)
|
|
2576
|
+
this.#eventEmitter.emit('tool_blocked', { name: toolName, reason: `Review ${base}'s git history first (one-time provenance reminder).`, kind: 'reminder' });
|
|
2686
2577
|
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gateReason };
|
|
2687
2578
|
}
|
|
2688
|
-
const { decision, reason } = decideWrite(
|
|
2689
|
-
console.log(`🔎 Write gate: agent=${agentType ?? 'main'} path="${filePath || '(none)'}" → ${decision}`);
|
|
2579
|
+
const { decision, reason } = decideWrite(role, filePath);
|
|
2580
|
+
console.log(`🔎 Write gate: agent=${agentType ?? 'main'} role=${role ?? '-'} path="${filePath || '(none)'}" → ${decision}`);
|
|
2690
2581
|
if (decision === 'deny') {
|
|
2691
|
-
this.#eventEmitter.emit('tool_blocked', { name: toolName, reason });
|
|
2582
|
+
this.#eventEmitter.emit('tool_blocked', { name: toolName, reason, agent: agentType ?? 'main', role, path: filePath });
|
|
2692
2583
|
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason };
|
|
2693
2584
|
}
|
|
2694
2585
|
if (decision === 'defer') {
|
|
2695
2586
|
// Writer ('anywhere') surfaces its write in the live trace before
|
|
2696
2587
|
// the permission dialog; adversarial agents (reviewer/tester) do
|
|
2697
2588
|
// NOT emit here — parity with the prior hardcoded branches.
|
|
2698
|
-
if (
|
|
2589
|
+
if (historyFirst) {
|
|
2699
2590
|
this.#eventEmitter.emit('tool_use', { name: toolName, input: toolInput, agentRole: agentType || 'main', agentId: input?.agent_id });
|
|
2700
2591
|
}
|
|
2701
2592
|
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask' } };
|
|
@@ -3174,23 +3065,36 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
3174
3065
|
const aid = input?.agent_id ?? ('sa-' + Date.now());
|
|
3175
3066
|
statusManager.upsertDispatch(aid, { subagentType: at, dispatchState: 'completed', artifact: msg });
|
|
3176
3067
|
this.#eventEmitter.emit('task_completed', { agent_type: at, agent_id: aid, last_assistant_message: String(msg).slice(0, 400) });
|
|
3068
|
+
// Steward verdict card (#221): parsed, kept in the session's sidecar, sent to the chat.
|
|
3069
|
+
const atRole = roleOf(at, this.#opts.agentRoles, NAMED_AGENTS);
|
|
3070
|
+
const verdict = atRole && ROLES[atRole].verdict ? parseStewardVerdict(msg) : null;
|
|
3071
|
+
if (verdict) {
|
|
3072
|
+
try {
|
|
3073
|
+
if (this.#sessionId && this.#opts.workingDirectory)
|
|
3074
|
+
appendStewardVerdict(this.#sessionId, this.#opts.workingDirectory, verdict);
|
|
3075
|
+
}
|
|
3076
|
+
catch (e) {
|
|
3077
|
+
console.warn('steward verdict persist failed:', e instanceof Error ? e.message : e);
|
|
3078
|
+
}
|
|
3079
|
+
this.#eventEmitter.emit('steward_verdict', verdict);
|
|
3080
|
+
}
|
|
3177
3081
|
// Pattern #1 verifier chaining — CORRECT timing (moved here from PostToolUse).
|
|
3178
3082
|
// SubagentStop fires at REAL completion. When a chained producer (writer/researcher)
|
|
3179
|
-
// finishes, push its
|
|
3083
|
+
// finishes, push its chain reminder (prompts/chain-after-<role>.md) into the MAIN agent's streaming input so the main
|
|
3180
3084
|
// agent dispatches the next verifier(s) as real Task sub-agents (verdicts return
|
|
3181
|
-
// inline). Only writer/researcher
|
|
3182
|
-
// verifiers (reviewer/tester/reasoner) never re-chain. Dedup on agent_id guards a
|
|
3085
|
+
// inline). Only roles with a chain (writer/planner/researcher) push a reminder, so
|
|
3086
|
+
// verifiers (reviewer/tester/reasoner/steward) never re-chain. Dedup on agent_id guards a
|
|
3183
3087
|
// double-fired SubagentStop; a fresh fix-round writer has a NEW id → re-chains (the
|
|
3184
3088
|
// intended bounded loop). Guarded on a live session so we never cold-start a query
|
|
3185
3089
|
// just to deliver a reminder. Silent-dispatch prefix keeps it off the voice.
|
|
3186
|
-
const
|
|
3090
|
+
const chainReminder = atRole && ROLES[atRole].chain ? getChainReminder(atRole, at) : null;
|
|
3187
3091
|
// Dedup MUST key on the REAL agent_id, never the fabricated 'sa-<ts>' fallback used
|
|
3188
3092
|
// above for status/emit — a synthetic id is unique every call and would defeat the
|
|
3189
3093
|
// double-fire guard. If the SDK omits agent_id we can't dedup safely, so skip chaining.
|
|
3190
|
-
if (
|
|
3094
|
+
if (chainReminder && input?.agent_id && this.#llmRef.hasSession() && this.#llmRef.markChainDispatched(input.agent_id)) {
|
|
3191
3095
|
console.log(`[DISPATCH] Pattern#1 chain (SubagentStop): ${at} done → pushing verify reminder to main agent`);
|
|
3192
3096
|
try {
|
|
3193
|
-
this.#llmRef.pushMessage(SILENT_VERIFY_PREFIX +
|
|
3097
|
+
this.#llmRef.pushMessage(SILENT_VERIFY_PREFIX + chainReminder, sdkOptions, {
|
|
3194
3098
|
onSessionId: this.#onSessionId,
|
|
3195
3099
|
onCheckpoint: this.#onCheckpoint,
|
|
3196
3100
|
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 {
|
|
22
|
-
import {
|
|
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
|
|
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:
|
|
50
|
+
return isDone(handoff.startRowId) ? { period: null, reason: 'already-done' } : { period: handoff, page: fileOf(handoff) };
|
|
49
51
|
}
|
|
50
|
-
const
|
|
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:
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
'
|
|
19
|
-
|
|
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
|
|
2
|
+
* lens-library-select.ts — which PERIOD just ended. Pure + deterministic.
|
|
3
3
|
*
|
|
4
|
-
* A period runs from one
|
|
5
|
-
*
|
|
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
|
|
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
|
|
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 = {
|