Skip to content

Commit 109e1af

Browse files
sepo-engopencodeclaude
authored
fix(opencode): wire monitor/goal/ledger/history into the legacy tool registry (#46)
* fix(opencode): wire monitor/goal/ledger/history into the legacy tool registry Sean's live instance had no monitor tool despite TKT-322 registering it in core's V2 BuiltInTools.node. Root cause: two independent tool registries and session runners coexist in this fork. packages/core/src/tool/registry.ts's ToolRegistry.materialize() (which DOES include monitor/goal/ledger/history) is consumed only by packages/core/src/session/runner/llm.ts's runTurn, which has zero callers anywhere in the codebase. The actual live serving path (session/processor.ts -> session/llm.ts -> session/tools.ts) calls a separate, hand-maintained legacy registry that predates all four V2 tool families. This wires the four missing tool families into the legacy registry as thin V1 bridges delegating to the same core services the V2 tools already use -- mirroring the existing question/skill wiring pattern. It does not retire the dual-registry architecture or wire/delete the dead runTurn; that is filed as its own follow-up ticket per Ethan's ruling, since it intersects the carry-ruling class and needs a design pass rather than a war-footing patch. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M1CJmqai46ihahdKMVNB27 * test(opencode): drive SessionTools.resolve's real wire output, not just the registry listing Henry's review on #46, upgraded to required by Ethan: the endpoint-based test proves the registry OFFERS monitor/goal/ledger/history, but neither endpoint passes a real agent+session permission ruleset, so green there doesn't mean "a fresh session HAS them" the way Sean's re-test will read it. Adds a test running a genuinely fresh session (no permission override) with the real default "build" agent through the actual prompt.loop(), asserting on the literal tools array the fake LLM provider received on the wire -- the same artifact a real model would see, not a registry listing. Delete- the-fix verified (removed ledger_add from the registry, test failed naming that exact tool absent from the wire payload, restored). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M1CJmqai46ihahdKMVNB27 * fix(opencode): reconcile Copilot review on #46 - httpapi-experimental.test.ts: widen the parsed toolList type to include description, so a contract drift (description disappearing from the API) fails typecheck instead of silently compiling. - history.ts: history_get now serializes {entries} matching the V2 tool's output shape, instead of the bare array. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M1CJmqai46ihahdKMVNB27 * fix(opencode): align V1 bridge tool output envelopes with the V2 Output schema Five one-line fixes (Henry's review, Ethan's ruling): each bridge's output was a bare value (Info/array) instead of the V2 tool's own {monitor}/ {monitors}/{goal}/{entry} envelope -- the same works-in-one-registry-not- the-other class this PR exists to close. goal_get's no-goal case also stopped emitting an English sentence in place of JSON, matching the V2 tool's always-structured {goal: Info | undefined} shape. monitor_create: {monitor: info} monitor_list: {monitors} goal_get: {goal: current} in both branches goal_update_progress: {goal: updated} ledger_add: {entry} No test churn (no existing test asserted on output content). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M1CJmqai46ihahdKMVNB27 * docs(opencode): correct a fabricated feedback citation on #46 Cited "feedback anomalyco#205" in the PR body, FORK.md, and monitor.ts's comment without checking the feedback queue. anomalyco#205 is a real, unrelated item (the system-prompt WebFetch docs URL). This incident was relayed live via Ethan, never filed as feedback -- corrected in all three places, plus the PR body on GitHub directly. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M1CJmqai46ihahdKMVNB27 * docs(opencode): fix the remaining fabricated feedback anomalyco#205 citation Henry caught a survivor of the prior citation fix -- prompt.test.ts's own comment still cited feedback anomalyco#205, a real but unrelated queue item. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01M1CJmqai46ihahdKMVNB27 --------- Co-authored-by: opencode <[email protected]> Co-authored-by: Claude Sonnet 5 <[email protected]>
1 parent f8e3bf3 commit 109e1af

8 files changed

Lines changed: 433 additions & 0 deletions

File tree

‎FORK.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ retires it without reading every PR.
7878

7979
| CI `typecheck` job: `package.json`'s `typecheck` script, `bun turbo typecheck` → `bun turbo typecheck --concurrency=2` | War-footing fix (Sean-directed, Ethan): the self-hosted runner OOM'd — 9 concurrent `tsgo --noEmit` at ~1.7GiB each (15.6GiB, 28.6% of host resident memory), turbo's default concurrency (10, uncapped by task or CLI flag) fanning out unbounded across all 32 typecheck-bearing packages with no interdependencies gating them. Measured locally (`ps -C tsgo`, exact-comm match, not a broader cmdline grep that double-counts wrapper processes): uncapped peak was ~23 concurrent processes / ~14GB RSS; `--concurrency=2` holds peak to exactly 2 concurrent `tsgo` processes / ~5.6GB, inside the ~4-6GiB target. Wall-clock cost: ~18s → ~20s locally on a fresh (non-cached) run — a small, worthwhile trade for not killing the shared host | Not a code bug, a resource-scheduling gap between the monorepo's package count and the runner's memory budget | n/a — fork-infra CI config only | none | none | **keep** — this runner's memory budget is fixed and shared with other fleets' concurrent jobs (see "CI runner reality" below); revisit only if the runner's own memory budget changes or `tsgo`'s per-process footprint drops |
8080

81+
| V1 bridge for the V2-only builtin tools: `packages/opencode/src/tool/{monitor,goal,ledger,history}.ts` (new) register `monitor_create`/`monitor_list`, `goal_get`/`goal_update_progress`, `ledger_add`, `history_search`/`history_get` into `packages/opencode/src/tool/registry.ts`'s hand-maintained `builtin` list, mirroring the existing `question`/`skill` wiring pattern — delegating to the same core services (`Monitor.Service`, `SessionGoal.Service`, `SessionLedger.Service`, `SessionHistorySearch`) the V2 tools already use, no duplicated logic | Sean-directed war-footing fix (relayed live, not filed as feedback): asked the agent on his live instance whether it had a monitor tool and it did not. Root cause traced (not assumed): this fork has TWO independent tool registries and TWO independent session runners. `packages/core/src/tool/registry.ts`'s `ToolRegistry.materialize()` (composes `BuiltInTools.node`, which correctly includes `MonitorTool`/`GoalTool`/`LedgerTool`/`HistoryTool` since TKT-321/322/335/#10) is consumed ONLY by `packages/core/src/session/runner/llm.ts`'s `runTurn` — which has ZERO callers anywhere in the codebase, confirmed by a repo-wide grep. The actual live serving path (`packages/opencode/src/session/processor.ts` → `session/llm.ts` → `session/tools.ts:92`) calls a wholly separate, hand-maintained legacy registry (`packages/opencode/src/tool/registry.ts`) that predates all four V2 tool families and was never told about any of them. Not a permission/profile deny (`profile-builtin.ts`'s `monitorRules` gates runtime execution, not registry visibility), not a stale-session cache artifact — confirmed with a genuinely fresh session against the live instance (`ses_008ad9011ffezt0Sw3ODRnucIB`, `172.16.14.0:4633`, sha `adec6000`) before writing any code | n/a — tool-wiring gap, not a proposal | none — no schema/table changes, delegates to existing core services | none | **Deliberately not (b)**: retiring the dual registry (wiring or deleting the dead `runTurn`, migrating `session/tools.ts` onto V2 `materialize()`) is filed as its own ticket per Ethan's ruling — it intersects the carry-ruling class and needs a design pass, not a war-footing patch. This row is the minimal unblock only: it adds tool VISIBILITY on the live path, it does not change which registry is authoritative long-term |
82+
8183
`e2e` (in `test.yml`), `nix-eval.yml`, `pr-management.yml`'s `check-duplicates` job, and most of
8284
the release/publish/deploy/beta/docs/notify/storybook/triage/stats workflows are **not** in this
8385
ledger: they remain untouched and still non-functional on this fork (same `blacksmith-*` problem,

‎packages/opencode/src/tool/goal.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { Effect, Schema } from "effect"
2+
import { SessionGoal } from "@opencode-ai/core/session/goal"
3+
import * as Tool from "./tool"
4+
5+
// V1 bridge for the V2 Goal tool (packages/core/src/tool/goal.ts) -- see monitor.ts's header
6+
// for why this bridge exists. Delegates to the same SessionGoal.Service the V2 tool uses.
7+
8+
export const GetParameters = Schema.Struct({})
9+
10+
export const GoalGetTool = Tool.define(
11+
"goal_get",
12+
Effect.gen(function* () {
13+
const goal = yield* SessionGoal.Service
14+
15+
return {
16+
description:
17+
"Read the session's durable goal: objective, acceptance criteria, and constraints. This is typed state, not conversation recall -- it survives compaction. Call this instead of trusting the summary when you need the exact objective or a constraint's exact wording.",
18+
parameters: GetParameters,
19+
execute: (_params: Schema.Schema.Type<typeof GetParameters>, ctx: Tool.Context) =>
20+
Effect.gen(function* () {
21+
const current = yield* goal.get(ctx.sessionID)
22+
return {
23+
title: current ? "Session goal" : "No goal set",
24+
output: JSON.stringify({ goal: current }, null, 2),
25+
metadata: { hasGoal: !!current },
26+
}
27+
}).pipe(Effect.orDie),
28+
}
29+
}),
30+
)
31+
32+
export const UpdateProgressParameters = Schema.Struct({
33+
criterionID: SessionGoal.AcceptanceCriterion.fields.id,
34+
}).annotate({
35+
description: "Mark one acceptance criterion as met. The criterion must currently be open.",
36+
})
37+
38+
export const GoalUpdateProgressTool = Tool.define(
39+
"goal_update_progress",
40+
Effect.gen(function* () {
41+
const goal = yield* SessionGoal.Service
42+
43+
return {
44+
description:
45+
"Mark one acceptance criterion as met, once you have verified it. Cannot rewrite the objective, constraints, or waive a criterion -- those require the user.",
46+
parameters: UpdateProgressParameters,
47+
execute: (params: Schema.Schema.Type<typeof UpdateProgressParameters>, ctx: Tool.Context) =>
48+
Effect.gen(function* () {
49+
yield* ctx.ask({
50+
permission: "goal_update_progress",
51+
patterns: ["*"],
52+
always: ["*"],
53+
metadata: { criterionID: params.criterionID },
54+
})
55+
const current = yield* goal.get(ctx.sessionID)
56+
if (!current) throw new Error("No goal is set for this session.")
57+
const target = current.acceptanceCriteria.find((c) => c.id === params.criterionID)
58+
if (!target) throw new Error(`No acceptance criterion with id ${params.criterionID}.`)
59+
if (target.status !== "open") throw new Error(`Criterion ${params.criterionID} is already ${target.status}, not open.`)
60+
const updated = yield* goal
61+
.update({
62+
sessionID: ctx.sessionID,
63+
objective: current.objective,
64+
acceptanceCriteria: current.acceptanceCriteria.map((c) =>
65+
c.id === params.criterionID ? { ...c, status: "met" as const } : c,
66+
),
67+
constraints: current.constraints,
68+
sourceMessageIDs: current.sourceMessageIDs,
69+
expectedVersion: current.version,
70+
})
71+
.pipe(
72+
Effect.catchTag("SessionGoal.Conflict", () =>
73+
Effect.die(new Error("The goal changed concurrently. Re-read it with goal_get and retry.")),
74+
),
75+
)
76+
return {
77+
title: `Criterion ${params.criterionID} marked met`,
78+
output: JSON.stringify({ goal: updated }, null, 2),
79+
metadata: { criterionID: params.criterionID },
80+
}
81+
}).pipe(Effect.orDie),
82+
}
83+
}),
84+
)
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { Effect, Schema } from "effect"
2+
import { Database } from "@opencode-ai/core/database/database"
3+
import { SessionHistorySearch } from "@opencode-ai/core/session/history-search"
4+
import { SessionMessage } from "@opencode-ai/core/session/message"
5+
import * as Tool from "./tool"
6+
7+
// V1 bridge for the V2 History tools (packages/core/src/tool/history.ts) -- see monitor.ts's
8+
// header for why this bridge exists. Delegates to the same SessionHistorySearch functions the
9+
// V2 tool uses; read-only, no permission ask (matches the V2 tool).
10+
11+
export const SearchParameters = Schema.Struct({
12+
query: Schema.String,
13+
limit: Schema.Int.pipe(Schema.optional),
14+
}).annotate({
15+
description:
16+
"Search this session's full history, including content a compaction already summarized away. Returns bounded snippets with the source message ID -- call history_get on a result to read the full message. Use this whenever the user references something specific you don't currently see in context -- it may have been summarized away rather than never discussed.",
17+
})
18+
19+
export const HistorySearchTool = Tool.define(
20+
"history_search",
21+
Effect.gen(function* () {
22+
const { db } = yield* Database.Service
23+
24+
return {
25+
description:
26+
"Search this session's full history for a term, including content a compaction already summarized away. Returns bounded snippets, not full messages -- call history_get on a result's messageID to read the surrounding context in full. Use this whenever the user references something specific you don't currently see in context -- it may have been summarized away rather than never discussed.",
27+
parameters: SearchParameters,
28+
execute: (params: Schema.Schema.Type<typeof SearchParameters>, ctx: Tool.Context) =>
29+
Effect.gen(function* () {
30+
const result = yield* SessionHistorySearch.search(db, {
31+
sessionID: ctx.sessionID,
32+
query: params.query,
33+
limit: params.limit,
34+
})
35+
return {
36+
title: `${result.results.length} result${result.results.length === 1 ? "" : "s"}`,
37+
output: JSON.stringify(result, null, 2),
38+
metadata: { count: result.results.length, truncated: result.truncated },
39+
}
40+
}).pipe(Effect.orDie),
41+
}
42+
}),
43+
)
44+
45+
export const GetParameters = Schema.Struct({
46+
messageID: SessionMessage.ID,
47+
before: Schema.Int.pipe(Schema.optional),
48+
after: Schema.Int.pipe(Schema.optional),
49+
}).annotate({
50+
description: `Read a bounded neighborhood of full messages around one message ID, usually one cited by history_search. Capped at ${SessionHistorySearch.MaxNeighborhood} messages before/after.`,
51+
})
52+
53+
export const HistoryGetTool = Tool.define(
54+
"history_get",
55+
Effect.gen(function* () {
56+
const { db } = yield* Database.Service
57+
58+
return {
59+
description:
60+
"Read a bounded neighborhood of full messages around one message ID -- the second half of the retrieval flow after history_search finds a candidate by snippet.",
61+
parameters: GetParameters,
62+
execute: (params: Schema.Schema.Type<typeof GetParameters>, ctx: Tool.Context) =>
63+
Effect.gen(function* () {
64+
const entries = yield* SessionHistorySearch.get(db, {
65+
sessionID: ctx.sessionID,
66+
messageID: params.messageID,
67+
before: params.before,
68+
after: params.after,
69+
})
70+
if (!entries) throw new Error(`No message ${params.messageID} in this session.`)
71+
return {
72+
title: `${entries.length} message${entries.length === 1 ? "" : "s"}`,
73+
output: JSON.stringify({ entries }, null, 2),
74+
metadata: { count: entries.length },
75+
}
76+
}).pipe(Effect.orDie),
77+
}
78+
}),
79+
)
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { Effect, Schema } from "effect"
2+
import { SessionLedger } from "@opencode-ai/core/session/ledger"
3+
import { SessionMessage } from "@opencode-ai/core/session/message"
4+
import * as Tool from "./tool"
5+
6+
// V1 bridge for the V2 Ledger tool (packages/core/src/tool/ledger.ts) -- see monitor.ts's
7+
// header for why this bridge exists. Delegates to the same SessionLedger.Service the V2 tool
8+
// uses. Adding is the model-facing mutation; superseding an entry is a user action from the
9+
// ledger panel, not exposed to the model here.
10+
11+
export const AddParameters = Schema.Struct({
12+
kind: SessionLedger.Kind,
13+
text: Schema.String,
14+
}).annotate({
15+
description:
16+
"Record one fact that must remain true while continuing this task: a decision, a discovered constraint, a finding, a risk, or a next step.",
17+
})
18+
19+
export const LedgerAddTool = Tool.define(
20+
"ledger_add",
21+
Effect.gen(function* () {
22+
const ledger = yield* SessionLedger.Service
23+
24+
return {
25+
description:
26+
"Add one entry to the session's working ledger -- a decision, constraint, fact, risk, or next step worth remembering across compaction. The ledger has a bounded budget; if it is full, supersede an existing entry first (from the ledger panel) rather than expecting this call to silently drop something.",
27+
parameters: AddParameters,
28+
execute: (params: Schema.Schema.Type<typeof AddParameters>, ctx: Tool.Context) =>
29+
Effect.gen(function* () {
30+
yield* ctx.ask({
31+
permission: "ledger_add",
32+
patterns: ["*"],
33+
always: ["*"],
34+
metadata: { kind: params.kind },
35+
})
36+
const entry = yield* ledger
37+
.add({
38+
sessionID: ctx.sessionID,
39+
kind: params.kind,
40+
text: params.text,
41+
sourceMessageIDs: [SessionMessage.ID.make(ctx.messageID)],
42+
})
43+
.pipe(
44+
Effect.catchTag("SessionLedger.CapExceededError", (error) =>
45+
Effect.die(
46+
new Error(
47+
`Ledger is at its budget (${error.activeCount} entries, ${error.activeBytes} bytes active) -- supersede an existing entry before adding another.`,
48+
),
49+
),
50+
),
51+
)
52+
return {
53+
title: "Ledger entry added",
54+
output: JSON.stringify({ entry }, null, 2),
55+
metadata: { entryID: entry.id },
56+
}
57+
}).pipe(Effect.orDie),
58+
}
59+
}),
60+
)
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { Effect, Schema } from "effect"
2+
import { Monitor as MonitorSchema } from "@opencode-ai/schema/monitor"
3+
import { Monitor } from "@opencode-ai/core/monitor"
4+
import { PositiveInt } from "@opencode-ai/core/schema"
5+
import * as Tool from "./tool"
6+
7+
// V1 bridge for the V2 Monitor tools (packages/core/src/tool/monitor.ts): the live serving
8+
// path is this legacy registry (see registry.ts's builtin list), which the V2 registration in
9+
// core/tool/builtins.ts never reaches -- Sean's own live gate walk found this directly (not
10+
// filed as feedback). Delegates to the
11+
// same Monitor.Service the V2 tool uses; no duplicated monitor logic, only the tool-shape bridge.
12+
//
13+
// Plugin sources and the plugin condition are excluded, mirroring the V2 tool: neither is
14+
// executable yet (MonitorCondition.evaluate's "plugin" case always reports not-triggered).
15+
export const CreateParameters = Schema.Struct({
16+
title: Schema.String,
17+
command: Schema.String,
18+
cwd: Schema.String.pipe(Schema.optional),
19+
intervalMs: PositiveInt,
20+
timeoutMs: PositiveInt,
21+
condition: Schema.Union([MonitorSchema.ExitCodeCondition, MonitorSchema.RegexCondition, MonitorSchema.JsonCondition]),
22+
maxAttempts: PositiveInt.pipe(Schema.optional),
23+
outputPolicy: MonitorSchema.OutputPolicy.pipe(Schema.optional),
24+
}).annotate({
25+
description:
26+
"Declare a command monitor: a shell command re-run on an interval, checked against a condition (exit code, regex, or JSON path) until it triggers or maxAttempts is reached. Runs unattended: if the command's permission is configured to ask for approval rather than allow, checks are refused (not silently skipped) until it is set to allow -- monitors cannot prompt for approval.",
27+
})
28+
29+
export const MonitorCreateTool = Tool.define(
30+
"monitor_create",
31+
Effect.gen(function* () {
32+
const monitor = yield* Monitor.Service
33+
34+
return {
35+
description:
36+
"Declare a command monitor: a shell command re-run on an interval, checked against a condition (exit code, regex, or JSON path) until it triggers or maxAttempts is reached. Runs unattended: if the command's permission is configured to ask for approval rather than allow, checks are refused (not silently skipped) until it is set to allow -- monitors cannot prompt for approval.",
37+
parameters: CreateParameters,
38+
execute: (params: Schema.Schema.Type<typeof CreateParameters>, ctx: Tool.Context) =>
39+
Effect.gen(function* () {
40+
yield* ctx.ask({
41+
permission: "monitor_create",
42+
patterns: ["*"],
43+
always: ["*"],
44+
metadata: { command: params.command },
45+
})
46+
const info = yield* monitor.create({
47+
sessionID: ctx.sessionID,
48+
title: params.title,
49+
source: { type: "command", command: params.command, cwd: params.cwd },
50+
intervalMs: params.intervalMs,
51+
timeoutMs: params.timeoutMs,
52+
condition: params.condition,
53+
maxAttempts: params.maxAttempts,
54+
outputPolicy: params.outputPolicy ?? {},
55+
})
56+
return {
57+
title: `Monitor declared: ${info.title}`,
58+
output: JSON.stringify({ monitor: info }, null, 2),
59+
metadata: { monitorID: info.id },
60+
}
61+
}).pipe(Effect.orDie),
62+
}
63+
}),
64+
)
65+
66+
export const MonitorListParameters = Schema.Struct({})
67+
68+
export const MonitorListTool = Tool.define(
69+
"monitor_list",
70+
Effect.gen(function* () {
71+
const monitor = yield* Monitor.Service
72+
73+
return {
74+
description: "List monitors declared in this session, with their current status.",
75+
parameters: MonitorListParameters,
76+
execute: (_params: Schema.Schema.Type<typeof MonitorListParameters>, ctx: Tool.Context) =>
77+
Effect.gen(function* () {
78+
const monitors = yield* monitor.list(ctx.sessionID)
79+
return {
80+
title: `${monitors.length} monitor${monitors.length === 1 ? "" : "s"}`,
81+
output: JSON.stringify({ monitors }, null, 2),
82+
metadata: { count: monitors.length },
83+
}
84+
}).pipe(Effect.orDie),
85+
}
86+
}),
87+
)

0 commit comments

Comments
 (0)