@blockrun/franklin 3.32.1 → 3.34.0
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/README.md +23 -2
- package/dist/agent/approvals.d.ts +47 -0
- package/dist/agent/approvals.js +66 -0
- package/dist/agent/commands.js +230 -7
- package/dist/agent/compact.js +1 -1
- package/dist/agent/context.js +1 -1
- package/dist/agent/input-queue.d.ts +26 -0
- package/dist/agent/input-queue.js +65 -0
- package/dist/agent/loop.js +198 -5
- package/dist/agent/optimize.js +1 -1
- package/dist/agent/streaming-executor.d.ts +4 -0
- package/dist/agent/streaming-executor.js +52 -0
- package/dist/agent/tokens.js +2 -0
- package/dist/agent/tool-guard.d.ts +7 -0
- package/dist/agent/tool-guard.js +21 -0
- package/dist/agent/types.d.ts +26 -0
- package/dist/audit/approvals.d.ts +20 -0
- package/dist/audit/approvals.js +21 -0
- package/dist/commands/init.js +1 -1
- package/dist/commands/models.d.ts +11 -0
- package/dist/commands/models.js +157 -37
- package/dist/commands/start.d.ts +10 -1
- package/dist/commands/start.js +53 -1
- package/dist/events/types.d.ts +38 -1
- package/dist/gateway-models.d.ts +14 -2
- package/dist/gateway-models.js +8 -0
- package/dist/goal/engine.d.ts +39 -0
- package/dist/goal/engine.js +182 -0
- package/dist/goal/prompts.d.ts +16 -0
- package/dist/goal/prompts.js +206 -0
- package/dist/goal/runtime.d.ts +20 -0
- package/dist/goal/runtime.js +110 -0
- package/dist/goal/store.d.ts +22 -0
- package/dist/goal/store.js +79 -0
- package/dist/goal/types.d.ts +63 -0
- package/dist/goal/types.js +26 -0
- package/dist/hooks/loader.d.ts +19 -0
- package/dist/hooks/loader.js +115 -0
- package/dist/hooks/runner.d.ts +31 -0
- package/dist/hooks/runner.js +147 -0
- package/dist/hooks/types.d.ts +64 -0
- package/dist/hooks/types.js +35 -0
- package/dist/index.js +5 -1
- package/dist/learnings/extractor.js +1 -1
- package/dist/memory/capture.d.ts +40 -0
- package/dist/memory/capture.js +95 -0
- package/dist/memory/dream.d.ts +24 -0
- package/dist/memory/dream.js +147 -0
- package/dist/memory/indexer.d.ts +29 -0
- package/dist/memory/indexer.js +144 -0
- package/dist/memory/store.d.ts +50 -0
- package/dist/memory/store.js +163 -0
- package/dist/monitors/registry.d.ts +42 -0
- package/dist/monitors/registry.js +104 -0
- package/dist/panel/html.js +299 -0
- package/dist/panel/server.js +41 -0
- package/dist/pricing.js +4 -1
- package/dist/router/index.js +15 -9
- package/dist/router/vision.js +5 -4
- package/dist/scheduler/service.d.ts +24 -0
- package/dist/scheduler/service.js +44 -0
- package/dist/scheduler/store.d.ts +26 -0
- package/dist/scheduler/store.js +116 -0
- package/dist/scheduler/types.d.ts +36 -0
- package/dist/scheduler/types.js +31 -0
- package/dist/serve/agent-host.d.ts +63 -0
- package/dist/serve/agent-host.js +270 -0
- package/dist/serve/server.js +131 -2
- package/dist/session/live-registry.d.ts +32 -0
- package/dist/session/live-registry.js +83 -0
- package/dist/session/search.d.ts +6 -0
- package/dist/session/search.js +3 -3
- package/dist/session/storage.d.ts +6 -0
- package/dist/session/storage.js +6 -0
- package/dist/tools/goal.d.ts +7 -0
- package/dist/tools/goal.js +29 -0
- package/dist/tools/index.js +11 -0
- package/dist/tools/memory.js +14 -4
- package/dist/tools/moa.js +1 -1
- package/dist/tools/monitor.d.ts +11 -0
- package/dist/tools/monitor.js +96 -0
- package/dist/tools/scheduler.d.ts +12 -0
- package/dist/tools/scheduler.js +79 -0
- package/dist/tools/spend-tools.d.ts +33 -0
- package/dist/tools/spend-tools.js +114 -0
- package/dist/tools/tool-categories.js +7 -0
- package/dist/tools/trade-plan.d.ts +11 -0
- package/dist/tools/trade-plan.js +137 -0
- package/dist/tools/trading-execute.js +24 -0
- package/dist/trading/trade-plan.d.ts +75 -0
- package/dist/trading/trade-plan.js +290 -0
- package/dist/ui/app.js +54 -9
- package/dist/ui/model-picker.d.ts +40 -0
- package/dist/ui/model-picker.js +135 -25
- package/package.json +2 -2
- package/dist/agent/media-router.d.ts +0 -98
- package/dist/agent/media-router.js +0 -328
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal-engine prompt templates. All roles except the summarizer write for
|
|
3
|
+
* MACHINE readers (the implementer, the verifier panel, the parser) — keep
|
|
4
|
+
* their outputs structured and terse. The summarizer alone writes for the
|
|
5
|
+
* user.
|
|
6
|
+
*/
|
|
7
|
+
// ─── Planner ───────────────────────────────────────────────────────────────
|
|
8
|
+
const KIND_GUIDANCE = {
|
|
9
|
+
trading: `This is a TRADING goal. The plan MUST include:
|
|
10
|
+
- Entry criteria (what conditions justify opening each position)
|
|
11
|
+
- Exit criteria (profit target and stop conditions, in plain language)
|
|
12
|
+
- Risk limits: an explicit "Budget: $X" line (the maximum total USD at risk)
|
|
13
|
+
- A monitoring cadence if the goal spans time (use the Scheduler/Monitor tools)
|
|
14
|
+
Remember: every real-money trade will separately require an approved trade plan at execution time — your acceptance criteria should reference outcomes (position opened/closed per criteria, P&L recorded), not raw tool calls.`,
|
|
15
|
+
research: `This is a RESEARCH goal. The plan MUST name the deliverable (a written answer, comparison, or report), the source standards (primary sources over aggregators; cite what was actually read), and completeness criteria (which questions must be answered for the deliverable to count as done).`,
|
|
16
|
+
general: `This is a GENERAL task goal. Anchor acceptance criteria on observable outcomes (an artifact exists, a state changed, a question is answered with evidence) — never on effort spent.`,
|
|
17
|
+
};
|
|
18
|
+
export function plannerPrompt(objective, kind) {
|
|
19
|
+
return `You are a goal planner. Convert the objective below into a frozen plan that a
|
|
20
|
+
separate implementer agent will execute and a skeptical verifier panel will audit.
|
|
21
|
+
Downstream readers are machines, some on small models — be structured and unambiguous.
|
|
22
|
+
|
|
23
|
+
<objective>
|
|
24
|
+
${objective}
|
|
25
|
+
</objective>
|
|
26
|
+
|
|
27
|
+
${KIND_GUIDANCE[kind]}
|
|
28
|
+
|
|
29
|
+
Rules:
|
|
30
|
+
- Specify OUTCOMES, not methods. Do not prescribe which tools to call, in what
|
|
31
|
+
order, or how to structure intermediate work — freezing the HOW lets a verifier
|
|
32
|
+
wrongly refute correct work that took a different path.
|
|
33
|
+
- Write 3-5 ACCEPTANCE CRITERIA by GROUPING requirements, never one criterion per
|
|
34
|
+
detail and never an exhaustive conjunction. Satisficing beats completionism.
|
|
35
|
+
- If the objective references something with an established definition (a named
|
|
36
|
+
protocol, market mechanism, or convention), state the defining facts the
|
|
37
|
+
implementer must honor rather than assuming it knows them.
|
|
38
|
+
- Include a VERIFICATION PLAN: how the implementer should demonstrate each
|
|
39
|
+
criterion with evidence a skeptic can audit (commands run, data captured,
|
|
40
|
+
sources cited).
|
|
41
|
+
- Include NON-GOALS: what is explicitly out of scope, so the verifier cannot
|
|
42
|
+
invent requirements.
|
|
43
|
+
|
|
44
|
+
Output EXACTLY this structure (markdown):
|
|
45
|
+
|
|
46
|
+
# Goal Plan
|
|
47
|
+
## Objective
|
|
48
|
+
(one sentence restatement)
|
|
49
|
+
## Kind
|
|
50
|
+
${kind}
|
|
51
|
+
## Acceptance criteria
|
|
52
|
+
1. ...
|
|
53
|
+
## Verification plan
|
|
54
|
+
- ...
|
|
55
|
+
## Task checklist
|
|
56
|
+
- [ ] ...
|
|
57
|
+
## Non-goals
|
|
58
|
+
- ...
|
|
59
|
+
|
|
60
|
+
End your response with the plan only — no commentary after it.`;
|
|
61
|
+
}
|
|
62
|
+
// ─── Continuation directive (injected each turn while a goal is active) ────
|
|
63
|
+
export function taskDisciplineBlock() {
|
|
64
|
+
return `<task_discipline>
|
|
65
|
+
Four failure modes to avoid:
|
|
66
|
+
1. Narration without action: past-tense prose describing an action counts for
|
|
67
|
+
nothing unless the actual tool call happened. Call the tool, then narrate.
|
|
68
|
+
2. Do not ask permission to continue in-flight work. Only surface questions
|
|
69
|
+
that genuinely require a user decision.
|
|
70
|
+
3. The task checklist is your scratchpad, not the deliverable. Flip items to
|
|
71
|
+
[x] as you finish them; record real deviations in a "## Deviations" note.
|
|
72
|
+
4. Do not stop with easy work undone — the goal loop re-engages you until
|
|
73
|
+
verification passes anyway, so finishing now is strictly cheaper.
|
|
74
|
+
NO EVIDENCE THEATER: verification will audit what you actually did. Captured
|
|
75
|
+
outputs, real data, and cited sources count; claims do not.
|
|
76
|
+
</task_discipline>`;
|
|
77
|
+
}
|
|
78
|
+
/** Spend shown as coarse buckets so the directive stays prompt-cache-friendly. */
|
|
79
|
+
export function spendBucket(spentUsd, maxUsd) {
|
|
80
|
+
if (!maxUsd || maxUsd <= 0) {
|
|
81
|
+
if (spentUsd < 0.5)
|
|
82
|
+
return 'under $0.50';
|
|
83
|
+
if (spentUsd < 2)
|
|
84
|
+
return 'under $2';
|
|
85
|
+
if (spentUsd < 10)
|
|
86
|
+
return 'under $10';
|
|
87
|
+
return 'over $10';
|
|
88
|
+
}
|
|
89
|
+
const pct = (spentUsd / maxUsd) * 100;
|
|
90
|
+
if (pct < 25)
|
|
91
|
+
return 'under 25% of budget';
|
|
92
|
+
if (pct < 50)
|
|
93
|
+
return '25-50% of budget';
|
|
94
|
+
if (pct < 75)
|
|
95
|
+
return '50-75% of budget';
|
|
96
|
+
if (pct < 100)
|
|
97
|
+
return '75-100% of budget — wrap up';
|
|
98
|
+
return 'BUDGET EXHAUSTED';
|
|
99
|
+
}
|
|
100
|
+
export function continuationDirective(goal, planMd, nextStep) {
|
|
101
|
+
const gaps = goal.verifierGaps.length
|
|
102
|
+
? `\nOpen verification gaps (address these FIRST):\n${goal.verifierGaps.map(g => `- ${g}`).join('\n')}`
|
|
103
|
+
: '';
|
|
104
|
+
const strategist = goal.strategistNote
|
|
105
|
+
? `\nStrategist recommendation (a structural change — apply it rather than patching symptoms):\n${goal.strategistNote}`
|
|
106
|
+
: '';
|
|
107
|
+
const next = nextStep ? `\nNext step: ${nextStep}` : '';
|
|
108
|
+
return `<goal-state>
|
|
109
|
+
Active goal (${goal.kind}): ${goal.objective}
|
|
110
|
+
Status: ${goal.status} · verification rounds: ${goal.rounds.length} · spend: ${spendBucket(goal.budget.spentUsd, goal.budget.maxUsd)}
|
|
111
|
+
${gaps}${strategist}${next}
|
|
112
|
+
</goal-state>
|
|
113
|
+
|
|
114
|
+
<goal-plan>
|
|
115
|
+
${planMd}
|
|
116
|
+
</goal-plan>
|
|
117
|
+
|
|
118
|
+
Work the plan's task checklist in order. Run the plan's Verification plan yourself
|
|
119
|
+
BEFORE claiming completion. When (and only when) every acceptance criterion is
|
|
120
|
+
demonstrably met, call UpdateGoal with completed: true. If genuinely blocked on a
|
|
121
|
+
user decision, call UpdateGoal with blocked_reason.
|
|
122
|
+
|
|
123
|
+
${taskDisciplineBlock()}`;
|
|
124
|
+
}
|
|
125
|
+
// ─── Verifier (adversarial skeptic) ────────────────────────────────────────
|
|
126
|
+
export function verifierPrompt(goal, planMd, claimMessage, lens) {
|
|
127
|
+
return `You are an adversarial verifier. An implementer agent claims the goal below is
|
|
128
|
+
complete. Your JOB is to REFUTE the claim. If you are uncertain whether a
|
|
129
|
+
criterion is met, the verdict is refuted — a false pass that ships broken work
|
|
130
|
+
costs far more than one more iteration.
|
|
131
|
+
|
|
132
|
+
Your assigned lens: ${lens}.
|
|
133
|
+
|
|
134
|
+
<goal-plan>
|
|
135
|
+
${planMd}
|
|
136
|
+
</goal-plan>
|
|
137
|
+
|
|
138
|
+
<completion-claim>
|
|
139
|
+
${claimMessage || '(no message attached to the claim)'}
|
|
140
|
+
</completion-claim>
|
|
141
|
+
|
|
142
|
+
Audit doctrine:
|
|
143
|
+
- AUDIT, DON'T AUTHOR: examine the evidence the implementer produced (files,
|
|
144
|
+
captured outputs, cited sources, recorded data) with your read-only tools.
|
|
145
|
+
Minimize tool calls; do not redo the work.
|
|
146
|
+
- EVIDENCE HONESTY: hardcoded expected values, self-referential claims, sources
|
|
147
|
+
that were never actually read, or "verified" without captured output prove
|
|
148
|
+
nothing. But controlling an environment boundary (fixed clock, pinned data
|
|
149
|
+
snapshot) to make real behavior observable is honest evidence.
|
|
150
|
+
- ANTI-RATCHET: judge ONLY against the plan's acceptance criteria and non-goals.
|
|
151
|
+
Do not raise requirements the plan does not contain — missing edge cases,
|
|
152
|
+
stylistic preferences, and scope beyond the criteria are NOT grounds to refute.
|
|
153
|
+
On re-review rounds the bar must not rise; a fresh nitpick each round is the
|
|
154
|
+
failure mode that makes goals unfinishable.
|
|
155
|
+
- Classify a refute: blocking "none" = implementer can fix it; "contradiction" =
|
|
156
|
+
the objective precludes itself; "unverifiable" = the required evidence cannot
|
|
157
|
+
exist in this environment. The latter two escalate to the user, not to retry.
|
|
158
|
+
|
|
159
|
+
Respond with EXACTLY one JSON object on the final line of your response:
|
|
160
|
+
{"refuted": true|false, "findings": ["specific actionable gap", ...], "confidence": "low|medium|high", "blocking": "none|contradiction|unverifiable"}
|
|
161
|
+
Findings must be empty when refuted is false.`;
|
|
162
|
+
}
|
|
163
|
+
export const VERIFIER_LENSES = [
|
|
164
|
+
'criteria coverage — is every acceptance criterion demonstrably met with real evidence',
|
|
165
|
+
'evidence honesty — does the claimed evidence actually support the claims, or is it theater',
|
|
166
|
+
'reproducibility — would the demonstrated outcome hold if checked again right now',
|
|
167
|
+
];
|
|
168
|
+
// ─── Strategist ────────────────────────────────────────────────────────────
|
|
169
|
+
export function strategistPrompt(goal, planMd) {
|
|
170
|
+
const gapHistory = goal.rounds
|
|
171
|
+
.map(r => `Round ${r.round}: ${r.refuted ? 'REFUTED' : 'passed'} — ${r.gaps.join('; ') || 'no gaps'}`)
|
|
172
|
+
.join('\n');
|
|
173
|
+
return `You are a strategist. An implementer keeps failing verification on the goal
|
|
174
|
+
below, with a DIFFERENT gap surfacing each round (whack-a-mole) — patching
|
|
175
|
+
symptoms is not converging. Diagnose the STRUCTURAL root cause and recommend ONE
|
|
176
|
+
concrete structural change to HOW the work is being approached.
|
|
177
|
+
|
|
178
|
+
Hard limits: you may not change the objective or the acceptance criteria (WHAT is
|
|
179
|
+
frozen; only HOW may change). Recommend exactly one change, not a list.
|
|
180
|
+
|
|
181
|
+
<goal-plan>
|
|
182
|
+
${planMd}
|
|
183
|
+
</goal-plan>
|
|
184
|
+
|
|
185
|
+
<verification-history>
|
|
186
|
+
${gapHistory}
|
|
187
|
+
</verification-history>
|
|
188
|
+
|
|
189
|
+
Respond in at most 120 words:
|
|
190
|
+
Diagnosis: (the structural cause)
|
|
191
|
+
Restructure: (the one change)
|
|
192
|
+
Why this converges: (one sentence)`;
|
|
193
|
+
}
|
|
194
|
+
// ─── Summarizer ────────────────────────────────────────────────────────────
|
|
195
|
+
export function summarizerPrompt(goal, planMd) {
|
|
196
|
+
return `A goal just passed verification. Write the single closing message the user will
|
|
197
|
+
read. At most 80 words and 4 bullet points total: WHAT was delivered, and HOW to
|
|
198
|
+
use or see it (exact command, file, or position to look at). No process
|
|
199
|
+
narration, no praise, no caveats already covered by the plan's non-goals.
|
|
200
|
+
|
|
201
|
+
<goal-plan>
|
|
202
|
+
${planMd}
|
|
203
|
+
</goal-plan>
|
|
204
|
+
|
|
205
|
+
Objective: ${goal.objective}`;
|
|
206
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal runtime — bridges the UpdateGoal capability (constructed at module
|
|
3
|
+
* load, before any session exists) to the session's model client and
|
|
4
|
+
* capability set, and processes completion claims through the verifier
|
|
5
|
+
* panel. The loop installs the dependencies at session start.
|
|
6
|
+
*/
|
|
7
|
+
import type { ModelClient } from '../agent/llm.js';
|
|
8
|
+
import type { CapabilityHandler, CapabilityResult, ExecutionScope } from '../agent/types.js';
|
|
9
|
+
export interface GoalEngineDeps {
|
|
10
|
+
client: ModelClient;
|
|
11
|
+
getModel: () => string;
|
|
12
|
+
capabilities: CapabilityHandler[];
|
|
13
|
+
}
|
|
14
|
+
export declare function setGoalEngineDeps(d: GoalEngineDeps | null): void;
|
|
15
|
+
export interface GoalClaimInput {
|
|
16
|
+
completed?: boolean;
|
|
17
|
+
blocked_reason?: string;
|
|
18
|
+
message?: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function processGoalClaim(input: GoalClaimInput, scope: ExecutionScope): Promise<CapabilityResult>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal runtime — bridges the UpdateGoal capability (constructed at module
|
|
3
|
+
* load, before any session exists) to the session's model client and
|
|
4
|
+
* capability set, and processes completion claims through the verifier
|
|
5
|
+
* panel. The loop installs the dependencies at session start.
|
|
6
|
+
*/
|
|
7
|
+
import { getActiveGoal, loadPlan, saveVerdicts, updateActiveGoal, } from './store.js';
|
|
8
|
+
import { needsStrategist, runStrategist, runSummarizer, runVerifierPanel, } from './engine.js';
|
|
9
|
+
import { goalMaxRounds } from './types.js';
|
|
10
|
+
let deps = null;
|
|
11
|
+
export function setGoalEngineDeps(d) {
|
|
12
|
+
deps = d;
|
|
13
|
+
}
|
|
14
|
+
function engineContext(scope) {
|
|
15
|
+
if (!deps)
|
|
16
|
+
return null;
|
|
17
|
+
return {
|
|
18
|
+
client: deps.client,
|
|
19
|
+
model: deps.getModel(),
|
|
20
|
+
capabilities: deps.capabilities,
|
|
21
|
+
workingDir: scope.workingDir,
|
|
22
|
+
signal: scope.abortSignal,
|
|
23
|
+
onProgress: scope.onProgress,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export async function processGoalClaim(input, scope) {
|
|
27
|
+
const goal = getActiveGoal();
|
|
28
|
+
if (!goal) {
|
|
29
|
+
return { output: 'No active goal. Start one with the /goal command.', isError: true };
|
|
30
|
+
}
|
|
31
|
+
if (input.blocked_reason) {
|
|
32
|
+
updateActiveGoal({ status: 'blocked', blockedReason: String(input.blocked_reason) });
|
|
33
|
+
return {
|
|
34
|
+
output: `Goal marked blocked: ${input.blocked_reason}. Explain the blocker to the user and ` +
|
|
35
|
+
'what decision you need from them. The goal resumes with /goal resume.',
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
if (!input.completed) {
|
|
39
|
+
// Progress note — recorded, no verification.
|
|
40
|
+
return {
|
|
41
|
+
output: `Progress noted${input.message ? `: ${String(input.message).slice(0, 200)}` : ''}. Keep working the plan.`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const ctx = engineContext(scope);
|
|
45
|
+
if (!ctx) {
|
|
46
|
+
return { output: 'Goal engine is not initialized in this session.', isError: true };
|
|
47
|
+
}
|
|
48
|
+
const round = goal.rounds.length + 1;
|
|
49
|
+
if (round > goalMaxRounds()) {
|
|
50
|
+
updateActiveGoal({
|
|
51
|
+
status: 'blocked',
|
|
52
|
+
blockedReason: `verification round cap (${goalMaxRounds()}) reached`,
|
|
53
|
+
});
|
|
54
|
+
return {
|
|
55
|
+
output: `Verification round cap reached (${goalMaxRounds()} rounds). The goal is now blocked — ` +
|
|
56
|
+
'summarize for the user what passed, what kept failing, and ask how they want to proceed.',
|
|
57
|
+
isError: true,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
updateActiveGoal({ status: 'verifying' });
|
|
61
|
+
const planMd = loadPlan(goal.id);
|
|
62
|
+
const outcome = await runVerifierPanel(ctx, goal, planMd, String(input.message ?? ''));
|
|
63
|
+
saveVerdicts(goal.id, round, outcome.verdicts);
|
|
64
|
+
const rounds = [...goal.rounds, { round, refuted: outcome.refuted, gaps: outcome.gaps, at: Date.now() }];
|
|
65
|
+
if (!outcome.refuted) {
|
|
66
|
+
let summary = '';
|
|
67
|
+
try {
|
|
68
|
+
summary = await runSummarizer(ctx, { ...goal, rounds }, planMd);
|
|
69
|
+
}
|
|
70
|
+
catch { /* summary is best-effort */ }
|
|
71
|
+
updateActiveGoal({ status: 'completed', rounds, verifierGaps: [], summary });
|
|
72
|
+
return {
|
|
73
|
+
output: `GOAL VERIFIED COMPLETE (round ${round}, ${outcome.verdicts.length}-reviewer panel).\n\n` +
|
|
74
|
+
`${summary || 'Deliverable verified against every acceptance criterion.'}\n\n` +
|
|
75
|
+
'Relay this closing summary to the user verbatim, then stop working the goal.',
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
if (outcome.blocking !== 'none') {
|
|
79
|
+
updateActiveGoal({
|
|
80
|
+
status: 'blocked',
|
|
81
|
+
rounds,
|
|
82
|
+
verifierGaps: outcome.gaps,
|
|
83
|
+
blockedReason: `verifiers judged the goal ${outcome.blocking}`,
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
output: `Completion claim REFUTED as ${outcome.blocking.toUpperCase()} — this is not fixable by more work.\n` +
|
|
87
|
+
`Findings:\n${outcome.gaps.map(g => `- ${g}`).join('\n')}\n\n` +
|
|
88
|
+
'Escalate to the user: explain the contradiction/unverifiable evidence and ask for a decision.',
|
|
89
|
+
isError: true,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
const updated = updateActiveGoal({ status: 'active', rounds, verifierGaps: outcome.gaps });
|
|
93
|
+
let strategistLine = '';
|
|
94
|
+
if (updated && needsStrategist(updated)) {
|
|
95
|
+
try {
|
|
96
|
+
const note = await runStrategist(ctx, updated, planMd);
|
|
97
|
+
updateActiveGoal({ strategistNote: note });
|
|
98
|
+
strategistLine = `\n\nStrategist intervention (structural — apply this rather than patching symptoms):\n${note}`;
|
|
99
|
+
}
|
|
100
|
+
catch { /* strategist is best-effort */ }
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
output: `Completion claim REFUTED by the verifier panel (round ${round}).\n` +
|
|
104
|
+
`Gaps to close:\n${outcome.gaps.map(g => `- ${g}`).join('\n')}` +
|
|
105
|
+
strategistLine +
|
|
106
|
+
'\n\nAddress every gap, re-run the plan\'s verification yourself, then claim completion again. ' +
|
|
107
|
+
'The panel judges only against the plan\'s acceptance criteria — no new requirements will appear.',
|
|
108
|
+
isError: true,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal persistence — ~/.blockrun/goals/<id>/ holding goal.json (atomic),
|
|
3
|
+
* plan.md (frozen by the planner), and verdicts/round-N.json. Plus the
|
|
4
|
+
* process-scoped active-goal slot the loop and /goal command share.
|
|
5
|
+
*/
|
|
6
|
+
import type { GoalKind, GoalState, VerifierVerdict } from './types.js';
|
|
7
|
+
export declare function goalsDir(): string;
|
|
8
|
+
export declare function goalDir(id: string): string;
|
|
9
|
+
export declare function saveGoal(goal: GoalState): void;
|
|
10
|
+
export declare function loadGoal(id: string): GoalState | null;
|
|
11
|
+
export declare function savePlan(id: string, planMd: string): void;
|
|
12
|
+
export declare function loadPlan(id: string): string;
|
|
13
|
+
export declare function saveVerdicts(id: string, round: number, verdicts: VerifierVerdict[]): void;
|
|
14
|
+
export declare function createGoal(opts: {
|
|
15
|
+
objective: string;
|
|
16
|
+
kind: GoalKind;
|
|
17
|
+
maxUsd?: number;
|
|
18
|
+
}): GoalState;
|
|
19
|
+
export declare function setActiveGoal(goal: GoalState | null): void;
|
|
20
|
+
export declare function getActiveGoal(): GoalState | null;
|
|
21
|
+
/** Mutate + persist + keep the in-memory slot coherent. */
|
|
22
|
+
export declare function updateActiveGoal(patch: Partial<GoalState>): GoalState | null;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal persistence — ~/.blockrun/goals/<id>/ holding goal.json (atomic),
|
|
3
|
+
* plan.md (frozen by the planner), and verdicts/round-N.json. Plus the
|
|
4
|
+
* process-scoped active-goal slot the loop and /goal command share.
|
|
5
|
+
*/
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import { BLOCKRUN_DIR } from '../config.js';
|
|
10
|
+
export function goalsDir() {
|
|
11
|
+
return path.join(BLOCKRUN_DIR, 'goals');
|
|
12
|
+
}
|
|
13
|
+
export function goalDir(id) {
|
|
14
|
+
return path.join(goalsDir(), id);
|
|
15
|
+
}
|
|
16
|
+
export function saveGoal(goal) {
|
|
17
|
+
const dir = goalDir(goal.id);
|
|
18
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
19
|
+
const tmp = path.join(dir, '.goal.tmp');
|
|
20
|
+
fs.writeFileSync(tmp, JSON.stringify({ ...goal, updatedAt: Date.now() }, null, 2));
|
|
21
|
+
fs.renameSync(tmp, path.join(dir, 'goal.json'));
|
|
22
|
+
}
|
|
23
|
+
export function loadGoal(id) {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(fs.readFileSync(path.join(goalDir(id), 'goal.json'), 'utf-8'));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export function savePlan(id, planMd) {
|
|
32
|
+
fs.mkdirSync(goalDir(id), { recursive: true });
|
|
33
|
+
fs.writeFileSync(path.join(goalDir(id), 'plan.md'), planMd);
|
|
34
|
+
}
|
|
35
|
+
export function loadPlan(id) {
|
|
36
|
+
try {
|
|
37
|
+
return fs.readFileSync(path.join(goalDir(id), 'plan.md'), 'utf-8');
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return '';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function saveVerdicts(id, round, verdicts) {
|
|
44
|
+
const dir = path.join(goalDir(id), 'verdicts');
|
|
45
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
46
|
+
fs.writeFileSync(path.join(dir, `round-${round}.json`), JSON.stringify(verdicts, null, 2));
|
|
47
|
+
}
|
|
48
|
+
export function createGoal(opts) {
|
|
49
|
+
const goal = {
|
|
50
|
+
id: `g_${crypto.randomBytes(5).toString('hex')}`,
|
|
51
|
+
objective: opts.objective,
|
|
52
|
+
kind: opts.kind,
|
|
53
|
+
status: 'active',
|
|
54
|
+
createdAt: Date.now(),
|
|
55
|
+
updatedAt: Date.now(),
|
|
56
|
+
rounds: [],
|
|
57
|
+
verifierGaps: [],
|
|
58
|
+
turnsUsed: 0,
|
|
59
|
+
budget: { maxUsd: opts.maxUsd, spentUsd: 0 },
|
|
60
|
+
};
|
|
61
|
+
saveGoal(goal);
|
|
62
|
+
return goal;
|
|
63
|
+
}
|
|
64
|
+
// ─── Active-goal slot (process-scoped, one per session) ────────────────────
|
|
65
|
+
let activeGoal = null;
|
|
66
|
+
export function setActiveGoal(goal) {
|
|
67
|
+
activeGoal = goal;
|
|
68
|
+
}
|
|
69
|
+
export function getActiveGoal() {
|
|
70
|
+
return activeGoal;
|
|
71
|
+
}
|
|
72
|
+
/** Mutate + persist + keep the in-memory slot coherent. */
|
|
73
|
+
export function updateActiveGoal(patch) {
|
|
74
|
+
if (!activeGoal)
|
|
75
|
+
return null;
|
|
76
|
+
activeGoal = { ...activeGoal, ...patch, updatedAt: Date.now() };
|
|
77
|
+
saveGoal(activeGoal);
|
|
78
|
+
return activeGoal;
|
|
79
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal engine — cross-turn autonomous objectives.
|
|
3
|
+
*
|
|
4
|
+
* A goal freezes an objective into a plan (outcomes, not implementation),
|
|
5
|
+
* steers the main model with per-turn directives, and gates every
|
|
6
|
+
* completion claim behind an adversarial verifier panel that defaults to
|
|
7
|
+
* refuting. The architecture is deliberately defensive: plausible-but-
|
|
8
|
+
* incomplete work must not survive verification, and verification must not
|
|
9
|
+
* ratchet (re-reviews may not raise fresh demands — see the verifier
|
|
10
|
+
* prompt), or goals become unfinishable.
|
|
11
|
+
*/
|
|
12
|
+
export type GoalKind = 'trading' | 'research' | 'general';
|
|
13
|
+
export type GoalStatus = 'active' | 'verifying' | 'paused' | 'blocked' | 'completed' | 'abandoned';
|
|
14
|
+
export interface GoalBudget {
|
|
15
|
+
/** Ceiling captured from --max-spend at creation (undefined = uncapped). */
|
|
16
|
+
maxUsd?: number;
|
|
17
|
+
/** Cumulative USD spent on this goal across sessions. */
|
|
18
|
+
spentUsd: number;
|
|
19
|
+
}
|
|
20
|
+
export interface GoalRoundRecord {
|
|
21
|
+
round: number;
|
|
22
|
+
refuted: boolean;
|
|
23
|
+
gaps: string[];
|
|
24
|
+
at: number;
|
|
25
|
+
}
|
|
26
|
+
export interface GoalState {
|
|
27
|
+
id: string;
|
|
28
|
+
objective: string;
|
|
29
|
+
kind: GoalKind;
|
|
30
|
+
status: GoalStatus;
|
|
31
|
+
createdAt: number;
|
|
32
|
+
updatedAt: number;
|
|
33
|
+
/** Verification rounds run so far. */
|
|
34
|
+
rounds: GoalRoundRecord[];
|
|
35
|
+
/** Latest verifier gaps, inlined into the next continuation directive. */
|
|
36
|
+
verifierGaps: string[];
|
|
37
|
+
/** One structural recommendation from the strategist, if it ran. */
|
|
38
|
+
strategistNote?: string;
|
|
39
|
+
/** Implementer turns consumed (continuation bound). */
|
|
40
|
+
turnsUsed: number;
|
|
41
|
+
budget: GoalBudget;
|
|
42
|
+
blockedReason?: string;
|
|
43
|
+
/** Closing user-facing summary, once completed. */
|
|
44
|
+
summary?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface VerifierVerdict {
|
|
47
|
+
refuted: boolean;
|
|
48
|
+
/** Concrete, actionable gaps (empty when not refuted). */
|
|
49
|
+
findings: string[];
|
|
50
|
+
confidence: 'low' | 'medium' | 'high';
|
|
51
|
+
/**
|
|
52
|
+
* none — implementer-fixable, iterate
|
|
53
|
+
* contradiction — the objective precludes itself; user must decide
|
|
54
|
+
* unverifiable — the needed evidence cannot exist here; user must decide
|
|
55
|
+
*/
|
|
56
|
+
blocking: 'none' | 'contradiction' | 'unverifiable';
|
|
57
|
+
}
|
|
58
|
+
export declare const GOAL_MAX_ROUNDS_DEFAULT = 5;
|
|
59
|
+
export declare const GOAL_MAX_TURNS_DEFAULT = 25;
|
|
60
|
+
export declare const GOAL_VERIFIERS_DEFAULT = 3;
|
|
61
|
+
export declare function goalMaxRounds(): number;
|
|
62
|
+
export declare function goalMaxTurns(): number;
|
|
63
|
+
export declare function goalVerifierCount(): number;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Goal engine — cross-turn autonomous objectives.
|
|
3
|
+
*
|
|
4
|
+
* A goal freezes an objective into a plan (outcomes, not implementation),
|
|
5
|
+
* steers the main model with per-turn directives, and gates every
|
|
6
|
+
* completion claim behind an adversarial verifier panel that defaults to
|
|
7
|
+
* refuting. The architecture is deliberately defensive: plausible-but-
|
|
8
|
+
* incomplete work must not survive verification, and verification must not
|
|
9
|
+
* ratchet (re-reviews may not raise fresh demands — see the verifier
|
|
10
|
+
* prompt), or goals become unfinishable.
|
|
11
|
+
*/
|
|
12
|
+
export const GOAL_MAX_ROUNDS_DEFAULT = 5;
|
|
13
|
+
export const GOAL_MAX_TURNS_DEFAULT = 25;
|
|
14
|
+
export const GOAL_VERIFIERS_DEFAULT = 3;
|
|
15
|
+
export function goalMaxRounds() {
|
|
16
|
+
const n = Number(process.env.FRANKLIN_GOAL_MAX_ROUNDS);
|
|
17
|
+
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : GOAL_MAX_ROUNDS_DEFAULT;
|
|
18
|
+
}
|
|
19
|
+
export function goalMaxTurns() {
|
|
20
|
+
const n = Number(process.env.FRANKLIN_GOAL_MAX_TURNS);
|
|
21
|
+
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : GOAL_MAX_TURNS_DEFAULT;
|
|
22
|
+
}
|
|
23
|
+
export function goalVerifierCount() {
|
|
24
|
+
const n = Number(process.env.FRANKLIN_GOAL_VERIFIERS);
|
|
25
|
+
return Number.isFinite(n) && n >= 1 ? Math.min(5, Math.floor(n)) : GOAL_VERIFIERS_DEFAULT;
|
|
26
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook discovery and validation.
|
|
3
|
+
*
|
|
4
|
+
* Sources, in load order:
|
|
5
|
+
* 1. ~/.blockrun/hooks/*.json — user scope, always trusted
|
|
6
|
+
* 2. <project>/.franklin/hooks/*.json — project scope, loads ONLY when the
|
|
7
|
+
* project dir is trusted (same trusted-projects.json marker that gates
|
|
8
|
+
* project .mcp.json — one mental model for "this repo may run code").
|
|
9
|
+
*
|
|
10
|
+
* Malformed files or entries warn once and are skipped; unknown event names
|
|
11
|
+
* are ignored so config files can carry events from other harnesses or
|
|
12
|
+
* future versions without breaking.
|
|
13
|
+
*/
|
|
14
|
+
import { type LoadedHook } from './types.js';
|
|
15
|
+
export declare function userHooksDir(): string;
|
|
16
|
+
export declare function projectHooksDir(workDir: string): string;
|
|
17
|
+
/** Same trust marker that gates project .mcp.json (see src/mcp/config.ts). */
|
|
18
|
+
export declare function isProjectTrusted(workDir: string): boolean;
|
|
19
|
+
export declare function loadHooks(workDir: string): LoadedHook[];
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook discovery and validation.
|
|
3
|
+
*
|
|
4
|
+
* Sources, in load order:
|
|
5
|
+
* 1. ~/.blockrun/hooks/*.json — user scope, always trusted
|
|
6
|
+
* 2. <project>/.franklin/hooks/*.json — project scope, loads ONLY when the
|
|
7
|
+
* project dir is trusted (same trusted-projects.json marker that gates
|
|
8
|
+
* project .mcp.json — one mental model for "this repo may run code").
|
|
9
|
+
*
|
|
10
|
+
* Malformed files or entries warn once and are skipped; unknown event names
|
|
11
|
+
* are ignored so config files can carry events from other harnesses or
|
|
12
|
+
* future versions without breaking.
|
|
13
|
+
*/
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { BLOCKRUN_DIR } from '../config.js';
|
|
17
|
+
import { logger } from '../logger.js';
|
|
18
|
+
import { HOOK_EVENTS, LIFECYCLE_EVENTS, } from './types.js';
|
|
19
|
+
export function userHooksDir() {
|
|
20
|
+
return path.join(BLOCKRUN_DIR, 'hooks');
|
|
21
|
+
}
|
|
22
|
+
export function projectHooksDir(workDir) {
|
|
23
|
+
return path.join(workDir, '.franklin', 'hooks');
|
|
24
|
+
}
|
|
25
|
+
/** Same trust marker that gates project .mcp.json (see src/mcp/config.ts). */
|
|
26
|
+
export function isProjectTrusted(workDir) {
|
|
27
|
+
const trustMarker = path.join(BLOCKRUN_DIR, 'trusted-projects.json');
|
|
28
|
+
try {
|
|
29
|
+
if (fs.existsSync(trustMarker)) {
|
|
30
|
+
const trustedDirs = JSON.parse(fs.readFileSync(trustMarker, 'utf-8'));
|
|
31
|
+
return Array.isArray(trustedDirs) && trustedDirs.includes(workDir);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
/* unreadable marker = not trusted */
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
export function loadHooks(workDir) {
|
|
40
|
+
const loaded = [];
|
|
41
|
+
collectDir(userHooksDir(), 'user', loaded);
|
|
42
|
+
const projDir = projectHooksDir(workDir);
|
|
43
|
+
if (fs.existsSync(projDir)) {
|
|
44
|
+
if (isProjectTrusted(workDir)) {
|
|
45
|
+
collectDir(projDir, 'project', loaded);
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
logger.info(`[hooks] Skipping untrusted project hooks in ${projDir} — run /mcp trust to enable`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return loaded;
|
|
52
|
+
}
|
|
53
|
+
function collectDir(dir, scope, out) {
|
|
54
|
+
let entries;
|
|
55
|
+
try {
|
|
56
|
+
entries = fs.readdirSync(dir).filter(f => f.endsWith('.json')).sort();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return; // dir missing — nothing to load
|
|
60
|
+
}
|
|
61
|
+
for (const file of entries) {
|
|
62
|
+
const sourceFile = path.join(dir, file);
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = JSON.parse(fs.readFileSync(sourceFile, 'utf-8'));
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
logger.warn(`[hooks] Skipping malformed hook file ${sourceFile}: ${err.message}`);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (!parsed || typeof parsed.hooks !== 'object' || parsed.hooks === null) {
|
|
72
|
+
logger.warn(`[hooks] Skipping ${sourceFile}: missing top-level "hooks" object`);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
for (const [eventName, matchers] of Object.entries(parsed.hooks)) {
|
|
76
|
+
if (!HOOK_EVENTS.has(eventName))
|
|
77
|
+
continue; // foreign/future event — ignore
|
|
78
|
+
const event = eventName;
|
|
79
|
+
if (!Array.isArray(matchers)) {
|
|
80
|
+
logger.warn(`[hooks] ${sourceFile}: "${eventName}" must be an array — skipped`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
for (const entry of matchers) {
|
|
84
|
+
collectMatcherEntry(entry, event, sourceFile, scope, out);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function collectMatcherEntry(entry, event, sourceFile, scope, out) {
|
|
90
|
+
if (!entry || !Array.isArray(entry.hooks)) {
|
|
91
|
+
logger.warn(`[hooks] ${sourceFile}: entry for ${event} lacks a "hooks" array — skipped`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
let matcher;
|
|
95
|
+
if (typeof entry.matcher === 'string' && entry.matcher.length > 0) {
|
|
96
|
+
if (LIFECYCLE_EVENTS.has(event)) {
|
|
97
|
+
logger.warn(`[hooks] ${sourceFile}: ${event} carries no tool context — matcher "${entry.matcher}" rejected, entry skipped`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
matcher = new RegExp(entry.matcher);
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
logger.warn(`[hooks] ${sourceFile}: invalid matcher regex "${entry.matcher}" for ${event}: ${err.message} — entry skipped`);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (const handler of entry.hooks) {
|
|
109
|
+
if (!handler || handler.type !== 'command' || typeof handler.command !== 'string' || !handler.command.trim()) {
|
|
110
|
+
logger.warn(`[hooks] ${sourceFile}: handler for ${event} must be {type:"command", command:"..."} — skipped`);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
out.push({ event, matcher, handler, sourceFile, scope });
|
|
114
|
+
}
|
|
115
|
+
}
|