@try-works/dsh-recursive-mode 0.4.9 → 0.6.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/src/index.ts CHANGED
@@ -1,700 +1,795 @@
1
- import { type Context } from '@deepseek-ai/cordis'
2
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
3
- import type { ContextFormed } from '@deepseek-ai/dsh-llm'
4
- import { existsSync } from 'node:fs'
5
- import { join } from 'node:path'
6
- import { RecursiveRuntime } from './runtime.ts'
7
- import type { UserQuestionsLike } from './runtime.ts'
8
- import type { JobsRegistryLike } from './jobs-runner.ts'
9
- import { planGateForExit } from './plan-gate.ts'
10
- import { registerPhaseSkills, type SkillRegistryLike } from './skills-phase.ts'
11
- import type { WorkflowEngineLike } from './workflow-audit.ts'
12
- import type { RecursiveModeConfig } from './config.ts'
13
- import { createRecursiveStatusTool } from './recursive_status.tool.ts'
14
- import { createRecursiveInitTool } from './recursive_init.tool.ts'
15
- import { createRecursiveLockTool } from './recursive_lock.tool.ts'
16
- import { createRecursiveLintTool } from './recursive_lint.tool.ts'
17
- import { createRecursiveCloseoutTool } from './recursive_closeout.tool.ts'
18
- import { createRecursiveScratchTool } from './recursive_scratch.tool.ts'
19
- import { createRecursiveWorktreeTool } from './recursive_worktree.tool.ts'
20
- import { createRecursivePhaseTool } from './recursive_phase.tool.ts'
21
- import { createRecursiveAuditTeamTool } from './recursive_audit_team.tool.ts'
22
- import { createRecursiveReviewTool } from './recursive_review.tool.ts'
23
- import { createRecursiveDelegateTool } from './recursive_delegate.tool.ts'
24
- import { createRecursiveAskTool } from './recursive_ask.tool.ts'
25
- import { createRecursivePreviewTool } from './recursive_preview.tool.ts'
26
- import type { SubagentsRuntimeLike } from './delegation.ts'
27
- import { registerRecursiveCommand } from './commands.ts'
28
- import { evaluateToolGuard, coerceAskToDecision, tamperCandidatePath, type ToolGuardDecision } from './enforcement.ts'
29
- import { appendGuardDecision, appendObservedTamper, type GuardDecisionRecord } from './guard-log.ts'
30
- import type { GoalServiceLike } from './goals-projection.ts'
31
- import type { TeamRuntimeLike } from './teams-loop.ts'
32
- import { renderRecursivePolicy } from './policy.ts'
33
- import { fsPolicyIntent } from './fs-intent.ts'
34
- import { snapshotWorkspace } from './snapshot.ts'
35
- import { mountRecursiveRoutesOnce, makeRecursiveRoutes, type RecursiveRouteHost } from './live-route.ts'
36
- import { registerRecursiveSkill } from './skills.ts'
37
- import { enumerateRuns, stageBWorkflowInit } from './bootstrap.ts'
38
- import { getNextLegalPhase, getLockStatus, PHASE_SEQUENCE } from './lock.ts'
39
- import { adoptSettlement } from './settlement.ts'
40
- import type { LlmInventoryLike } from './model-inventory.ts'
41
- import { resolveRunDir } from './run.ts'
42
- import { phaseLintRulesMessage, ReminderOnceGate } from './phase-rules.ts'
43
- import { settlementFromEvent, runDirForChild, recordSettlement } from './settlement.ts'
44
-
45
- /**
46
- * rc.2 rebase (T31a) — the message-source vocabulary changed under us.
47
- *
48
- * At `dsh-v0.1.1-rc.2` `MessageSourceMap` carried a shared catch-all
49
- * `plugin: { kind: 'plugin'; plugin: string }` entry, which this file used for
50
- * its injected phase-lint reminder. At `dsh-v0.2.0-rc.2` that entry is GONE:
51
- * the map is merge-extensible and, in its own words, "each producer declares
52
- * its own `kind` in its own module; there is no shared catch-all `plugin`
53
- * kind". This was invisible in the old checkout because its `node_modules`
54
- * still held a stale `dsh-llm`.
55
- *
56
- * The idiom below is copied from the shipped `@deepseek-ai/dsh-repeat-tool-reminder`,
57
- * whose pre-step reminder is the closest analogue to ours: a user-role message
58
- * whose source declares its own kind and a `form: 'notice'` one-line account.
59
- */
60
- declare module '@deepseek-ai/dsh-llm' {
61
- interface MessageSourceMap {
62
- 'recursive-mode': { kind: 'recursive-mode' } & ContextFormed
63
- }
64
- }
65
-
66
- /** Producer source stamped on every injected phase-lint reminder. */
67
- const REMINDER_SOURCE = { kind: 'recursive-mode' } as const
68
-
69
- export const name = '@try-works/dsh-recursive-mode'
70
-
71
- /**
72
- * T7: the plugin's Config schema, which the settings service DISCOVERS (see `src/config.ts`
73
- * for why declaring it is the registration). Re-exported from the entry because the Loader
74
- * reads it from the plugin module.
75
- */
76
- export { Config } from './config.ts'
77
- export type { RecursiveModeConfig } from './config.ts'
78
-
79
- export { RecursiveRuntime } from './runtime.ts'
80
- export { createRecursiveStatusTool } from './recursive_status.tool.ts'
81
- export { createRecursiveInitTool } from './recursive_init.tool.ts'
82
- export { createRecursiveLockTool } from './recursive_lock.tool.ts'
83
- export { createRecursiveLintTool } from './recursive_lint.tool.ts'
84
- export { createRecursiveCloseoutTool } from './recursive_closeout.tool.ts'
85
- export { createRecursiveScratchTool } from './recursive_scratch.tool.ts'
86
- export { createRecursiveWorktreeTool } from './recursive_worktree.tool.ts'
87
- export { createRecursivePhaseTool } from './recursive_phase.tool.ts'
88
- export * from './status.ts'
89
- export {
90
- PHASE_SEQUENCE,
91
- OPTIONAL_PHASES,
92
- normalizeForLockHash,
93
- lockHashFromContent,
94
- phaseIndex,
95
- isCoreArtifact,
96
- getPrerequisites,
97
- getLockStatus,
98
- getPrerequisiteBlockers,
99
- receiptPath,
100
- readReceipt,
101
- writeReceipt,
102
- invalidateReceipt,
103
- getStaleDownstreamPhases,
104
- getNextLegalPhase,
105
- getAllStaleReceipts,
106
- validateChain,
107
- } from './lock.ts'
108
- export type {
109
- LockReceipt,
110
- LockStatus,
111
- PrerequisiteBlocker,
112
- StaleDownstream,
113
- ChainPhaseResult,
114
- LockChainResult,
115
- } from './lock.ts'
116
- export * from './run.ts'
117
- export * from './review.ts'
118
- export * from './handoff.ts'
119
- export * from './router.ts'
120
- export * from './delegation.ts'
121
- export * from './lifecycle.ts'
122
- export * from './enforcement.ts'
123
- export * from './policy.ts'
124
- export * from './snapshot.ts'
125
- export * from './live-route.ts'
126
- export * from './teams-loop.ts'
127
- export * from './skills.ts'
128
-
129
- /**
130
- * Bundle plugin entry. The Loader activates this row once `tools` is available
131
- * (`inject` below); the RecursiveRuntime service is constructed directly so it
132
- * is provided on `ctx.recursive` for the lifetime of this fiber, and the
133
- * read-path tools (status/init/lock/lint) are registered through it (R2/R4).
134
- */
135
- export const inject = ['tools']
136
-
137
- /**
138
- * Plugin entry (SP2 R1). Stage A (mount-time, this apply): register the
139
- * isolated ctx.recursive service + the recursive_* tools + the /recursive
140
- * command + the recursive:policy prompt section + the LIVE board/strip route
141
- * (HTTP state + SSE), served per-workspace from the filesystem fold. No
142
- * repo/run work and NO session-event emission here: zero recursive/* events
143
- * are ever appended (resume-crash fix), and the board reads the live fs route.
144
- */
145
- /** T38: the built-in guard's hook name — the chain's identity for "this was the plugin's own". */
146
- const BUILTIN_GUARD_HOOK_NAME = 'builtin-tool-guard'
147
-
148
- /**
149
- * T38 — the tool guard, as a function rather than an inline block.
150
- *
151
- * Extracted so the SAME code can run as a hook on the registry: a built-in and a
152
- * sibling then share one chain, one ordering rule and one failure policy, instead of
153
- * the built-in being privileged code that always runs first. Every side effect stays
154
- * here — the guard-decision log is written by whoever computes the decision, so moving
155
- * the call site cannot lose it.
156
- *
157
- * The `ask` coercion is unchanged and stays key-frozen: `coerceAskToDecision`'s output
158
- * is asserted with an exact `toEqual`, so the rebuilt object carries the guard's `rule`
159
- * and `transition` forward rather than letting the coercion drop them.
160
- */
161
- function runToolGuard(
162
- recursive: RecursiveRuntime,
163
- exec: unknown,
164
- root: string,
165
- runId: string,
166
- ): ToolGuardDecision {
167
- const guardMode = recursive.enforcementConfig.toolGuards
168
- const decision = evaluateToolGuard(exec as never, root, runId, guardMode)
169
- const coerced = coerceAskToDecision(decision, guardMode)
170
- const final: ToolGuardDecision = coerced === decision
171
- ? decision
172
- : { ...coerced, rule: decision.rule, transition: decision.transition }
173
- // T15 (C/D): every decision is logged — allows included — so the rolling trace shows
174
- // what the guard decided AND why, not only refusals. File-backed evidence in the
175
- // control-plane config dir: zero session-event emission.
176
- if (root) {
177
- const record: GuardDecisionRecord = {
178
- at: new Date().toISOString(),
179
- runId,
180
- tool: (exec as { name?: string } | null)?.name ?? '',
181
- kind: final.kind,
182
- rule: final.rule ?? 'none',
183
- }
184
- if (final.kind === 'allow') {
185
- if (final.warn) record.reason = final.warn
186
- } else if (final.reason) {
187
- record.reason = final.reason
188
- }
189
- if (final.transition) record.transition = final.transition
190
- appendGuardDecision(root, record)
191
- }
192
- return final
193
- }
194
-
195
- export function apply(ctx: Context, config?: RecursiveModeConfig) {
196
- // R4 shell split (02-to-be-plan.addendum-r4-r2-mount-resolution.md): the
197
- // global bare-name row in cordis.patch.yml mounts with config.shellOnly=true
198
- // to expose ONLY the client bundle for client discovery. It must register
199
- // NOTHING on the server root — no tools, no /recursive command, no
200
- // recursive:policy, no projection (BUG 4 always-on leak). The full server
201
- // surface is mounted ONLY by the recursive preset's isolated recursive-realm,
202
- // whose rows carry no config (shellOnly undefined).
203
- if (config?.shellOnly) return
204
- ctx.effect(function* () {
205
- // Workspace registry: optional host service (durable). Access via ctx.get —
206
- // property access requires inject and would fail boot when undeclared.
207
- // Resolve the control-plane root strictly from the session agent's cwd.
208
- const workspaceRegistry = ctx.get('workspaceRegistry') as never
209
- // T1 (goals projection): the goals service is on the host plane; it resolves
210
- // from inside the recursive-realm via inheritance (same as workspaceRegistry).
211
- // SAFETY: the goals service is an optional host service (could be absent); the
212
- // run projection treats null as "no goal backing" and never throws.
213
- const goals = ctx.get('goals') as GoalServiceLike | null
214
- // T10: the native jobs registry, when the composition mounts one. OPTIONAL on purpose —
215
- // a long operation must still run, and say it was untracked, rather than fail because no
216
- // board is attached.
217
- const jobs = ctx.get('jobs') as JobsRegistryLike | undefined
218
- // T39: the subagents seam is resolved HERE, at the composition, so the runtime can fall back
219
- // to it when a caller passes none. Measured reason: `recursive_review.tool.ts` — the only
220
- // production caller of `delegateReview` — passes no seam, and the runtime then reported
221
- // "no ctx.subagents runtime available" on a host that had mounted it all along.
222
- const subagentsSeamForRuntime = ctx.get('subagents') as SubagentsRuntimeLike | undefined
223
- const recursive = new RecursiveRuntime(ctx, { repoRoot: config?.repoRoot ?? process.cwd(), workspaceRegistry, goals, jobs, subagents: subagentsSeamForRuntime ?? null, workflow: ctx.get('workflow') as WorkflowEngineLike | undefined ?? null })
224
- // ⚠ FU-9 — AND RESOLVE IT AGAIN WHENEVER THE SERVICE APPEARS, because the one-shot get above is only a
225
- // fast path. A live run proved the cost of relying on it: the review fell back to self-audit and reported
226
- // `Status: failed` while a child DIRECTORY sat there — written by this plugin's own brief writer, before
227
- // any service call — so the artifact looked like a started child and was not. `ctx.inject` is the
228
- // harness's own pattern for a service that may be mounted by a later layer, and it fires immediately when
229
- // the service is already present, so this is a guarantee rather than a second chance.
230
- ctx.inject(['subagents'], (subagentsCtx: Context) => {
231
- recursive.attachSubagents((subagentsCtx.get('subagents') as SubagentsRuntimeLike | undefined) ?? null)
232
- })
233
- // ⚠ FU-19 — AND THE LLM INVENTORY, the same late-attaching way: `ctx.llm` is what the browser model catalog is
234
- // built from, so it is the service that knows which providers and models this host actually has. Resolved
235
- // optionally — a host without it gets the `unverified` verdict rather than a silent approval.
236
- const llmInventory = ctx.get('llm') as LlmInventoryLike | undefined
237
- recursive.attachLlmInventory(llmInventory ?? null)
238
- ctx.inject(['llm'], (llmCtx: Context) => {
239
- recursive.attachLlmInventory((llmCtx.get('llm') as LlmInventoryLike | undefined) ?? null)
240
- })
241
- // ⚠ PHASE 0 — THE HUMAN-QUESTION CHANNEL, resolved the same late-attaching way for the same reason:
242
- // a composition may mount `userQuestions` after this plugin applies, and the run-start gate asks the
243
- // person DIRECTLY through it before it arms a goal — which is what keeps a relayed `Start run` from
244
- // being an approval while a person can actually be asked (see run-start.ts).
245
- recursive.attachUserQuestions((ctx.get('userQuestions') as UserQuestionsLike | undefined) ?? null)
246
- ctx.inject(['userQuestions'], (questionsCtx: Context) => {
247
- recursive.attachUserQuestions((questionsCtx.get('userQuestions') as UserQuestionsLike | undefined) ?? null)
248
- })
249
-
250
- // T7 — THE SETTINGS NAMESPACE, APPLIED ON EVERY APPLY. The settings service edits the
251
- // Loader entry's config and the Loader RE-APPLIES this plugin, so a toggle in the UI
252
- // lands on this line: the re-application IS the hot reload, and there is deliberately
253
- // no watcher or file poller here to drift out of sync with it.
254
- //
255
- // Guarded on PRESENCE rather than truthiness: `enforcement: undefined` means "the
256
- // caller said nothing", which must leave the runtime's own default alone, while an
257
- // explicit object — including one whose fields the schema defaulted — is a decision.
258
- // Validation stays in `resolveEnforcementConfig` (strict, fail-loud), so a bad value
259
- // from any source is refused rather than coerced.
260
- if (config?.enforcement !== undefined) recursive.setEnforcementConfig(config.enforcement)
261
-
262
- // T12 — publish each phase's rules to the native SKILL catalogue, so the agent and its
263
- // children can ASK what a phase requires instead of grepping this checkout. The catalogue is
264
- // optional; with none mounted this registers nothing and says so, because a composition
265
- // without skills should still run the workflow.
266
- const phaseSkills = registerPhaseSkills(ctx.get('skills') as SkillRegistryLike | undefined, PHASE_SEQUENCE)
267
- // Tied to this plugin's effects: the contribution is withdrawn with the fiber that made it.
268
- yield () => { for (const dispose of phaseSkills.disposers) dispose() }
269
-
270
- // T7 part 2 — the ROUTER overrides, on the same terms: present means override, absent
271
- // means defer to the workspace's declarative `recursive-router.json`. ONE PATH, NOT
272
- // TWO: this does not replace the file, it lays over it (see `loadRouterPolicy`).
273
- if (config?.router !== undefined) recursive.setRouterOverrides(config.router)
274
-
275
- const repairedRoots = new Set<string>()
276
- const reminderGate = new ReminderOnceGate()
277
- // T3 (agentTeams task loop): wire the live ctx.agentTeams service (optional —
278
- // absent in compositions without the experimental agent-team row) into the
279
- // turn-driven task-board tool. The whole-loop driver (auditToPass) is also
280
- // exported for callers with a settlement observer.
281
- // SAFETY: ctx.get returns the live service as an opaque value; the single
282
- // boundary cast asserts it satisfies the TeamRuntimeLike structural seam
283
- // (createTask/updateTask plus optional wait/interrupt/board reads). The
284
- // live service's real Agent parameter is a superset of TeamCallerHandle, so
285
- // the seam passes the exact live Agent the tool extracts from exec.agent.
286
- const agentTeams = ctx.get('agentTeams') as TeamRuntimeLike | undefined
287
- // T36: the continuable-subagent seam the review tool drives. Optional for the
288
- // same reason as agentTeams — absent it, `recursive_review` still runs and
289
- // reports `unavailable`, naming that the repair path does not exist rather than
290
- // pretending the review was a success.
291
- const subagentsSeam = subagentsSeamForRuntime
292
-
293
- // Packaged skill (dsh plugin standard): register the `recursive-mode` skill
294
- // into the host skills registry via ctx.skills.registerProvider (the
295
- // dsh-skill-badge bundled-provider shape). Optional — a composition without
296
- // a skills registry is valid and this no-ops (returns undefined).
297
- const skillDisposer = registerRecursiveSkill(ctx)
298
-
299
- const disposers = [
300
- ...(skillDisposer ? [skillDisposer] : []),
301
- ctx.tools.register(createRecursiveStatusTool(recursive)),
302
- ctx.tools.register(createRecursiveInitTool(recursive)),
303
- ctx.tools.register(createRecursiveLockTool(recursive)),
304
- ctx.tools.register(createRecursiveLintTool(recursive)),
305
- ctx.tools.register(createRecursiveCloseoutTool(recursive)),
306
- ctx.tools.register(createRecursiveScratchTool(recursive)),
307
- ctx.tools.register(createRecursiveWorktreeTool(recursive)),
308
- ctx.tools.register(createRecursivePhaseTool(recursive)),
309
- ctx.tools.register(createRecursiveReviewTool(recursive, subagentsSeam)),
310
- // ⚠ FU-17 — WORK delegation: the main agent hands a phase's actual work to a child, reads it, and sends
311
- // feedback to the same child. Registered beside the review tool because they share the round driver, the
312
- // settlement observer and the reply contract — the difference is what a settlement MEANS.
313
- ctx.tools.register(createRecursiveDelegateTool(recursive, subagentsSeam)),
314
- // T23: the three human gates as structured decisions. Registered here so the ask is a TOOL call
315
- // — which is what the host renders as a card — rather than prose a person has to interpret.
316
- ctx.tools.register(createRecursiveAskTool(recursive)),
317
- // T26: the read-only view of what the enforcement contract will do, before it fires.
318
- ctx.tools.register(createRecursivePreviewTool(recursive)),
319
- ]
320
-
321
- // ⚠ FIX 1 — THE THIRD SEAM NEEDED THE SAME LATE ATTACH AS THE OTHER TWO, AND DID NOT HAVE IT.
322
- //
323
- // The line that used to sit in the array above was `...(agentTeams ? [register(...)] : [])` — a ONE-SHOT
324
- // `ctx.get('agentTeams')` taken at apply time. A live verification pass found the consequence: `team_task_create`
325
- // worked in the same session whose tool catalog lacked `recursive_audit_team`, because the service was mounted
326
- // AFTER this plugin applied. The plugin shipped 13 tool files and offered 12.
327
- //
328
- // `subagents` and `llm` already solve this with `ctx.inject` (above); this is that pattern, with one addition the
329
- // others do not need: the tool may only be registered ONCE, because the one-shot path can already have taken it.
330
- let auditTeamRegistered = agentTeams !== undefined && agentTeams !== null
331
- if (auditTeamRegistered) disposers.push(ctx.tools.register(createRecursiveAuditTeamTool(agentTeams ?? null)))
332
- ctx.inject(['agentTeams'], (teamCtx: Context) => {
333
- if (auditTeamRegistered) return
334
- const late = teamCtx.get('agentTeams') as TeamRuntimeLike | undefined
335
- if (late === undefined || late === null) return
336
- auditTeamRegistered = true
337
- // ⚠ CORRECTED COMMENT. This registers through the OUTER plugin context (`ctx`), NOT through the
338
- // injecting `teamCtx` — `teamCtx` is used on the line above only to READ the late service, and the
339
- // sibling `subagents`/`llm` injects use their callback context the same way. The comment that used to
340
- // sit here claimed the injecting scope owned the registration, which is not what this call does.
341
- //
342
- // WHAT IS NOT CLAIMED: that the fiber withdraws this registration. Nobody has observed that — no test
343
- // covers the late `recursive_audit_team` being withdrawn — and the disposer returned here is not
344
- // retained, unlike the eager registration above, which pushes its own onto `disposers`. Until a test
345
- // observes the withdrawal, this comment promises nothing about it.
346
- ctx.tools.register(createRecursiveAuditTeamTool(late))
347
- })
348
-
349
- // /recursive command (R4): preset-scoped registration, workspace-scoped dispatch.
350
- const commands = ctx.get('commands') as { register: (def: unknown) => () => void } | undefined
351
- if (commands) {
352
- disposers.push(registerRecursiveCommand({ commands } as never, recursive))
353
- }
354
-
355
- // recursive:policy prompt section (Phase C R5): workspace-scoped behavior +
356
- // current-phase contract rendered from folded state + enforcement config.
357
- const systemPrompt = ctx.get('systemPrompt') as { section: (def: unknown) => () => void } | undefined
358
- if (systemPrompt) {
359
- disposers.push(systemPrompt.section({
360
- name: 'recursive:policy',
361
- order: 55,
362
- text: (context: unknown) => {
363
- const agent = (context as { agent?: { session?: { header?: { cwd?: string } } } } | undefined)?.agent
364
- if (!agent) return ''
365
- // SP3 R5 policy-render fix: derive intent from the FILESYSTEM, not the
366
- // retired recursive/phase-intent session event (zero-emission removed
367
- // the emitter; 0.2.2 deleted the event-fold helper that read it, so this
368
- // signal was ALWAYS null and this section rendered ''). Pure read-only fs
369
- // folding; no recursive/*
370
- // events are appended.
371
- const intent = fsPolicyIntent(agent, workspaceRegistry as never)
372
- if (!intent) return ''
373
- return renderRecursivePolicy({ worktreeRoot: intent.worktreeRoot, runId: intent.runId, config: recursive.enforcementConfig })
374
- },
375
- }))
376
- }
377
-
378
- // Phase C R3 (Layer 1, agent/pre-step proactive intent gate) is RETIRED
379
- // under zero-emission (SP2 R1): its only signal was the recursive/phase-intent
380
- // session event, whose emitter is now deleted, and it was ADVISORY by default
381
- // (it never rejected; its sole side effect was the now-removed emission).
382
- // Enforcement is preserved where it actually bites: Layer 2 (tools/pre-execute
383
- // inspects the REAL tool call args below) plus the recursive_lock tool's own
384
- // prerequisite validation in lockArtifact — strictly more reliable than the
385
- // heuristic intent scan. See 03-implementation-summary.addendum-r1-*.md.
386
-
387
- // Phase C R4: tools/pre-execute surgical guards (Layer 2, caller of the
388
- // transition set). Scope-filtered to the active run's worktree.
389
- //
390
- // T15 — this listener used to hand `evaluateToolGuard` an EMPTY runId, so its
391
- // `runDir` resolved to `<root>/.recursive/run` — the directory that holds run
392
- // DIRECTORIES, not artifacts. The monotonic lock-order and Phase-3 TDD
393
- // branches could therefore never fire; only the locked-write branch worked
394
- // (it resolves its target path directly). The REAL active run id is now
395
- // resolved per call, the same way recursive_status/phaseRules do it.
396
- const sessionsStore = ctx.get('sessions') as
397
- | { get?: (id: string) => { header?: { cwd?: string } } | undefined }
398
- | undefined
399
- // T38 — THE BUILT-IN GUARD IS NOW A HOOK ON THE SAME CHAIN AS EVERYONE ELSE.
400
- //
401
- // Registered at PRIORITY 0 so a sibling with a higher priority runs FIRST and can
402
- // pre-empt it cheaply — which is the point of participation. The guard stays the
403
- // baseline that runs when nobody objects.
404
- //
405
- // `fail_closed` because this is a GATING point: a guard that cannot decide must not
406
- // let the call through. The FULL decision rides back as an annotation, so `ask` and
407
- // `allow` survive with `warn`/`rule`/`transition` intact — the listener returns that
408
- // object VERBATIM, which is what keeps `guard-path` byte-identical.
409
- recursive.hooks.register('pre_trigger', {
410
- name: BUILTIN_GUARD_HOOK_NAME,
411
- priority: 0,
412
- onError: 'fail_closed',
413
- run: (input) => {
414
- const payload = input as { exec?: unknown; root?: string; runId?: string }
415
- const decision = runToolGuard(recursive, payload.exec, payload.root ?? '', payload.runId ?? '')
416
- return decision.kind === 'deny'
417
- ? { decision: 'deny' as const, reason: decision.reason ?? 'denied by the tool guard', annotations: { guardDecision: decision } }
418
- : { decision: 'continue' as const, annotations: { guardDecision: decision } }
419
- },
420
- })
421
- // T13 (part 2) — THE PLAN GATE IS LIVE. `exit_plan_mode` is the event that leaves plan mode,
422
- // so it is where the gate belongs: a run still waiting on a DISCOVERY phase must not leave
423
- // plan mode, because that would start implementing on an unfinished plan. The gate reads the
424
- // phase the run is already waiting on rather than keeping its own state, which is why it
425
- // cannot drift from the workflow.
426
- //
427
- // Priority 5, ABOVE the built-in tool guard at 0: this is a workflow-shaped refusal and
428
- // should be the reason a caller sees, not something the generic guard has to restate.
429
- recursive.hooks.register('pre_trigger', {
430
- name: 'exit-plan-mode-gate',
431
- priority: 5,
432
- onError: 'fail_closed',
433
- run: (input) => {
434
- const payload = input as { tool?: string; root?: string; runId?: string }
435
- if (payload.tool !== 'exit_plan_mode') return { decision: 'continue' as const }
436
- const root = payload.root ?? ''
437
- const runId = payload.runId ?? ''
438
- if (root === '' || runId === '') return { decision: 'continue' as const }
439
- const gate = planGateForExit(getNextLegalPhase(join(root, '.recursive', 'run', runId)))
440
- return gate.allow
441
- ? { decision: 'continue' as const, annotations: { planGate: gate.reason } }
442
- : { decision: 'deny' as const, reason: gate.reason }
443
- },
444
- })
445
- const toolRuntime = ctx as unknown as { on?: (event: string, listener: (payload: unknown, next?: unknown) => unknown) => () => void }
446
- if (toolRuntime.on) {
447
- disposers.push(toolRuntime.on('tools/pre-execute', async (payload, next) => {
448
- const exec = payload as { name?: string; arguments?: unknown; agent?: { session?: { header?: { cwd?: string } } } | null } | null
449
- if (!exec?.name) return typeof next === 'function' ? next() : { kind: 'allow' }
450
- // B3: per-call root is the session cwd (authoritative when the registry is
451
- // absent), never process.cwd().
452
- const cwd = exec?.agent?.session?.header?.cwd ?? ''
453
- const root = (await recursive.resolveRootForRoute(undefined, cwd, sessionsStore)) ?? cwd
454
- // T15 (A): the active run id is resolved from the FILESYSTEM on every call
455
- // — `resolveRunDir` is the canonical latest-run-by-mtime used by
456
- // recursive_status/phaseRules. Deliberately NO ttl/time cache: a cached run
457
- // id would silently reintroduce exactly the empty-runId bug being fixed
458
- // here, because a run created moments ago must be visible immediately. If a
459
- // cache is ever added it must be provably invalidated on run creation.
460
- const runId = root ? resolveRunDir(root)?.runId ?? '' : ''
461
-
462
- // T27 — THE NAMED POINT IS LIVE AT THE ENFORCEMENT SEAM. A sibling hook may
463
- // deny here BEFORE the built-in guard runs, so participation is real rather
464
- // than a reachable registry that nothing consults.
465
- //
466
- // With no hooks registered — the ordinary case — the chain returns `continue`
467
- // and the guard below runs exactly as it always has, which is what keeps
468
- // `guard-path.spec.ts`'s pinned contract byte-identical. That is the point of
469
- // putting the chain FIRST: it adds a way in without moving what was there.
470
- //
471
- // A `hold` is treated as a denial at this seam. `hold` means "stop and wait"
472
- // for a point that can resume later; a tool call has nothing to resume, so
473
- // pretending to hold would silently proceed. Better to refuse and say so.
474
- const preTrigger = await recursive.hooks.run('pre_trigger', {
475
- tool: exec.name,
476
- args: exec.arguments,
477
- exec,
478
- root,
479
- runId,
480
- })
481
- const decider = preTrigger.ran[preTrigger.ran.length - 1]
482
-
483
- // A SIBLING stopped the chain. Checked by the DECIDER, not by the built-in's
484
- // mere absence: a sibling with a LOWER priority than the guard runs after it, so
485
- // "the guard is in the trail" does not mean "the guard decided".
486
- if ((preTrigger.decision === 'deny' || preTrigger.decision === 'hold') && decider?.name !== BUILTIN_GUARD_HOOK_NAME) {
487
- const by = decider?.name ?? 'a pre_trigger hook'
488
- const why = preTrigger.reason ?? 'no reason given'
489
- // A `hold` is treated as a refusal at this seam. `hold` means "stop and wait"
490
- // for a point that can resume later; a tool call has nothing to resume, so
491
- // pretending to hold would silently proceed — worse than refusing, because the
492
- // caller would never learn a hook wanted to stop it.
493
- return {
494
- kind: 'deny',
495
- reason: preTrigger.decision === 'hold'
496
- ? 'held by pre_trigger hook ' + by + ': ' + why
497
- : 'denied by pre_trigger hook ' + by + ': ' + why,
498
- }
499
- }
500
-
501
- // The guard itself failed: it is fail_closed, so the refusal is reported with
502
- // its own error rather than as a silent allow.
503
- if (decider?.name === BUILTIN_GUARD_HOOK_NAME && decider.error !== undefined) {
504
- return { kind: 'deny', reason: 'the tool guard failed: ' + decider.error }
505
- }
506
-
507
- const builtIn = preTrigger.ran.find((entry) => entry.name === BUILTIN_GUARD_HOOK_NAME)
508
- const final = builtIn?.annotations?.guardDecision as ToolGuardDecision | undefined
509
- if (final === undefined) {
510
- // Unreachable while the built-in is registered unconditionally. It fails
511
- // CLOSED rather than allowing, because "we could not decide" is not permission.
512
- return { kind: 'deny', reason: 'the tool guard produced no decision' }
513
- }
514
- // The guard's own object, returned VERBATIM — the pinned contract.
515
- if (final.kind === 'deny') return final
516
- if (final.kind === 'allow' && final.warn) {
517
- // Package-tagged host logging; never a silent pass under approval=never.
518
- console.warn('[recursive] tool guard (advisory): ' + final.warn + ' — allowing')
519
- }
520
- return typeof next === 'function' ? next() : { kind: 'allow' }
521
- }))
522
- }
523
-
524
- // T15 (E): the fs/observed lock-tamper path. The harness contract is a plain
525
- // SYNCHRONOUS emit fired AFTER a successful write, so this listener cannot
526
- // veto anything and contractually must not throw — it only RECORDS. Before
527
- // T15 the plugin had no fs/observed listener at all (the string appeared in
528
- // comments only), so `detectTamper` was exported and unit-tested with no live
529
- // caller and a tampered lock surfaced nowhere but prompt text.
530
- const observationRuntime = ctx as unknown as { on?: (event: string, listener: (target: unknown, observation: unknown, actor: unknown) => void) => () => void }
531
- if (observationRuntime.on) {
532
- disposers.push(observationRuntime.on('fs/observed', (target, observation, actor) => {
533
- try {
534
- // Only a present observation can be a tamper; absent/unrelated are ignored.
535
- if ((observation as { kind?: string } | null)?.kind !== 'present') return
536
- const displayPath = (target as { displayPath?: string } | null)?.displayPath ?? ''
537
- if (!displayPath) return
538
- // Cheap shape test BEFORE any filesystem work: fs/observed fires on reads
539
- // too, so enumerating runs for every observation would be a readdir per
540
- // file touch. The actor is the tool execution. This event cannot await, so
541
- // the root is the actor's session cwd (the same B4 sync shortcut
542
- // fsPolicyIntent takes: the session cwd is authoritative, the registry
543
- // path is async-only). Resolving the cwd first is free — plain property
544
- // reads — and the admission test needs it.
545
- const cwd = (actor as { agent?: { session?: { header?: { cwd?: string } } } } | null)?.agent?.session?.header?.cwd ?? ''
546
- if (!cwd) return
547
- // ⚠ AND THIS IS `detectTamper`'s OWN ADMISSION TEST, CALLED RATHER THAN COPIED.
548
- //
549
- // It used to be an inline hand-copy — `endsWith('.md') && includes('/.recursive/run/')`
550
- // — and a hand-copy is what made the tamper guard blind to one spelling of one
551
- // path: the substring test needs a separator BEFORE `.recursive`, which a
552
- // repo-relative target (`displayPath` as a model would type it) does not have, so
553
- // the listener rejected the candidate here and `detectTamper` was never reached.
554
- // Widening only `detectTamper` would have changed nothing observable. The test now
555
- // lives in one place (`tamperCandidatePath`), so the two cannot disagree; it stays
556
- // pure path arithmetic, so the "no filesystem work before admission" property the
557
- // shape check exists for is preserved.
558
- const normalized = displayPath.replace(/\\/g, '/')
559
- if (!tamperCandidatePath(normalized, cwd)) return
560
- const runId = resolveRunDir(cwd)?.runId ?? ''
561
- const tamper = recursive.detectTamper(normalized, cwd, runId)
562
- if (!tamper) return
563
- appendObservedTamper(cwd, {
564
- at: new Date().toISOString(),
565
- runId: tamper.runId,
566
- path: tamper.path,
567
- reason: tamper.reason,
568
- })
569
- } catch {
570
- // Observe-only: the fs/observed contract forbids throwing.
571
- }
572
- }))
573
- }
574
-
575
- // T36: capture a delegated child's SETTLEMENT at delivery time.
576
- //
577
- // WHY DELIVERY AND NOT HISTORY. The obvious implementation of a parent-side
578
- // settlement observer is to scan the session log for the `subagent-settled`
579
- // notice. That is prohibited: DSH deprecates synchronous reads of arbitrary
580
- // session history (`eventAt`/`snapshotEvents`/`ownEvents`) and states that new
581
- // production calls are prohibited, enforced by an executable lint check. The
582
- // sanctioned replacement is to process the DELIVERED event, which is this
583
- // listener — the same `session/event` seam the projection registry subscribes
584
- // to. The durable fact then lands in the run's own FILE state, which is where
585
- // every other plugin fact lands and keeps the plugin zero-emission.
586
- //
587
- // The loop needs this because there is NO parent-side promise to await: a
588
- // continuable child's settlement arrives as a durable user message on a later
589
- // turn, so the round observer must find a recorded settlement or honestly
590
- // report that none has landed yet.
591
- const sessionRuntime = ctx as unknown as { on?: (event: string, listener: (session: unknown, event: unknown) => void) => () => void }
592
- if (sessionRuntime.on) {
593
- disposers.push(sessionRuntime.on('session/event', (session, event) => {
594
- try {
595
- // Cheap shape test FIRST: session/event fires for EVERY committed event
596
- // in every session, so a non-settlement must be rejected before any
597
- // filesystem work. This is the same ordering the fs/observed listener
598
- // uses, for the same reason.
599
- const notice = settlementFromEvent(event as never)
600
- if (notice === null) return
601
- // B3: the session cwd is the authoritative control-plane root per call.
602
- const cwd = (session as { header?: { cwd?: string } } | null)?.header?.cwd ?? ''
603
- if (cwd === '') return
604
- const runDir = runDirForChild(cwd, notice.childId)
605
- // No run (or an ambiguous one) means the settlement is not filed rather
606
- // than filed wrongly: the loop will report "no settlement yet", which is
607
- // recoverable, whereas attaching evidence to the wrong run is not.
608
- if (runDir === null) {
609
- // ⚠ FU-17 — ADOPT RATHER THAN DROP. The rule above still holds — never guess between runs — but a
610
- // settlement for a child nobody filed is evidence of work that really happened, and dropping it
611
- // means a phase artifact cannot cite it. `adoptSettlement` files it into the single run when there
612
- // is exactly one, and into a root-level adoption log when choosing would mean guessing. Marked as
613
- // adopted either way, so a reader can tell an adopted record from a delegation's own.
614
- adoptSettlement(cwd, notice)
615
- return
616
- }
617
- recordSettlement(runDir, notice)
618
- } catch {
619
- // Observe-only. This rides the hot path of every session event and must
620
- // never break the session it observes.
621
- }
622
- }))
623
- }
624
-
625
- // SP3 R5: agent/pre-step lint-rules injection (pre-step contract verified: the
626
- // listener returns { kind: 'enter', messages: [...messages, injected] } and the
627
- // returned array REPLACES the default [...claimed, context]). When the session's
628
- // control-plane root has an active recursive run whose current phase doc is
629
- // DRAFT, prepend a compact system-reminder with THAT phase's required sections +
630
- // gates. Pure fs read (zero-emission): never appends recursive/* events.
631
- const agentRuntime = ctx as unknown as { on?: (event: string, listener: (payload: unknown, next?: unknown) => unknown) => () => void }
632
- if (agentRuntime.on) {
633
- disposers.push(agentRuntime.on('agent/pre-step', async (payload, next) => {
634
- const p = payload as {
635
- messages?: Array<{ content: Array<{ type: string; text?: string }> }>,
636
- agent?: { session?: { header?: { cwd?: string } } } | null,
637
- } | null
638
- const messages = p?.messages ?? []
639
- const agent = p?.agent ?? null
640
- const cwd = agent?.session?.header?.cwd ?? ''
641
- // delegate first so later listeners keep veto power, then fold ours on
642
- if (typeof next === 'function') await next()
643
- if (!cwd) return { kind: 'enter', messages } as const
644
- const root = await recursive.resolveRootForRoute(undefined, cwd, undefined)
645
- if (!root) return { kind: 'enter', messages } as const
646
- // R3/R6 (run 09): idempotent scaffold REPAIR on session-start (new AND
647
- // resume). bootstrapScaffold is upsert-only: it adds missing control-plane
648
- // files/dirs + re-upserts marked blocks, NEVER overwriting user content or
649
- // touching run/ artifacts (in-flight 02-to-be-plan etc. are preserved).
650
- // Guarded once per root so repeated pre-steps are cheap no-ops.
651
- if (!repairedRoots.has(root)) {
652
- repairedRoots.add(root)
653
- stageBWorkflowInit({ root, source: 'resume' })
654
- }
655
- const runs = enumerateRuns(root)
656
- if (runs.length === 0) return { kind: 'enter', messages } as const
657
- const runId = runs[runs.length - 1]
658
- const runDir = join(root, '.recursive', 'run', runId)
659
- if (!existsSync(runDir)) return { kind: 'enter', messages } as const
660
- const phase = getNextLegalPhase(runDir)
661
- if (!phase) return { kind: 'enter', messages } as const
662
- // only inject when the phase doc is DRAFT (not locked/missing).
663
- const phasePath = join(runDir, phase)
664
- const status = existsSync(phasePath) ? getLockStatus(phasePath) : null
665
- if (status !== 'DRAFT') return { kind: 'enter', messages } as const
666
- if (!reminderGate.shouldInject(root, runId, phase)) return { kind: 'enter', messages } as const
667
- // LIVE BUG 6 (0.2.1): inject the lint-rules reminder AT MOST ONCE PER PHASE.
668
- // The scaffold repair above is deduped via repairedRoots; the reminder itself was
669
- // not, so every pre-step while DRAFT re-injected it.
670
- const reminder = phaseLintRulesMessage(phase)
671
- return {
672
- kind: 'enter',
673
- messages: [...messages, createUserMessage({ content: [{ type: 'text', text: reminder }], source: { ...REMINDER_SOURCE, form: 'notice', summary: 'phase ' + phase + ' lint rules' } })],
674
- } as const
675
- }))
676
- }
677
-
678
- // Phase C R8: fs/observed lock-tamper WARNINGS are served to the board via the
679
- // mountOnce-global: apply() runs per-session, but the route must register
680
- // exactly once (WebServer.register throws on duplicate kind+path) and serve
681
- // PER-WORKSPACE state. No-op when the host composes no webServer (headless).
682
- // (`sessionsStore` is resolved once, above the pre-execute listener, which now
683
- // needs it too.)
684
- const webServer = ctx.get('webServer') as
685
- | { register: (route: { kind: string; path: string; handler: unknown }) => () => void }
686
- | undefined
687
- if (webServer) {
688
- const host: RecursiveRouteHost = {
689
- // sessionId PRIMARY: the host resolves cwd from the attached session header;
690
- // the client-passed cwd is a fallback hint (hydration / headless).
691
- resolveRoot: async (sessionId: string | undefined, cwd: string) => recursive.resolveRootForRoute(sessionId, cwd, sessionsStore),
692
- snapshot: async (root: string) => snapshotWorkspace(root),
693
- revision: () => 1,
694
- }
695
- disposers.push(mountRecursiveRoutesOnce('@try-works/dsh-recursive-mode', () => makeRecursiveRoutes(host), webServer))
696
- }
697
-
698
- yield () => { for (const d of disposers) d() }
699
- })
700
- }
1
+ import { type Context } from '@deepseek-ai/cordis'
2
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
3
+ import type { ContextFormed } from '@deepseek-ai/dsh-llm'
4
+ import { existsSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { RecursiveRuntime } from './runtime.ts'
7
+ import type { UserQuestionsLike } from './runtime.ts'
8
+ import type { JobsRegistryLike } from './jobs-runner.ts'
9
+ import { planGateForExit } from './plan-gate.ts'
10
+ import { registerPhaseSkills, type SkillRegistryLike } from './skills-phase.ts'
11
+ import type { WorkflowEngineLike } from './workflow-audit.ts'
12
+ import type { RecursiveModeConfig } from './config.ts'
13
+ import { createRecursiveStatusTool } from './recursive_status.tool.ts'
14
+ import { createRecursiveInitTool } from './recursive_init.tool.ts'
15
+ import { createRecursiveLockTool } from './recursive_lock.tool.ts'
16
+ import { createRecursiveLintTool } from './recursive_lint.tool.ts'
17
+ import { createRecursiveCloseoutTool } from './recursive_closeout.tool.ts'
18
+ import { createRecursiveScratchTool } from './recursive_scratch.tool.ts'
19
+ import { createRecursiveWorktreeTool } from './recursive_worktree.tool.ts'
20
+ import { createRecursivePhaseTool } from './recursive_phase.tool.ts'
21
+ import { createRecursiveAuditTeamTool } from './recursive_audit_team.tool.ts'
22
+ import { createRecursiveReviewTool } from './recursive_review.tool.ts'
23
+ import { createRecursiveDelegateTool } from './recursive_delegate.tool.ts'
24
+ import { createRecursiveAskTool } from './recursive_ask.tool.ts'
25
+ import { renderGateBlockAsk } from './recursive_ask.tool.ts'
26
+ import { createRecursivePreviewTool } from './recursive_preview.tool.ts'
27
+ import type { SubagentsRuntimeLike } from './delegation.ts'
28
+ import { registerRecursiveCommand } from './commands.ts'
29
+ import { evaluateToolGuard, coerceAskToDecision, tamperCandidatePath, type ToolGuardDecision } from './enforcement.ts'
30
+ import { appendGuardDecision, appendObservedTamper, type GuardDecisionRecord } from './guard-log.ts'
31
+ import type { GoalServiceLike } from './goals-projection.ts'
32
+ import type { TeamRuntimeLike } from './teams-loop.ts'
33
+ import { renderRecursivePolicy } from './policy.ts'
34
+ import { fsPolicyIntent } from './fs-intent.ts'
35
+ import { snapshotWorkspace } from './snapshot.ts'
36
+ import { mountRecursiveRoutesOnce, makeRecursiveRoutes, type RecursiveRouteHost } from './live-route.ts'
37
+ import { registerRecursiveSkill } from './skills.ts'
38
+ import { enumerateRuns, stageBWorkflowInit } from './bootstrap.ts'
39
+ import { getNextLegalPhase, getLockStatus, PHASE_SEQUENCE } from './lock.ts'
40
+ import { adoptSettlement } from './settlement.ts'
41
+ import type { LlmInventoryLike } from './model-inventory.ts'
42
+ import { resolveRunDir } from './run.ts'
43
+ import { phaseLintRulesMessage, ReminderOnceGate } from './phase-rules.ts'
44
+ import { settlementFromEvent, runDirForChild, recordSettlement } from './settlement.ts'
45
+
46
+ /**
47
+ * rc.2 rebase (T31a) — the message-source vocabulary changed under us.
48
+ *
49
+ * At `dsh-v0.1.1-rc.2` `MessageSourceMap` carried a shared catch-all
50
+ * `plugin: { kind: 'plugin'; plugin: string }` entry, which this file used for
51
+ * its injected phase-lint reminder. At `dsh-v0.2.0-rc.2` that entry is GONE:
52
+ * the map is merge-extensible and, in its own words, "each producer declares
53
+ * its own `kind` in its own module; there is no shared catch-all `plugin`
54
+ * kind". This was invisible in the old checkout because its `node_modules`
55
+ * still held a stale `dsh-llm`.
56
+ *
57
+ * The idiom below is copied from the shipped `@deepseek-ai/dsh-repeat-tool-reminder`,
58
+ * whose pre-step reminder is the closest analogue to ours: a user-role message
59
+ * whose source declares its own kind and a `form: 'notice'` one-line account.
60
+ */
61
+ declare module '@deepseek-ai/dsh-llm' {
62
+ interface MessageSourceMap {
63
+ 'recursive-mode': { kind: 'recursive-mode' } & ContextFormed
64
+ }
65
+ }
66
+
67
+ /** Producer source stamped on every injected phase-lint reminder. */
68
+ const REMINDER_SOURCE = { kind: 'recursive-mode' } as const
69
+
70
+ export const name = '@try-works/dsh-recursive-mode'
71
+
72
+ /**
73
+ * T7: the plugin's Config schema, which the settings service DISCOVERS (see `src/config.ts`
74
+ * for why declaring it is the registration). Re-exported from the entry because the Loader
75
+ * reads it from the plugin module.
76
+ */
77
+ export { Config } from './config.ts'
78
+ export type { RecursiveModeConfig } from './config.ts'
79
+
80
+ export { RecursiveRuntime } from './runtime.ts'
81
+ export { createRecursiveStatusTool } from './recursive_status.tool.ts'
82
+ export { createRecursiveInitTool } from './recursive_init.tool.ts'
83
+ export { createRecursiveLockTool } from './recursive_lock.tool.ts'
84
+ export { createRecursiveLintTool } from './recursive_lint.tool.ts'
85
+ export { createRecursiveCloseoutTool } from './recursive_closeout.tool.ts'
86
+ export { createRecursiveScratchTool } from './recursive_scratch.tool.ts'
87
+ export { createRecursiveWorktreeTool } from './recursive_worktree.tool.ts'
88
+ export { createRecursivePhaseTool } from './recursive_phase.tool.ts'
89
+ export * from './status.ts'
90
+ export {
91
+ PHASE_SEQUENCE,
92
+ OPTIONAL_PHASES,
93
+ normalizeForLockHash,
94
+ lockHashFromContent,
95
+ phaseIndex,
96
+ isCoreArtifact,
97
+ getPrerequisites,
98
+ getLockStatus,
99
+ getPrerequisiteBlockers,
100
+ receiptPath,
101
+ readReceipt,
102
+ writeReceipt,
103
+ invalidateReceipt,
104
+ getStaleDownstreamPhases,
105
+ getNextLegalPhase,
106
+ getAllStaleReceipts,
107
+ validateChain,
108
+ } from './lock.ts'
109
+ export type {
110
+ LockReceipt,
111
+ LockStatus,
112
+ PrerequisiteBlocker,
113
+ StaleDownstream,
114
+ ChainPhaseResult,
115
+ LockChainResult,
116
+ } from './lock.ts'
117
+ export * from './run.ts'
118
+ export * from './review.ts'
119
+ export * from './handoff.ts'
120
+ export * from './router.ts'
121
+ export * from './delegation.ts'
122
+ export * from './lifecycle.ts'
123
+ export * from './enforcement.ts'
124
+ export * from './policy.ts'
125
+ export * from './snapshot.ts'
126
+ export * from './live-route.ts'
127
+ export * from './teams-loop.ts'
128
+ export * from './skills.ts'
129
+
130
+ /**
131
+ * Bundle plugin entry. The Loader activates this row once `tools` is available
132
+ * (`inject` below); the RecursiveRuntime service is constructed directly so it
133
+ * is provided on `ctx.recursive` for the lifetime of this fiber, and the
134
+ * read-path tools (status/init/lock/lint) are registered through it (R2/R4).
135
+ */
136
+ export const inject = ['tools']
137
+
138
+ /**
139
+ * Plugin entry (SP2 R1). Stage A (mount-time, this apply): register the
140
+ * isolated ctx.recursive service + the recursive_* tools + the /recursive
141
+ * command + the recursive:policy prompt section + the LIVE board/strip route
142
+ * (HTTP state + SSE), served per-workspace from the filesystem fold. No
143
+ * repo/run work and NO session-event emission here: zero recursive/* events
144
+ * are ever appended (resume-crash fix), and the board reads the live fs route.
145
+ */
146
+ /** T38: the built-in guard's hook name — the chain's identity for "this was the plugin's own". */
147
+ const BUILTIN_GUARD_HOOK_NAME = 'builtin-tool-guard'
148
+
149
+ /**
150
+ * T38 — the tool guard, as a function rather than an inline block.
151
+ *
152
+ * Extracted so the SAME code can run as a hook on the registry: a built-in and a
153
+ * sibling then share one chain, one ordering rule and one failure policy, instead of
154
+ * the built-in being privileged code that always runs first. Every side effect stays
155
+ * here — the guard-decision log is written by whoever computes the decision, so moving
156
+ * the call site cannot lose it.
157
+ *
158
+ * The `ask` coercion is unchanged and stays key-frozen: `coerceAskToDecision`'s output
159
+ * is asserted with an exact `toEqual`, so the rebuilt object carries the guard's `rule`
160
+ * and `transition` forward rather than letting the coercion drop them.
161
+ */
162
+ function runToolGuard(
163
+ recursive: RecursiveRuntime,
164
+ exec: unknown,
165
+ root: string,
166
+ runId: string,
167
+ ): ToolGuardDecision {
168
+ const guardMode = recursive.enforcementConfig.toolGuards
169
+ const decision = evaluateToolGuard(exec as never, root, runId, guardMode)
170
+ const coerced = coerceAskToDecision(decision, guardMode)
171
+ // ⚠ ISSUE 2 (b) — THE RECORD FOLLOWS THE RUN THE GUARD ACTUALLY READ, not the one the filesystem calls
172
+ // active. The guard resolves the run per call (a lock call that names a run is judged against THAT run's
173
+ // tree — see `resolveGuardRunId`), so logging the active run here would attribute a rule's answer to a run
174
+ // it never looked at: measured before this fix as `runId: "run-a"` on a refusal whose blockers came from
175
+ // run-b. `runId` (the active run) remains the fallback for a hand-built decision, which is the
176
+ // pre-existing behaviour.
177
+ const evaluatedRunId = decision.runId ?? runId
178
+ const final: ToolGuardDecision = coerced === decision
179
+ ? decision
180
+ : { ...coerced, rule: decision.rule, transition: decision.transition, runId: evaluatedRunId }
181
+ // T15 (C/D): every decision is logged — allows included — so the rolling trace shows
182
+ // what the guard decided AND why, not only refusals. File-backed evidence in the
183
+ // control-plane config dir: zero session-event emission.
184
+ if (root) {
185
+ const record: GuardDecisionRecord = {
186
+ at: new Date().toISOString(),
187
+ runId: evaluatedRunId,
188
+ tool: (exec as { name?: string } | null)?.name ?? '',
189
+ kind: final.kind,
190
+ rule: final.rule ?? 'none',
191
+ }
192
+ if (final.kind === 'allow') {
193
+ if (final.warn) record.reason = final.warn
194
+ } else if (final.reason) {
195
+ record.reason = final.reason
196
+ }
197
+ if (final.transition) record.transition = final.transition
198
+ // FU-7: a refusal a person has to resolve carries its options into the trace too, so the
199
+ // question "why was this lock refused?" and the answer to it are read from one record.
200
+ if (final.kind === 'deny' && final.ask) record.ask = final.ask
201
+ appendGuardDecision(root, record)
202
+ }
203
+ return final
204
+ }
205
+
206
+ /**
207
+ * ISSUE 1 — THE GOAL BLOCK, FROM THE LAYER THAT REFUSED.
208
+ *
209
+ * WHERE THIS BELONGS, decided from the code rather than assumed: the GUARD CANNOT DO THIS ITSELF.
210
+ * `evaluateToolGuard` is a pure policy layer — it takes an exec, a worktree root, a run id and a mode, and
211
+ * it has no goals service, no live agent and no runtime handle; it is also called from a dry-run preview
212
+ * (`src/recursive_preview.tool.ts`), where a side effect would be a lie about a call that never happened.
213
+ * The ONE place where a guard refusal becomes real is the `tools/pre-execute` listener below: it holds the
214
+ * runtime (which owns `blockRunToGoal` and the late-attached goals service), the live agent from the exec
215
+ * payload, and the decision itself — and it is the same boundary that already renders the refusal's ask
216
+ * into the caller's text (FU-7). So this is called there, and nowhere else.
217
+ *
218
+ * WHY IT IS NEEDED AT ALL. `lockArtifact` blocks the run's goal when its OWN ordering check refuses
219
+ * (`runtime.ts`, the `Prerequisite blockers:` branch). Under the strict default the guard refuses an
220
+ * out-of-order lock BEFORE DISPATCH, so `lockArtifact` never runs, its block never happens, and the run was
221
+ * told it was blocked while the goal machinery was not — the goal stayed armed and kept driving rounds
222
+ * through a refused gate.
223
+ *
224
+ * ⚠ WHY THIS CANNOT DOUBLE-BLOCK. The two block sites are on MUTUALLY EXCLUSIVE branches of one call:
225
+ * this one runs only when the guard DENIED (so the tool is never dispatched), and the tool's own block runs
226
+ * only when the guard let the call through to `lockArtifact`. One refusal, one dispatch decision, one
227
+ * block. A repeat of the SAME refused call re-enters this branch, and the second block is refused by the
228
+ * goal service itself (`block` requires an ACTIVE goal; an already-blocked goal is not active), which is
229
+ * swallowed here exactly as the tool path swallows it — the goal stays blocked, and it is not blocked
230
+ * twice.
231
+ *
232
+ * ⚠ THE TRIGGER IS THE ASK, NOT THE RULE LABEL — the same trigger FU-7 uses, for the same reason: an ask is
233
+ * present exactly when the refusal was DECIDED FROM REAL ORDERING BLOCKERS (`PolicyDecision.blockers` read
234
+ * from disk), which includes a policy FILE whose `recursive_lock*` deny carries no label (its `rule` reads
235
+ * `none`). Gating on the label instead would silently skip the goal block in every repo that ships a policy
236
+ * file — the shipped default here.
237
+ *
238
+ * ⚠ AND IT IS THE LOCK ORDERING REFUSAL ONLY. The phase-order WRITE rule refuses a write ahead of the
239
+ * active phase, and it has NO tool-layer counterpart that blocks a goal — `lockArtifact` is the only
240
+ * tool-side blocker in the plugin. Blocking a goal on it would be a NEW behaviour, not the consistency this
241
+ * fix is for: the defect was one refusal with two layers disagreeing, not a rule that should start
242
+ * blocking.
243
+ */
244
+ function blockGoalOnGuardRefusal(
245
+ recursive: RecursiveRuntime,
246
+ exec: unknown,
247
+ decision: ToolGuardDecision,
248
+ activeRunId: string,
249
+ ): void {
250
+ if (decision.kind !== 'deny' || decision.ask === undefined) return
251
+ const agent = (exec as { agent?: { session?: { header?: { cwd?: string } } } } | null)?.agent ?? null
252
+ // Best-effort, exactly like the tool path: the run's filesystem state is the source of truth and a goal
253
+ // projection that cannot be written must never turn a refusal into a different refusal.
254
+ try {
255
+ recursive.blockRunToGoal(agent, decision.runId ?? activeRunId, {
256
+ // The SAME code the tool path uses, because it is the same gate: a caller reading a blocked goal
257
+ // cannot tell which layer refused, and must not have to.
258
+ code: 'prerequisite-blockers',
259
+ message: decision.reason ?? 'the lock was refused: its prerequisites are unmet',
260
+ })
261
+ } catch {
262
+ /* best-effort */
263
+ }
264
+ }
265
+
266
+ export function apply(ctx: Context, config?: RecursiveModeConfig) {
267
+ // R4 shell split (02-to-be-plan.addendum-r4-r2-mount-resolution.md): the
268
+ // global bare-name row in cordis.patch.yml mounts with config.shellOnly=true
269
+ // to expose ONLY the client bundle for client discovery. It must register
270
+ // NOTHING on the server root — no tools, no /recursive command, no
271
+ // recursive:policy, no projection (BUG 4 always-on leak). The full server
272
+ // surface is mounted ONLY by the recursive preset's isolated recursive-realm,
273
+ // whose rows carry no config (shellOnly undefined).
274
+ if (config?.shellOnly) return
275
+ ctx.effect(function* () {
276
+ // Workspace registry: optional host service (durable). Access via ctx.get —
277
+ // property access requires inject and would fail boot when undeclared.
278
+ // Resolve the control-plane root strictly from the session agent's cwd.
279
+ const workspaceRegistry = ctx.get('workspaceRegistry') as never
280
+ // T1 (goals projection): the goals service is on the host plane; it resolves
281
+ // from inside the recursive-realm via inheritance (same as workspaceRegistry).
282
+ // SAFETY: the goals service is an optional host service (could be absent); the
283
+ // run projection treats null as "no goal backing" and never throws.
284
+ const goals = ctx.get('goals') as GoalServiceLike | null
285
+ // T10: the native jobs registry, when the composition mounts one. OPTIONAL on purpose —
286
+ // a long operation must still run, and say it was untracked, rather than fail because no
287
+ // board is attached.
288
+ const jobs = ctx.get('jobs') as JobsRegistryLike | undefined
289
+ // T39: the subagents seam is resolved HERE, at the composition, so the runtime can fall back
290
+ // to it when a caller passes none. Measured reason: `recursive_review.tool.ts` — the only
291
+ // production caller of `delegateReview` — passes no seam, and the runtime then reported
292
+ // "no ctx.subagents runtime available" on a host that had mounted it all along.
293
+ const subagentsSeamForRuntime = ctx.get('subagents') as SubagentsRuntimeLike | undefined
294
+ const recursive = new RecursiveRuntime(ctx, { repoRoot: config?.repoRoot ?? process.cwd(), workspaceRegistry, goals, jobs, subagents: subagentsSeamForRuntime ?? null, workflow: ctx.get('workflow') as WorkflowEngineLike | undefined ?? null })
295
+ // ⚠ FU-9 — AND RESOLVE IT AGAIN WHENEVER THE SERVICE APPEARS, because the one-shot get above is only a
296
+ // fast path. A live run proved the cost of relying on it: the review fell back to self-audit and reported
297
+ // `Status: failed` while a child DIRECTORY sat there — written by this plugin's own brief writer, before
298
+ // any service call — so the artifact looked like a started child and was not. `ctx.inject` is the
299
+ // harness's own pattern for a service that may be mounted by a later layer, and it fires immediately when
300
+ // the service is already present, so this is a guarantee rather than a second chance.
301
+ ctx.inject(['subagents'], (subagentsCtx: Context) => {
302
+ recursive.attachSubagents((subagentsCtx.get('subagents') as SubagentsRuntimeLike | undefined) ?? null)
303
+ })
304
+ // ⚠ FU-19 — AND THE LLM INVENTORY, the same late-attaching way: `ctx.llm` is what the browser model catalog is
305
+ // built from, so it is the service that knows which providers and models this host actually has. Resolved
306
+ // optionally — a host without it gets the `unverified` verdict rather than a silent approval.
307
+ const llmInventory = ctx.get('llm') as LlmInventoryLike | undefined
308
+ recursive.attachLlmInventory(llmInventory ?? null)
309
+ ctx.inject(['llm'], (llmCtx: Context) => {
310
+ recursive.attachLlmInventory((llmCtx.get('llm') as LlmInventoryLike | undefined) ?? null)
311
+ })
312
+ // ⚠ PHASE 0 — THE HUMAN-QUESTION CHANNEL, resolved the same late-attaching way for the same reason:
313
+ // a composition may mount `userQuestions` after this plugin applies, and the run-start gate asks the
314
+ // person DIRECTLY through it before it arms a goal — which is what keeps a relayed `Start run` from
315
+ // being an approval while a person can actually be asked (see run-start.ts).
316
+ recursive.attachUserQuestions((ctx.get('userQuestions') as UserQuestionsLike | undefined) ?? null)
317
+ ctx.inject(['userQuestions'], (questionsCtx: Context) => {
318
+ recursive.attachUserQuestions((questionsCtx.get('userQuestions') as UserQuestionsLike | undefined) ?? null)
319
+ })
320
+
321
+ // T7 — THE SETTINGS NAMESPACE, APPLIED ON EVERY APPLY. The settings service edits the
322
+ // Loader entry's config and the Loader RE-APPLIES this plugin, so a toggle in the UI
323
+ // lands on this line: the re-application IS the hot reload, and there is deliberately
324
+ // no watcher or file poller here to drift out of sync with it.
325
+ //
326
+ // Guarded on PRESENCE rather than truthiness: `enforcement: undefined` means "the
327
+ // caller said nothing", which must leave the runtime's own default alone, while an
328
+ // explicit object — including one whose fields the schema defaulted — is a decision.
329
+ // Validation stays in `resolveEnforcementConfig` (strict, fail-loud), so a bad value
330
+ // from any source is refused rather than coerced.
331
+ if (config?.enforcement !== undefined) recursive.setEnforcementConfig(config.enforcement)
332
+
333
+ // T12 — publish each phase's rules to the native SKILL catalogue, so the agent and its
334
+ // children can ASK what a phase requires instead of grepping this checkout. The catalogue is
335
+ // optional; with none mounted this registers nothing and says so, because a composition
336
+ // without skills should still run the workflow.
337
+ const phaseSkills = registerPhaseSkills(ctx.get('skills') as SkillRegistryLike | undefined, PHASE_SEQUENCE)
338
+ // Tied to this plugin's effects: the contribution is withdrawn with the fiber that made it.
339
+ yield () => { for (const dispose of phaseSkills.disposers) dispose() }
340
+
341
+ // T7 part 2 — the ROUTER overrides, on the same terms: present means override, absent
342
+ // means defer to the workspace's declarative `recursive-router.json`. ONE PATH, NOT
343
+ // TWO: this does not replace the file, it lays over it (see `loadRouterPolicy`).
344
+ if (config?.router !== undefined) recursive.setRouterOverrides(config.router)
345
+
346
+ const repairedRoots = new Set<string>()
347
+ const reminderGate = new ReminderOnceGate()
348
+ // T3 (agentTeams task loop): wire the live ctx.agentTeams service (optional —
349
+ // absent in compositions without the experimental agent-team row) into the
350
+ // turn-driven task-board tool. The whole-loop driver (auditToPass) is also
351
+ // exported for callers with a settlement observer.
352
+ // SAFETY: ctx.get returns the live service as an opaque value; the single
353
+ // boundary cast asserts it satisfies the TeamRuntimeLike structural seam
354
+ // (createTask/updateTask plus optional wait/interrupt/board reads). The
355
+ // live service's real Agent parameter is a superset of TeamCallerHandle, so
356
+ // the seam passes the exact live Agent the tool extracts from exec.agent.
357
+ const agentTeams = ctx.get('agentTeams') as TeamRuntimeLike | undefined
358
+ // T36: the continuable-subagent seam the review tool drives. Optional for the
359
+ // same reason as agentTeams — absent it, `recursive_review` still runs and
360
+ // reports `unavailable`, naming that the repair path does not exist rather than
361
+ // pretending the review was a success.
362
+ const subagentsSeam = subagentsSeamForRuntime
363
+
364
+ // Packaged skill (dsh plugin standard): register the `recursive-mode` skill
365
+ // into the host skills registry via ctx.skills.registerProvider (the
366
+ // dsh-skill-badge bundled-provider shape). Optional — a composition without
367
+ // a skills registry is valid and this no-ops (returns undefined).
368
+ const skillDisposer = registerRecursiveSkill(ctx)
369
+
370
+ const disposers = [
371
+ ...(skillDisposer ? [skillDisposer] : []),
372
+ ctx.tools.register(createRecursiveStatusTool(recursive)),
373
+ ctx.tools.register(createRecursiveInitTool(recursive)),
374
+ ctx.tools.register(createRecursiveLockTool(recursive)),
375
+ ctx.tools.register(createRecursiveLintTool(recursive)),
376
+ ctx.tools.register(createRecursiveCloseoutTool(recursive)),
377
+ ctx.tools.register(createRecursiveScratchTool(recursive)),
378
+ ctx.tools.register(createRecursiveWorktreeTool(recursive)),
379
+ ctx.tools.register(createRecursivePhaseTool(recursive)),
380
+ ctx.tools.register(createRecursiveReviewTool(recursive, subagentsSeam)),
381
+ // ⚠ FU-17 — WORK delegation: the main agent hands a phase's actual work to a child, reads it, and sends
382
+ // feedback to the same child. Registered beside the review tool because they share the round driver, the
383
+ // settlement observer and the reply contract — the difference is what a settlement MEANS.
384
+ ctx.tools.register(createRecursiveDelegateTool(recursive, subagentsSeam)),
385
+ // T23: the three human gates as structured decisions. Registered here so the ask is a TOOL call
386
+ // — which is what the host renders as a card — rather than prose a person has to interpret.
387
+ ctx.tools.register(createRecursiveAskTool(recursive)),
388
+ // T26: the read-only view of what the enforcement contract will do, before it fires.
389
+ ctx.tools.register(createRecursivePreviewTool(recursive)),
390
+ ]
391
+
392
+ // ⚠ FIX 1 — THE THIRD SEAM NEEDED THE SAME LATE ATTACH AS THE OTHER TWO, AND DID NOT HAVE IT.
393
+ //
394
+ // The line that used to sit in the array above was `...(agentTeams ? [register(...)] : [])` — a ONE-SHOT
395
+ // `ctx.get('agentTeams')` taken at apply time. A live verification pass found the consequence: `team_task_create`
396
+ // worked in the same session whose tool catalog lacked `recursive_audit_team`, because the service was mounted
397
+ // AFTER this plugin applied. The plugin shipped 13 tool files and offered 12.
398
+ //
399
+ // `subagents` and `llm` already solve this with `ctx.inject` (above); this is that pattern, with one addition the
400
+ // others do not need: the tool may only be registered ONCE, because the one-shot path can already have taken it.
401
+ let auditTeamRegistered = agentTeams !== undefined && agentTeams !== null
402
+ if (auditTeamRegistered) disposers.push(ctx.tools.register(createRecursiveAuditTeamTool(agentTeams ?? null)))
403
+ ctx.inject(['agentTeams'], (teamCtx: Context) => {
404
+ if (auditTeamRegistered) return
405
+ const late = teamCtx.get('agentTeams') as TeamRuntimeLike | undefined
406
+ if (late === undefined || late === null) return
407
+ auditTeamRegistered = true
408
+ // ⚠ CORRECTED COMMENT. This registers through the OUTER plugin context (`ctx`), NOT through the
409
+ // injecting `teamCtx` — `teamCtx` is used on the line above only to READ the late service, and the
410
+ // sibling `subagents`/`llm` injects use their callback context the same way. The comment that used to
411
+ // sit here claimed the injecting scope owned the registration, which is not what this call does.
412
+ //
413
+ // WHAT IS NOT CLAIMED: that the fiber withdraws this registration. Nobody has observed that — no test
414
+ // covers the late `recursive_audit_team` being withdrawn — and the disposer returned here is not
415
+ // retained, unlike the eager registration above, which pushes its own onto `disposers`. Until a test
416
+ // observes the withdrawal, this comment promises nothing about it.
417
+ ctx.tools.register(createRecursiveAuditTeamTool(late))
418
+ })
419
+
420
+ // /recursive command (R4): preset-scoped registration, workspace-scoped dispatch.
421
+ const commands = ctx.get('commands') as { register: (def: unknown) => () => void } | undefined
422
+ if (commands) {
423
+ disposers.push(registerRecursiveCommand({ commands } as never, recursive))
424
+ }
425
+
426
+ // recursive:policy prompt section (Phase C R5): workspace-scoped behavior +
427
+ // current-phase contract rendered from folded state + enforcement config.
428
+ const systemPrompt = ctx.get('systemPrompt') as { section: (def: unknown) => () => void } | undefined
429
+ if (systemPrompt) {
430
+ disposers.push(systemPrompt.section({
431
+ name: 'recursive:policy',
432
+ order: 55,
433
+ text: (context: unknown) => {
434
+ const agent = (context as { agent?: { session?: { header?: { cwd?: string } } } } | undefined)?.agent
435
+ if (!agent) return ''
436
+ // SP3 R5 policy-render fix: derive intent from the FILESYSTEM, not the
437
+ // retired recursive/phase-intent session event (zero-emission removed
438
+ // the emitter; 0.2.2 deleted the event-fold helper that read it, so this
439
+ // signal was ALWAYS null and this section rendered ''). Pure read-only fs
440
+ // folding; no recursive/*
441
+ // events are appended.
442
+ const intent = fsPolicyIntent(agent, workspaceRegistry as never)
443
+ if (!intent) return ''
444
+ return renderRecursivePolicy({ worktreeRoot: intent.worktreeRoot, runId: intent.runId, config: recursive.enforcementConfig })
445
+ },
446
+ }))
447
+ }
448
+
449
+ // Phase C R3 (Layer 1, agent/pre-step proactive intent gate) is RETIRED
450
+ // under zero-emission (SP2 R1): its only signal was the recursive/phase-intent
451
+ // session event, whose emitter is now deleted, and it was ADVISORY by default
452
+ // (it never rejected; its sole side effect was the now-removed emission).
453
+ // Enforcement is preserved where it actually bites: Layer 2 (tools/pre-execute
454
+ // inspects the REAL tool call args below) plus the recursive_lock tool's own
455
+ // prerequisite validation in lockArtifact — strictly more reliable than the
456
+ // heuristic intent scan. See 03-implementation-summary.addendum-r1-*.md.
457
+
458
+ // Phase C R4: tools/pre-execute surgical guards (Layer 2, caller of the
459
+ // transition set). Scope-filtered to the active run's worktree.
460
+ //
461
+ // T15 — this listener used to hand `evaluateToolGuard` an EMPTY runId, so its
462
+ // `runDir` resolved to `<root>/.recursive/run` — the directory that holds run
463
+ // DIRECTORIES, not artifacts. The monotonic lock-order and Phase-3 TDD
464
+ // branches could therefore never fire; only the locked-write branch worked
465
+ // (it resolves its target path directly). The REAL active run id is now
466
+ // resolved per call, the same way recursive_status/phaseRules do it.
467
+ const sessionsStore = ctx.get('sessions') as
468
+ | { get?: (id: string) => { header?: { cwd?: string } } | undefined }
469
+ | undefined
470
+ // T38 — THE BUILT-IN GUARD IS NOW A HOOK ON THE SAME CHAIN AS EVERYONE ELSE.
471
+ //
472
+ // Registered at PRIORITY 0 so a sibling with a higher priority runs FIRST and can
473
+ // pre-empt it cheaply — which is the point of participation. The guard stays the
474
+ // baseline that runs when nobody objects.
475
+ //
476
+ // `fail_closed` because this is a GATING point: a guard that cannot decide must not
477
+ // let the call through. The FULL decision rides back as an annotation, so `ask` and
478
+ // `allow` survive with `warn`/`rule`/`transition` intact — the listener returns that
479
+ // object VERBATIM, which is what keeps `guard-path` byte-identical.
480
+ recursive.hooks.register('pre_trigger', {
481
+ name: BUILTIN_GUARD_HOOK_NAME,
482
+ priority: 0,
483
+ onError: 'fail_closed',
484
+ run: (input) => {
485
+ const payload = input as { exec?: unknown; root?: string; runId?: string }
486
+ const decision = runToolGuard(recursive, payload.exec, payload.root ?? '', payload.runId ?? '')
487
+ return decision.kind === 'deny'
488
+ ? { decision: 'deny' as const, reason: decision.reason ?? 'denied by the tool guard', annotations: { guardDecision: decision } }
489
+ : { decision: 'continue' as const, annotations: { guardDecision: decision } }
490
+ },
491
+ })
492
+ // T13 (part 2) — THE PLAN GATE IS LIVE. `exit_plan_mode` is the event that leaves plan mode,
493
+ // so it is where the gate belongs: a run still waiting on a DISCOVERY phase must not leave
494
+ // plan mode, because that would start implementing on an unfinished plan. The gate reads the
495
+ // phase the run is already waiting on rather than keeping its own state, which is why it
496
+ // cannot drift from the workflow.
497
+ //
498
+ // Priority 5, ABOVE the built-in tool guard at 0: this is a workflow-shaped refusal and
499
+ // should be the reason a caller sees, not something the generic guard has to restate.
500
+ recursive.hooks.register('pre_trigger', {
501
+ name: 'exit-plan-mode-gate',
502
+ priority: 5,
503
+ onError: 'fail_closed',
504
+ run: (input) => {
505
+ const payload = input as { tool?: string; root?: string; runId?: string }
506
+ if (payload.tool !== 'exit_plan_mode') return { decision: 'continue' as const }
507
+ const root = payload.root ?? ''
508
+ const runId = payload.runId ?? ''
509
+ if (root === '' || runId === '') return { decision: 'continue' as const }
510
+ const gate = planGateForExit(getNextLegalPhase(join(root, '.recursive', 'run', runId)))
511
+ return gate.allow
512
+ ? { decision: 'continue' as const, annotations: { planGate: gate.reason } }
513
+ : { decision: 'deny' as const, reason: gate.reason }
514
+ },
515
+ })
516
+ const toolRuntime = ctx as unknown as { on?: (event: string, listener: (payload: unknown, next?: unknown) => unknown) => () => void }
517
+ if (toolRuntime.on) {
518
+ disposers.push(toolRuntime.on('tools/pre-execute', async (payload, next) => {
519
+ const exec = payload as { name?: string; arguments?: unknown; agent?: { session?: { header?: { cwd?: string } } } | null } | null
520
+ if (!exec?.name) return typeof next === 'function' ? next() : { kind: 'allow' }
521
+ // B3: per-call root is the session cwd (authoritative when the registry is
522
+ // absent), never process.cwd().
523
+ const cwd = exec?.agent?.session?.header?.cwd ?? ''
524
+ const root = (await recursive.resolveRootForRoute(undefined, cwd, sessionsStore)) ?? cwd
525
+ // T15 (A): the active run id is resolved from the FILESYSTEM on every call
526
+ // — `resolveRunDir` is the canonical latest-run-by-mtime used by
527
+ // recursive_status/phaseRules. Deliberately NO ttl/time cache: a cached run
528
+ // id would silently reintroduce exactly the empty-runId bug being fixed
529
+ // here, because a run created moments ago must be visible immediately. If a
530
+ // cache is ever added it must be provably invalidated on run creation.
531
+ const runId = root ? resolveRunDir(root)?.runId ?? '' : ''
532
+
533
+ // T27 — THE NAMED POINT IS LIVE AT THE ENFORCEMENT SEAM. A sibling hook may
534
+ // deny here BEFORE the built-in guard runs, so participation is real rather
535
+ // than a reachable registry that nothing consults.
536
+ //
537
+ // With no hooks registered — the ordinary case — the chain returns `continue`
538
+ // and the guard below runs exactly as it always has, which is what keeps
539
+ // `guard-path.spec.ts`'s pinned contract byte-identical. That is the point of
540
+ // putting the chain FIRST: it adds a way in without moving what was there.
541
+ //
542
+ // A `hold` is treated as a denial at this seam. `hold` means "stop and wait"
543
+ // for a point that can resume later; a tool call has nothing to resume, so
544
+ // pretending to hold would silently proceed. Better to refuse and say so.
545
+ const preTrigger = await recursive.hooks.run('pre_trigger', {
546
+ tool: exec.name,
547
+ args: exec.arguments,
548
+ exec,
549
+ root,
550
+ runId,
551
+ })
552
+ const decider = preTrigger.ran[preTrigger.ran.length - 1]
553
+
554
+ // A SIBLING stopped the chain. Checked by the DECIDER, not by the built-in's
555
+ // mere absence: a sibling with a LOWER priority than the guard runs after it, so
556
+ // "the guard is in the trail" does not mean "the guard decided".
557
+ if ((preTrigger.decision === 'deny' || preTrigger.decision === 'hold') && decider?.name !== BUILTIN_GUARD_HOOK_NAME) {
558
+ const by = decider?.name ?? 'a pre_trigger hook'
559
+ const why = preTrigger.reason ?? 'no reason given'
560
+ // A `hold` is treated as a refusal at this seam. `hold` means "stop and wait"
561
+ // for a point that can resume later; a tool call has nothing to resume, so
562
+ // pretending to hold would silently proceed — worse than refusing, because the
563
+ // caller would never learn a hook wanted to stop it.
564
+ return {
565
+ kind: 'deny',
566
+ reason: preTrigger.decision === 'hold'
567
+ ? 'held by pre_trigger hook ' + by + ': ' + why
568
+ : 'denied by pre_trigger hook ' + by + ': ' + why,
569
+ }
570
+ }
571
+
572
+ // The guard itself failed: it is fail_closed, so the refusal is reported with
573
+ // its own error rather than as a silent allow.
574
+ if (decider?.name === BUILTIN_GUARD_HOOK_NAME && decider.error !== undefined) {
575
+ return { kind: 'deny', reason: 'the tool guard failed: ' + decider.error }
576
+ }
577
+
578
+ const builtIn = preTrigger.ran.find((entry) => entry.name === BUILTIN_GUARD_HOOK_NAME)
579
+ const final = builtIn?.annotations?.guardDecision as ToolGuardDecision | undefined
580
+ if (final === undefined) {
581
+ // Unreachable while the built-in is registered unconditionally. It fails
582
+ // CLOSED rather than allowing, because "we could not decide" is not permission.
583
+ return { kind: 'deny', reason: 'the tool guard produced no decision' }
584
+ }
585
+ // The guard's own object, returned VERBATIM — the pinned contract.
586
+ //
587
+ // ⚠ EXCEPT THAT A DENIAL'S `ask` MUST BE CARRIED IN THE TEXT, and this is the one place the
588
+ // plugin can do it. Measured in the harness (`packages/core/tools`): a `tools/pre-execute`
589
+ // deny becomes `content: [{ type: 'text', text: 'Error: ' + reason }]` and EVERY other field
590
+ // of the decision is dropped, so the gate-block payload added for FU-7 would have reached the
591
+ // model as nothing at all — which is precisely the defect: a strict-by-default guard refusing
592
+ // a lock with a bare sentence, while `fix | reopen | abandon` was how the run got unblocked.
593
+ // The sentence is rendered FROM the payload (`renderGateBlockAsk`), so what the caller reads
594
+ // and what the decision carries cannot drift; the plain reason stays first and intact, so a
595
+ // caller that ignores the ask still gets the rule name and the blocking artifact.
596
+ if (final.kind === 'deny') {
597
+ // ⚠ ISSUE 1 — THE GUARD-REFUSED LOCK BLOCKS THE RUN'S GOAL, HERE, because this is the layer that
598
+ // made the refusal: the tool is never dispatched, so `lockArtifact`'s own goal block cannot run.
599
+ // Called BEFORE the ask is rendered into the sentence so the durable `blockedReason` is the plain
600
+ // refusal, not the refusal plus its option list. See `blockGoalOnGuardRefusal`.
601
+ blockGoalOnGuardRefusal(recursive, exec, final, runId)
602
+ return final.ask === undefined
603
+ ? final
604
+ : { ...final, reason: final.reason + ' ' + renderGateBlockAsk(final.ask) }
605
+ }
606
+ if (final.kind === 'allow' && final.warn) {
607
+ // ⚠ IT NAMES THE MODE IT ACTUALLY RAN UNDER. This line used to begin `tool guard (advisory)`
608
+ // unconditionally, while the warning it carries comes from the transition gate's REPORT-ONLY
609
+ // consult — which attaches a warning to an ALLOW in BOTH modes. Under the strict default the
610
+ // line therefore told a reader that enforcement was off while every gate was strict: text
611
+ // asserting a state that was not so. The mode is read from the same config the guard ran
612
+ // under, so the prefix moves with the setting; the warn semantics are unchanged.
613
+ console.warn('[recursive] tool guard (' + recursive.enforcementConfig.toolGuards + ') allowed this call: ' + final.warn)
614
+ }
615
+ return typeof next === 'function' ? next() : { kind: 'allow' }
616
+ }))
617
+ }
618
+
619
+ // T15 (E): the fs/observed lock-tamper path. The harness contract is a plain
620
+ // SYNCHRONOUS emit fired AFTER a successful write, so this listener cannot
621
+ // veto anything and contractually must not throw — it only RECORDS. Before
622
+ // T15 the plugin had no fs/observed listener at all (the string appeared in
623
+ // comments only), so `detectTamper` was exported and unit-tested with no live
624
+ // caller and a tampered lock surfaced nowhere but prompt text.
625
+ const observationRuntime = ctx as unknown as { on?: (event: string, listener: (target: unknown, observation: unknown, actor: unknown) => void) => () => void }
626
+ if (observationRuntime.on) {
627
+ disposers.push(observationRuntime.on('fs/observed', (target, observation, actor) => {
628
+ try {
629
+ // Only a present observation can be a tamper; absent/unrelated are ignored.
630
+ if ((observation as { kind?: string } | null)?.kind !== 'present') return
631
+ const displayPath = (target as { displayPath?: string } | null)?.displayPath ?? ''
632
+ if (!displayPath) return
633
+ // Cheap shape test BEFORE any filesystem work: fs/observed fires on reads
634
+ // too, so enumerating runs for every observation would be a readdir per
635
+ // file touch. The actor is the tool execution. This event cannot await, so
636
+ // the root is the actor's session cwd (the same B4 sync shortcut
637
+ // fsPolicyIntent takes: the session cwd is authoritative, the registry
638
+ // path is async-only). Resolving the cwd first is free — plain property
639
+ // reads — and the admission test needs it.
640
+ const cwd = (actor as { agent?: { session?: { header?: { cwd?: string } } } } | null)?.agent?.session?.header?.cwd ?? ''
641
+ if (!cwd) return
642
+ // ⚠ AND THIS IS `detectTamper`'s OWN ADMISSION TEST, CALLED RATHER THAN COPIED.
643
+ //
644
+ // It used to be an inline hand-copy — `endsWith('.md') && includes('/.recursive/run/')`
645
+ // — and a hand-copy is what made the tamper guard blind to one spelling of one
646
+ // path: the substring test needs a separator BEFORE `.recursive`, which a
647
+ // repo-relative target (`displayPath` as a model would type it) does not have, so
648
+ // the listener rejected the candidate here and `detectTamper` was never reached.
649
+ // Widening only `detectTamper` would have changed nothing observable. The test now
650
+ // lives in one place (`tamperCandidatePath`), so the two cannot disagree; it stays
651
+ // pure path arithmetic, so the "no filesystem work before admission" property the
652
+ // shape check exists for is preserved.
653
+ const normalized = displayPath.replace(/\\/g, '/')
654
+ if (!tamperCandidatePath(normalized, cwd)) return
655
+ const runId = resolveRunDir(cwd)?.runId ?? ''
656
+ const tamper = recursive.detectTamper(normalized, cwd, runId)
657
+ if (!tamper) return
658
+ appendObservedTamper(cwd, {
659
+ at: new Date().toISOString(),
660
+ runId: tamper.runId,
661
+ path: tamper.path,
662
+ reason: tamper.reason,
663
+ })
664
+ } catch {
665
+ // Observe-only: the fs/observed contract forbids throwing.
666
+ }
667
+ }))
668
+ }
669
+
670
+ // T36: capture a delegated child's SETTLEMENT at delivery time.
671
+ //
672
+ // WHY DELIVERY AND NOT HISTORY. The obvious implementation of a parent-side
673
+ // settlement observer is to scan the session log for the `subagent-settled`
674
+ // notice. That is prohibited: DSH deprecates synchronous reads of arbitrary
675
+ // session history (`eventAt`/`snapshotEvents`/`ownEvents`) and states that new
676
+ // production calls are prohibited, enforced by an executable lint check. The
677
+ // sanctioned replacement is to process the DELIVERED event, which is this
678
+ // listener — the same `session/event` seam the projection registry subscribes
679
+ // to. The durable fact then lands in the run's own FILE state, which is where
680
+ // every other plugin fact lands and keeps the plugin zero-emission.
681
+ //
682
+ // The loop needs this because there is NO parent-side promise to await: a
683
+ // continuable child's settlement arrives as a durable user message on a later
684
+ // turn, so the round observer must find a recorded settlement or honestly
685
+ // report that none has landed yet.
686
+ const sessionRuntime = ctx as unknown as { on?: (event: string, listener: (session: unknown, event: unknown) => void) => () => void }
687
+ if (sessionRuntime.on) {
688
+ disposers.push(sessionRuntime.on('session/event', (session, event) => {
689
+ try {
690
+ // Cheap shape test FIRST: session/event fires for EVERY committed event
691
+ // in every session, so a non-settlement must be rejected before any
692
+ // filesystem work. This is the same ordering the fs/observed listener
693
+ // uses, for the same reason.
694
+ const notice = settlementFromEvent(event as never)
695
+ if (notice === null) return
696
+ // B3: the session cwd is the authoritative control-plane root per call.
697
+ const cwd = (session as { header?: { cwd?: string } } | null)?.header?.cwd ?? ''
698
+ if (cwd === '') return
699
+ const runDir = runDirForChild(cwd, notice.childId)
700
+ // No run (or an ambiguous one) means the settlement is not filed rather
701
+ // than filed wrongly: the loop will report "no settlement yet", which is
702
+ // recoverable, whereas attaching evidence to the wrong run is not.
703
+ if (runDir === null) {
704
+ // ⚠ FU-17 — ADOPT RATHER THAN DROP. The rule above still holds — never guess between runs — but a
705
+ // settlement for a child nobody filed is evidence of work that really happened, and dropping it
706
+ // means a phase artifact cannot cite it. `adoptSettlement` files it into the single run when there
707
+ // is exactly one, and into a root-level adoption log when choosing would mean guessing. Marked as
708
+ // adopted either way, so a reader can tell an adopted record from a delegation's own.
709
+ adoptSettlement(cwd, notice)
710
+ return
711
+ }
712
+ recordSettlement(runDir, notice)
713
+ } catch {
714
+ // Observe-only. This rides the hot path of every session event and must
715
+ // never break the session it observes.
716
+ }
717
+ }))
718
+ }
719
+
720
+ // SP3 R5: agent/pre-step lint-rules injection (pre-step contract verified: the
721
+ // listener returns { kind: 'enter', messages: [...messages, injected] } and the
722
+ // returned array REPLACES the default [...claimed, context]). When the session's
723
+ // control-plane root has an active recursive run whose current phase doc is
724
+ // DRAFT, prepend a compact system-reminder with THAT phase's required sections +
725
+ // gates. Pure fs read (zero-emission): never appends recursive/* events.
726
+ const agentRuntime = ctx as unknown as { on?: (event: string, listener: (payload: unknown, next?: unknown) => unknown) => () => void }
727
+ if (agentRuntime.on) {
728
+ disposers.push(agentRuntime.on('agent/pre-step', async (payload, next) => {
729
+ const p = payload as {
730
+ messages?: Array<{ content: Array<{ type: string; text?: string }> }>,
731
+ agent?: { session?: { header?: { cwd?: string } } } | null,
732
+ } | null
733
+ const messages = p?.messages ?? []
734
+ const agent = p?.agent ?? null
735
+ const cwd = agent?.session?.header?.cwd ?? ''
736
+ // delegate first so later listeners keep veto power, then fold ours on
737
+ if (typeof next === 'function') await next()
738
+ if (!cwd) return { kind: 'enter', messages } as const
739
+ const root = await recursive.resolveRootForRoute(undefined, cwd, undefined)
740
+ if (!root) return { kind: 'enter', messages } as const
741
+ // R3/R6 (run 09): idempotent scaffold REPAIR on session-start (new AND
742
+ // resume). bootstrapScaffold is upsert-only: it adds missing control-plane
743
+ // files/dirs + re-upserts marked blocks, NEVER overwriting user content or
744
+ // touching run/ artifacts (in-flight 02-to-be-plan etc. are preserved).
745
+ // Guarded once per root so repeated pre-steps are cheap no-ops.
746
+ if (!repairedRoots.has(root)) {
747
+ repairedRoots.add(root)
748
+ stageBWorkflowInit({ root, source: 'resume' })
749
+ }
750
+ const runs = enumerateRuns(root)
751
+ if (runs.length === 0) return { kind: 'enter', messages } as const
752
+ const runId = runs[runs.length - 1]
753
+ const runDir = join(root, '.recursive', 'run', runId)
754
+ if (!existsSync(runDir)) return { kind: 'enter', messages } as const
755
+ const phase = getNextLegalPhase(runDir)
756
+ if (!phase) return { kind: 'enter', messages } as const
757
+ // only inject when the phase doc is DRAFT (not locked/missing).
758
+ const phasePath = join(runDir, phase)
759
+ const status = existsSync(phasePath) ? getLockStatus(phasePath) : null
760
+ if (status !== 'DRAFT') return { kind: 'enter', messages } as const
761
+ if (!reminderGate.shouldInject(root, runId, phase)) return { kind: 'enter', messages } as const
762
+ // LIVE BUG 6 (0.2.1): inject the lint-rules reminder AT MOST ONCE PER PHASE.
763
+ // The scaffold repair above is deduped via repairedRoots; the reminder itself was
764
+ // not, so every pre-step while DRAFT re-injected it.
765
+ const reminder = phaseLintRulesMessage(phase)
766
+ return {
767
+ kind: 'enter',
768
+ messages: [...messages, createUserMessage({ content: [{ type: 'text', text: reminder }], source: { ...REMINDER_SOURCE, form: 'notice', summary: 'phase ' + phase + ' lint rules' } })],
769
+ } as const
770
+ }))
771
+ }
772
+
773
+ // Phase C R8: fs/observed lock-tamper WARNINGS are served to the board via the
774
+ // mountOnce-global: apply() runs per-session, but the route must register
775
+ // exactly once (WebServer.register throws on duplicate kind+path) and serve
776
+ // PER-WORKSPACE state. No-op when the host composes no webServer (headless).
777
+ // (`sessionsStore` is resolved once, above the pre-execute listener, which now
778
+ // needs it too.)
779
+ const webServer = ctx.get('webServer') as
780
+ | { register: (route: { kind: string; path: string; handler: unknown }) => () => void }
781
+ | undefined
782
+ if (webServer) {
783
+ const host: RecursiveRouteHost = {
784
+ // sessionId PRIMARY: the host resolves cwd from the attached session header;
785
+ // the client-passed cwd is a fallback hint (hydration / headless).
786
+ resolveRoot: async (sessionId: string | undefined, cwd: string) => recursive.resolveRootForRoute(sessionId, cwd, sessionsStore),
787
+ snapshot: async (root: string) => snapshotWorkspace(root),
788
+ revision: () => 1,
789
+ }
790
+ disposers.push(mountRecursiveRoutesOnce('@try-works/dsh-recursive-mode', () => makeRecursiveRoutes(host), webServer))
791
+ }
792
+
793
+ yield () => { for (const d of disposers) d() }
794
+ })
795
+ }