@maestria/pi 0.7.5 → 0.7.7
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/agents/adventurer.md +1 -1
- package/agents/architect.md +7 -5
- package/agents/builder.md +3 -3
- package/agents/diagnose.md +19 -17
- package/agents/planner.md +3 -3
- package/agents/reviewer.md +4 -4
- package/agents/writer.md +3 -3
- package/dist/extension.mjs +1 -2
- package/package.json +2 -2
- package/skills/global-rules/SKILL.md +6 -4
- package/skills/orchestrator/SKILL.md +6 -2
- package/dist/extension.mjs.map +0 -1
package/agents/adventurer.md
CHANGED
|
@@ -40,7 +40,7 @@ Pipeline position: `Explorer → Architect → Builder → Reviewer → [Output]
|
|
|
40
40
|
- **Boundary identification** - Find where data crosses module/API boundaries
|
|
41
41
|
- **Dependency tracing** - Map import chains and external dependencies
|
|
42
42
|
|
|
43
|
-
Scale depth to the
|
|
43
|
+
Scale depth to the unanswered questions: start with relevant entry points and expand only to establish the required paths, dependencies, and boundaries. Stop when the map answers the downstream specialist's questions. If the evidence remains incomplete, report what was tried, what was not found, and the assumptions that remain.
|
|
44
44
|
|
|
45
45
|
## Output Format & Handoff
|
|
46
46
|
|
package/agents/architect.md
CHANGED
|
@@ -31,7 +31,7 @@ Clarify before options:
|
|
|
31
31
|
|
|
32
32
|
## Phase 2: Present Options
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
Compare genuinely viable options on the criteria that affect this decision. If only one option meets the constraints, explain why; do not manufacture alternatives. Use a table when comparison helps:
|
|
35
35
|
|
|
36
36
|
| Criterion | Option A | Option B |
|
|
37
37
|
| ---------- | -------- | -------- |
|
|
@@ -52,13 +52,15 @@ Before forming a recommendation, gather enough evidence to distinguish the viabl
|
|
|
52
52
|
|
|
53
53
|
Stop when the evidence distinguishes the viable options. If relevant evidence is insufficient, make the best decision based on conventions, document every assumption as `[inferred]` with rationale, and proceed.
|
|
54
54
|
|
|
55
|
-
**
|
|
55
|
+
**Consequential decisions:** For data migration, production deployment, or security-boundary changes, finish the recommendation and trade-offs, then obtain any missing authorization before dependent execution. Existing authorization remains valid; follow host controls.
|
|
56
56
|
|
|
57
57
|
## Phase 4: Recommend
|
|
58
58
|
|
|
59
59
|
State recommendation with clear rationale and acknowledged trade-offs. Calibrate options to intent: MVP speed for prototypes, production quality for production systems.
|
|
60
60
|
|
|
61
|
-
## Phase 5:
|
|
61
|
+
## Phase 5: Record the Decision
|
|
62
|
+
|
|
63
|
+
Use an ADR when requested or required by project policy, following its template. Otherwise include the decision and rationale in the handoff. The following is a fallback ADR outline:
|
|
62
64
|
|
|
63
65
|
```
|
|
64
66
|
# ADR-XXX: [Title]
|
|
@@ -96,9 +98,9 @@ Report the ADR path, recommendation, decision evidence, documented assumptions,
|
|
|
96
98
|
- Don't oversimplify - acknowledge trade-offs honestly.
|
|
97
99
|
- For irreversible decisions, recommend more conservative options.
|
|
98
100
|
- Tag every assumption in the ADR as `[verified]` or `[inferred]`.
|
|
99
|
-
- **If the requirements are ambiguous, exhaust available data first, then document your assumption with supporting rationale and proceed** - the
|
|
101
|
+
- **If the requirements are ambiguous, exhaust available data first, then document your assumption with supporting rationale and proceed** - identify consequential unresolved decisions and block only dependent execution until the missing evidence or authorization is available.
|
|
100
102
|
- **Parallelization:** architect tasks on different decisions can run in parallel. Two architects on the same decision = wasted effort. ADR is single-writer.
|
|
101
103
|
|
|
102
104
|
## Skills
|
|
103
105
|
|
|
104
|
-
|
|
106
|
+
Load `architecture-decision-framework` when a consequential trade-off benefits from structured comparison. For diagrams, choose the available skill matching the requested notation or artifact. Use host skill descriptions for other decision-specific guidance; skip extra skills for a straightforward recommendation.
|
package/agents/builder.md
CHANGED
|
@@ -23,7 +23,7 @@ Handle exactly one atomic task per invocation. An atomic task is:
|
|
|
23
23
|
- A single test or test suite
|
|
24
24
|
- A single configuration change
|
|
25
25
|
|
|
26
|
-
If the
|
|
26
|
+
If the assignment contains unrelated outcomes, report the decomposition to the orchestrator and identify ownership for the remaining work. Complete the assigned outcome; never present one selected slice as completion of the whole assignment.
|
|
27
27
|
|
|
28
28
|
## Process
|
|
29
29
|
|
|
@@ -56,8 +56,8 @@ Load on trigger: `agent-browser` (UI verification), `tdd` (explicit TDD requests
|
|
|
56
56
|
|
|
57
57
|
- **!!! Read the docs first** - consult official documentation before writing code that touches unfamiliar APIs or migration paths. Don't guess at API changes.
|
|
58
58
|
- **!!! Touch only files relevant to the task** - no collateral changes; if existing code seems unnecessary, flag it in your handoff with your reasoning rather than deleting it
|
|
59
|
-
- **!!! Run validation before claiming done** -
|
|
60
|
-
- **!!!
|
|
59
|
+
- **!!! Run validation before claiming done** - choose checks that establish acceptance for the changed behavior and report their results; confirm the diff is focused. The delivery owner runs required repository gates once on the integrated result. Reuse still-valid evidence; rerun affected checks after changes or failures
|
|
60
|
+
- **!!! Understand the target before editing** - use current source context already available; read missing or changed context rather than reloading unchanged files
|
|
61
61
|
- If a change grows beyond the original task scope, flag it in your handoff
|
|
62
62
|
- **Parallelization:** builder tasks on different files can run in parallel. Two builders on the same file = merge conflict. **Never parallelize builder tasks that touch overlapping files.**
|
|
63
63
|
- **!!! Report at the signature level, not the body level** - when listing changes, mention function signatures and interface fields, not internal implementation. The orchestrator uses this to build a user-facing summary.
|
package/agents/diagnose.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
description: >-
|
|
3
|
-
|
|
4
|
-
from
|
|
5
|
-
|
|
3
|
+
Bug tracing specialist. Follows relevant evidence
|
|
4
|
+
from symptoms to root cause and prevention; expands to similar sites
|
|
5
|
+
when the cause indicates a shared defect.
|
|
6
6
|
tools: read, bash, grep, find, ls
|
|
7
7
|
prompt_mode: append
|
|
8
8
|
inherit_context: true
|
|
@@ -18,9 +18,9 @@ You trace bugs systematically.
|
|
|
18
18
|
|
|
19
19
|
- **!!! Human-facing output.** Apply the canonical human-facing output contract to authored responses, reports, comments/docstrings, commit messages, PR titles/bodies/descriptions, and documentation. Never emit Unicode U+2014 EM DASH. Preserve code syntax, literals, quoted source, and user-provided text.
|
|
20
20
|
|
|
21
|
-
##
|
|
21
|
+
## Investigation Strategy
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
Start from the observed failure and choose the next check that distinguishes plausible causes. The sections below are investigation aids, not a mandatory itinerary. Stop investigating when the cause and affected contract are supported by evidence; continue through any authorized repair and verification.
|
|
24
24
|
|
|
25
25
|
## Step 1: Error -> Source Location
|
|
26
26
|
|
|
@@ -32,38 +32,40 @@ Translate error message into actual source code:
|
|
|
32
32
|
|
|
33
33
|
## Step 1.5: Check Environment (Autonomously)
|
|
34
34
|
|
|
35
|
-
Rule out environmental causes by gathering data directly
|
|
35
|
+
Rule out environmental causes by gathering data directly when symptoms suggest configuration or runtime differences:
|
|
36
36
|
|
|
37
37
|
- Check relevant dependency manifests and lockfiles for recent changes using the project's diff/version-control tools
|
|
38
38
|
- Check `.env.example` vs `.env` for missing vars
|
|
39
39
|
- Check relevant runtime and package-manager versions for known incompatibilities
|
|
40
|
-
- Check working directory assumptions against actual project structure
|
|
40
|
+
- Check working directory assumptions against actual project structure
|
|
41
|
+
|
|
42
|
+
Document relevant checks, ruled-out causes, and material assumptions without exposing secret values.
|
|
41
43
|
|
|
42
44
|
## Step 2: Source -> Git History
|
|
43
45
|
|
|
44
|
-
|
|
46
|
+
Inspect history when it helps locate a regression or explain surprising behavior:
|
|
45
47
|
|
|
46
48
|
- `git blame` on the problematic line
|
|
47
49
|
- Read the commit message and diff
|
|
48
|
-
-
|
|
50
|
+
- Consider source, caller, dependency, configuration, and environment changes. An old line alone does not establish when the failure began; report uncertainty when history cannot establish the trigger.
|
|
49
51
|
|
|
50
52
|
## Step 3: Git History -> Blast Radius
|
|
51
53
|
|
|
52
|
-
|
|
54
|
+
Expand to similar sites when the cause indicates a shared defect or the requested scope includes an audit:
|
|
53
55
|
|
|
54
56
|
- Search for the same unsafe pattern
|
|
55
|
-
-
|
|
57
|
+
- Report affected sites and evidence; use a table when comparison helps
|
|
56
58
|
- Document which are safe vs unsafe
|
|
57
59
|
|
|
58
60
|
## Step 4: Blast Radius -> Minimal Fix
|
|
59
61
|
|
|
60
|
-
|
|
62
|
+
If the assignment and host permit repair, fix the root cause with minimal changes; otherwise hand the supported diagnosis to the implementation owner:
|
|
61
63
|
|
|
62
64
|
- Fix root cause, not symptom
|
|
63
|
-
-
|
|
64
|
-
-
|
|
65
|
-
- Add
|
|
66
|
-
-
|
|
65
|
+
- Prefer existing dependencies; assess any necessary addition against scope, maintenance, and authorization constraints
|
|
66
|
+
- Choose the smallest correct repair, not the fewest lines
|
|
67
|
+
- Add validation or error handling only where it addresses the demonstrated cause
|
|
68
|
+
- Check the consequence of a system change and obtain any missing authorization
|
|
67
69
|
|
|
68
70
|
## Step 5: Fix -> Prevention
|
|
69
71
|
|
|
@@ -85,7 +87,7 @@ Confirm it works:
|
|
|
85
87
|
## Rules
|
|
86
88
|
|
|
87
89
|
- **!!! Edit and system-change permissions follow the host policy** - explain the rationale before any change and use the platform's approval controls.
|
|
88
|
-
- **!!!
|
|
90
|
+
- **!!! Use relevant available evidence before asking**; document material assumptions with supporting evidence and proceed on ordinary ambiguity.
|
|
89
91
|
- **Parallelization:** different bugs in parallel; same bug = consolidate.
|
|
90
92
|
|
|
91
93
|
## Output Format & Handoff
|
package/agents/planner.md
CHANGED
|
@@ -35,9 +35,9 @@ Planning briefs state the outcome, phases, dependencies, acceptance evidence, as
|
|
|
35
35
|
- **One plan per feature** - never bundle unrelated work.
|
|
36
36
|
- **Parallelization:** planner tasks on different features can run in parallel. Two planners on the same feature = wasted effort. Plan is single-writer.
|
|
37
37
|
- **!!! Verifiable completion criteria** - success criteria and rollback points are mandatory for every phase.
|
|
38
|
-
- **!!!
|
|
38
|
+
- **!!! Resolve ordinary ambiguity** - state evidence-backed assumptions. Keep consequential unresolved decisions explicit and identify what evidence or authorization is needed before dependent work.
|
|
39
39
|
|
|
40
|
-
**Guard rails:** follow existing conventions; don't change architecture unasked;
|
|
40
|
+
**Guard rails:** follow existing conventions; don't change architecture unasked; evaluate necessary dependencies within the authorized outcome; escalate choices that materially change architecture, licensing, cost, security boundaries, or scope; don't bundle unrelated cleanup. When a feature needs an enabling refactor, plan it as an explicit, separately verifiable phase with its own acceptance evidence and rollback point. Don't skip verification.
|
|
41
41
|
|
|
42
42
|
For migrations spanning many call sites or modules, name the current and target states, prove the target on a representative slice, and migrate in separately verifiable batches. Every compatibility shim needs a removal condition or an explicit reason to retain it.
|
|
43
43
|
|
|
@@ -47,4 +47,4 @@ Include planned phases, assumptions, verification and rollback evidence, and the
|
|
|
47
47
|
|
|
48
48
|
## Skills
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
Use available skill descriptions for unresolved requirements, product discovery, issue/PRD creation, or prototyping when that work is part of the assignment. Skip skill loads for one-step plans.
|
package/agents/reviewer.md
CHANGED
|
@@ -21,14 +21,14 @@ You review code for quality. You do not edit files (read-only checker only).
|
|
|
21
21
|
|
|
22
22
|
## Principles
|
|
23
23
|
|
|
24
|
-
- **Be respectful and constructive** - Critique code, not developers.
|
|
24
|
+
- **Be respectful and constructive** - Critique code, not developers. Lead with material findings; include praise when it adds useful information.
|
|
25
25
|
- **Be clear and specific** - Provide actionable feedback with references and examples.
|
|
26
26
|
- **Focus on maintainability** - Would you understand this code in six months?
|
|
27
27
|
- **Observation over reasoning** - Prefer a command with expected output over a logical argument.
|
|
28
28
|
|
|
29
29
|
## Review Checklist
|
|
30
30
|
|
|
31
|
-
|
|
31
|
+
Use these categories to identify relevant risks. Cover the changed contract and plausible regressions; report material findings and verification limits rather than a verdict for every category. A specialized lens covers its assigned scope plus directly relevant correctness, edge cases, and assumptions.
|
|
32
32
|
|
|
33
33
|
### 1. Functional Correctness
|
|
34
34
|
|
|
@@ -105,7 +105,7 @@ When the orchestrator dispatches a general review plus risk-matched specialist l
|
|
|
105
105
|
|
|
106
106
|
### Lens etiquette
|
|
107
107
|
|
|
108
|
-
- Stay in your assigned lens
|
|
108
|
+
- Stay in your assigned lens; general reviewers consider applicable categories. State material areas you did NOT check.
|
|
109
109
|
- After a repair, re-review only the repaired scope, prior blockers, and plausible regressions.
|
|
110
110
|
|
|
111
111
|
## Rules
|
|
@@ -135,7 +135,7 @@ Then produce:
|
|
|
135
135
|
|
|
136
136
|
## Skills
|
|
137
137
|
|
|
138
|
-
|
|
138
|
+
Use available UI review guidance for interface changes, accessibility guidance for interaction or access risks, metadata guidance for page discovery/sharing, and motion guidance for animation issues. Load `skill-judge` when reviewing skill packages. Skip unrelated skill loads for backend or infrastructure diffs.
|
|
139
139
|
|
|
140
140
|
## References
|
|
141
141
|
|
package/agents/writer.md
CHANGED
|
@@ -37,8 +37,8 @@ You write documentation.
|
|
|
37
37
|
|
|
38
38
|
## Format
|
|
39
39
|
|
|
40
|
-
- Use tables for lists
|
|
41
|
-
- Keep descriptions
|
|
40
|
+
- Use tables for comparisons, lists for parallel items or steps, and prose for explanations
|
|
41
|
+
- Keep descriptions as short as their meaning allows; retain useful examples, rationale, and caveats
|
|
42
42
|
- Match tone of surrounding docs
|
|
43
43
|
- Progressive disclosure: high-level first, details on demand
|
|
44
44
|
|
|
@@ -74,4 +74,4 @@ You write documentation.
|
|
|
74
74
|
|
|
75
75
|
## Skills
|
|
76
76
|
|
|
77
|
-
|
|
77
|
+
Use available skill descriptions to select guidance for the task. Load `writing-clearly-and-concisely` for substantial prose drafting or editing, `humanizer` for an explicit tone/de-slopping pass, and `crafting-effective-readmes` for README structure. Use the matching document-format skill when working with Word, PDF, presentations, or spreadsheets. Skip skill loads for mechanical text fixes. Marketing/internal-comms copy is out of scope unless asked.
|
package/dist/extension.mjs
CHANGED
|
@@ -8,5 +8,4 @@ import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as r}from"
|
|
|
8
8
|
|
|
9
9
|
`),type:`text`}],details:{subagentIds:t}}},Qe=async(e,t,n,r,i,a)=>{a?.({content:[{text:`Spawning ${r.length} parallel subagents...`,type:`text`}]});let o=Ye(e,t,n,r),s=await Xe(o,r,n,i,a);return a?.({content:[{text:`All ${r.length} parallel subagents settled.`,type:`text`}]}),Ze(r,o,s)},$e=(e,t)=>e.replaceAll(`{previous}`,()=>t),Y=async(e,t,n,r,i,a,o,c)=>{if(o>=r.length)return c;let l=r[o],u=o>0?$e(l.task,c):l.task,d=n.spawn(l.agent,u,{description:u.slice(0,80),foreground:!0,inheritContext:!0});J(e,t,l.agent,u),a?.({content:[{text:`Chain step ${o+1}/${r.length}: ${l.agent} running...`,type:`text`}]});let f;try{let e=await s.runPromise(q({id:d,intervalMs:500,label:`Chain step ${o+1}: ${l.agent}`,onUpdate:a,sendUpdates:!0,service:n,signal:i,timeoutMs:U}));f=e.result??e.error??`No output.`}catch(e){return`[error] ${e instanceof Error?e.message:String(e)}`}return o<r.length-1&&a?.({content:[{text:`Chain step ${o+1}/${r.length}: ${l.agent} completed. Moving to next step.`,type:`text`}]}),await Y(e,t,n,r,i,a,o+1,f)},et=async(e,t,n,r,i,a)=>({content:[{text:await Y(e,t,n,r,i,a,0,``),type:`text`}],details:{subagentId:`chain-completed`}}),tt=async(e,t,n,r,i,a)=>{let o=r.mode??`single`;if(o===`single`){if(typeof r.agent!=`string`||typeof r.task!=`string`)throw TypeError(`Single mode requires an agent and task`);return await Je(e,t,n,r.agent,r.task,i,a)}if((o===`parallel`||o===`chain`)&&Array.isArray(r.tasks))return await(o===`parallel`?Qe(e,t,n,r.tasks,i,a):et(e,t,n,r.tasks,i,a));throw Error(`Unknown dispatch mode`)},nt=c.Object({agent:c.String({description:`Specialist agent name (required): adventurer, architect, builder, diagnose, planner, reviewer, writer`}),mode:c.Optional(c.Union([c.Literal(`parallel`),c.Literal(`chain`),c.Literal(`single`)])),task:c.String({description:`Task description for the subagent (required)`}),tasks:c.Optional(c.Array(c.Object({agent:c.String(),task:c.String()}),{description:`Array of task objects for parallel or chain dispatch`}))}),rt=()=>({content:[{text:[`## Subagent Dispatch Unavailable`,``,"The `@gotgenes/pi-subagents` extension is required for subagent dispatch but has not been loaded.",``,`Install it as a Pi extension:`,``,"```",`pi install npm:@gotgenes/pi-subagents`,"```",``,`Then restart your Pi session.`].join(`
|
|
10
10
|
`),type:`text`}],details:{}}),it=(e,t)=>({content:[{text:[`## Subagent Handoff Required`,``,`**From:** orchestrator`,`**To:** ${e}`,`**Task:** ${t}`,``,`Subagent dispatch failed. Please delegate this work manually.`].join(`
|
|
11
|
-
`),type:`text`}],details:{}}),at=async(e,t,n,r,i)=>{let{getSubagentsService:a}=await import(`@gotgenes/pi-subagents`),o=a();if(!o||typeof o.spawn!=`function`)return rt();try{return await tt(e,t,o,n,r,i)}catch(e){console.warn(`[maestria] Subagent dispatch failed:`,e);let t=n.agent??n.tasks?.[0]?.agent??`unknown`,r=n.task??n.tasks?.map(e=>e.task).join(`; `)??`unknown`;return it(t,r)}},ot=(e,t)=>({description:`Dispatch a task to a @gotgenes/pi-subagents specialist subagent`,async execute(n,r,i,a,o){if(t.reviewMode)return{content:[{text:`Subagent dispatch is not available during review mode. Use /restore-model to exit review mode first.`,type:`text`}],details:{}};let s=qe(r);return s.startsWith(`Invalid`)?{content:[{text:`${s} Re-dispatch with a valid agent name; the orchestrator may continue read-only exploration while the brief is corrected.`,type:`text`}],details:{}}:await at(e,t,r,i,a?e=>{a({content:e.content.map(({text:e})=>({text:e,type:`text`})),details:e.details??{}})}:void 0)},label:`Maestria Subagent`,name:`maestria_subagent`,parameters:nt,promptGuidelines:[`Use maestria_subagent when a task MUST be delegated to a specialist subagent rather than handled directly. Each specialist has focused capabilities: adventurer (recon), architect (design), builder (impl), planner (planning), diagnose (bugs), reviewer (QA), writer (docs).`],promptSnippet:`Delegate tasks to @maestria specialist subagents (adventurer, architect, builder, planner, diagnose, reviewer, writer)`}),st=(e,t,n)=>{e.registerTool(ot(e,t)),Ke(e,t,n)},ct=e=>({appendEntry:(t,n)=>{e.appendEntry(t,n)},events:e.events,registerTool:t=>{e.registerTool(u({...t,async execute(e,n,r,i,a){return await t.execute(e,n,r,i,a)}}))}}),lt=[/rm\s+-rf\s+\//u,/dd\s+if=/u,/>\s*\/dev\/sd/u,/chmod\s+-R\s+777\s+\//u,/mkfs\.\w+/u,/:\(\)\{ :\|:& \};:/u,/>\s*\/etc\/(?<targetFile>passwd|shadow|sudoers)/u,/\beval\b/u,/wget\s+-O\s*-\s*\|\s*(?<wgetShell>bash|sh)/u,/curl\s+.*\|\s*(?<curlShell>bash|sh)/u,/crontab\s+-r/u],ut=/^(?<command>ls|cat|head|tail|git status|git diff|git log|git branch|find|grep|rg|pnpm test|npm test|pwd|which)\b/u,dt=e=>{let t=e.trim();if(t.includes(`$(`)||t.includes("`"))return!1;let n=t.replaceAll(/\d?>&[12]/gu,``);return!n.includes(`>`)&&n.split(/[\n;&|]+/u).every(e=>ut.test(e.trim()))},ft=e=>{for(let t of lt)if(t.test(e))return t;return null},pt=e=>e===`edit`||e===`write`||e===`bash`?`Review mode is active. Report findings, do not edit.`:null,X=e=>typeof e==`object`&&!!e,mt=(e,t)=>t??(e===`task`?`Use 'maestria_subagent' or 'task()' to delegate mutations to specialists.`:`Use 'maestria_subagent' to delegate mutations to specialists.`),Z=(e,t,n,r,i)=>{if(!(e.mode===null||!n.getActiveTools().some(e=>e===r))&&!(!(n.isMutationTool??(e=>{let t=e.toolName??``;return t===`edit`||t===`write`||t===`patch`||t===`bash`||n.extraMutations?.some(e=>e===t)===!0}))(t)||t.toolName===r)){if(n.isBashTool(t)){let e=X(t.input)?t.input:void 0,n=typeof e?.command==`string`?e.command:``;if(dt(n))return}return{block:!0,reason:`Tool '${t.toolName}' is blocked for the orchestrator. ${i}`}}},ht=async(e,t,n)=>{if(!t.isBashTool(e))return;let r=X(e.input)?e.input:void 0;if(!r)return;let{command:i}=r;if(typeof i!=`string`||!i)return;let a=ft(i);if(a&&!(n.hasUI===!0&&n.ui&&await n.ui.confirm(`Dangerous Pattern Detected`,`This command matches a dangerous pattern:\n${i}\nProceed?`)))return{block:!0,reason:`Command matches dangerous pattern: ${a}`}},gt=(e,t,n)=>{if(n.isReadTool(t)){let n=X(t.input)?t.input.path:void 0;if(typeof n==`string`&&n)return Object.assign(e,ie(e,n)),!0}else if(n.isWriteTool(t)){let n=X(t.input)?t.input.path:void 0;if(typeof n==`string`&&n)return Object.assign(e,re(e,n)),!0}return!1},_t=e=>{let{delegationTool:t}=e,n=mt(t,e.delegationHint),r=()=>{if(e.persist){e.persist();return}e.pi&&y(e.pi,e.getState())};return async(i,a)=>{if(i.toolName===void 0||i.toolName===``)return;let o=e.getState(),{toolName:s}=i,c=Z(o,i,e,t,n);if(c)return c;if(o.reviewMode&&(e.isWriteTool(i)||e.isBashTool(i)))return{block:!0,reason:pt(s)??`Review mode is active. Report findings, do not edit.`};let l=await ht(i,e,a);if(l)return l;gt(o,i,e)&&r()}},vt=e=>({appendEntry:(t,n)=>{e.appendEntry(t,n)},getActiveTools:()=>e.getActiveTools(),on:(t,n)=>{e.on(`tool_call`,async(e,t)=>await n(e,t))}}),yt=(e,t)=>{let n=_t({delegationTool:`subagent`,getActiveTools:()=>e.getActiveTools(),getState:()=>t,isBashTool:e=>e.toolName===`bash`,isMutationTool:e=>e.toolName===`edit`||e.toolName===`write`||e.toolName===`patch`||e.toolName===`bash`,isReadTool:e=>e.toolName===`read`,isWriteTool:e=>e.toolName===`edit`||e.toolName===`write`,persist:()=>{y(e,t)}});e.on(`tool_call`,n)},bt=e=>typeof e==`object`&&!!e,xt=e=>{let t=e?.sessionManager;if(typeof t?.getBranch!=`function`)return null;let n=t.getBranch();return Array.isArray(n)?n:null},Q=e=>{for(let t of Object.keys(e))Reflect.deleteProperty(e,t)},$=(e,t)=>{let n=g(),r=xt(t);if(!r){Q(e),Object.assign(e,n);return}for(let e=r.length-1;e>=0;--e){let t=r[e];if(t.type===`custom`&&t.customType===`maestria_state`){bt(t.data)&&Object.assign(n,t.data);break}}Q(e),Object.assign(e,n)},St=e=>{let t=g(),n=[];Pe(Ne(e),t),je(e,t);let r=Le(t);e.on(`before_agent_start`,(e,t)=>r(e,t)),e.on(`session_start`,(e,n)=>{ne(n),$(t,n)}),e.on(`session_tree`,(e,n)=>{$(t,n)}),C(S(e),t),st(ct(e),t,n),ve(_e(e),t),e.on(`session_shutdown`,()=>{for(let e of n)e();n.length=0}),yt(vt(e),t)};export{St as default};
|
|
12
|
-
//# sourceMappingURL=extension.mjs.map
|
|
11
|
+
`),type:`text`}],details:{}}),at=async(e,t,n,r,i)=>{let{getSubagentsService:a}=await import(`@gotgenes/pi-subagents`),o=a();if(!o||typeof o.spawn!=`function`)return rt();try{return await tt(e,t,o,n,r,i)}catch(e){console.warn(`[maestria] Subagent dispatch failed:`,e);let t=n.agent??n.tasks?.[0]?.agent??`unknown`,r=n.task??n.tasks?.map(e=>e.task).join(`; `)??`unknown`;return it(t,r)}},ot=(e,t)=>({description:`Dispatch a task to a @gotgenes/pi-subagents specialist subagent`,async execute(n,r,i,a,o){if(t.reviewMode)return{content:[{text:`Subagent dispatch is not available during review mode. Use /restore-model to exit review mode first.`,type:`text`}],details:{}};let s=qe(r);return s.startsWith(`Invalid`)?{content:[{text:`${s} Re-dispatch with a valid agent name; the orchestrator may continue read-only exploration while the brief is corrected.`,type:`text`}],details:{}}:await at(e,t,r,i,a?e=>{a({content:e.content.map(({text:e})=>({text:e,type:`text`})),details:e.details??{}})}:void 0)},label:`Maestria Subagent`,name:`maestria_subagent`,parameters:nt,promptGuidelines:[`Use maestria_subagent when a task MUST be delegated to a specialist subagent rather than handled directly. Each specialist has focused capabilities: adventurer (recon), architect (design), builder (impl), planner (planning), diagnose (bugs), reviewer (QA), writer (docs).`],promptSnippet:`Delegate tasks to @maestria specialist subagents (adventurer, architect, builder, planner, diagnose, reviewer, writer)`}),st=(e,t,n)=>{e.registerTool(ot(e,t)),Ke(e,t,n)},ct=e=>({appendEntry:(t,n)=>{e.appendEntry(t,n)},events:e.events,registerTool:t=>{e.registerTool(u({...t,async execute(e,n,r,i,a){return await t.execute(e,n,r,i,a)}}))}}),lt=[/rm\s+-rf\s+\//u,/dd\s+if=/u,/>\s*\/dev\/sd/u,/chmod\s+-R\s+777\s+\//u,/mkfs\.\w+/u,/:\(\)\{ :\|:& \};:/u,/>\s*\/etc\/(?<targetFile>passwd|shadow|sudoers)/u,/\beval\b/u,/wget\s+-O\s*-\s*\|\s*(?<wgetShell>bash|sh)/u,/curl\s+.*\|\s*(?<curlShell>bash|sh)/u,/crontab\s+-r/u],ut=/^(?<command>ls|cat|head|tail|git status|git diff|git log|git branch|find|grep|rg|pnpm test|npm test|pwd|which)\b/u,dt=e=>{let t=e.trim();if(t.includes(`$(`)||t.includes("`"))return!1;let n=t.replaceAll(/\d?>&[12]/gu,``);return!n.includes(`>`)&&n.split(/[\n;&|]+/u).every(e=>ut.test(e.trim()))},ft=e=>{for(let t of lt)if(t.test(e))return t;return null},pt=e=>e===`edit`||e===`write`||e===`bash`?`Review mode is active. Report findings, do not edit.`:null,X=e=>typeof e==`object`&&!!e,mt=(e,t)=>t??(e===`task`?`Use 'maestria_subagent' or 'task()' to delegate mutations to specialists.`:`Use 'maestria_subagent' to delegate mutations to specialists.`),Z=(e,t,n,r,i)=>{if(!(e.mode===null||!n.getActiveTools().some(e=>e===r))&&!(!(n.isMutationTool??(e=>{let t=e.toolName??``;return t===`edit`||t===`write`||t===`patch`||t===`bash`||n.extraMutations?.some(e=>e===t)===!0}))(t)||t.toolName===r)){if(n.isBashTool(t)){let e=X(t.input)?t.input:void 0,n=typeof e?.command==`string`?e.command:``;if(dt(n))return}return{block:!0,reason:`Tool '${t.toolName}' is blocked for the orchestrator. ${i}`}}},ht=async(e,t,n)=>{if(!t.isBashTool(e))return;let r=X(e.input)?e.input:void 0;if(!r)return;let{command:i}=r;if(typeof i!=`string`||!i)return;let a=ft(i);if(a&&!(n.hasUI===!0&&n.ui&&await n.ui.confirm(`Dangerous Pattern Detected`,`This command matches a dangerous pattern:\n${i}\nProceed?`)))return{block:!0,reason:`Command matches dangerous pattern: ${a}`}},gt=(e,t,n)=>{if(n.isReadTool(t)){let n=X(t.input)?t.input.path:void 0;if(typeof n==`string`&&n)return Object.assign(e,ie(e,n)),!0}else if(n.isWriteTool(t)){let n=X(t.input)?t.input.path:void 0;if(typeof n==`string`&&n)return Object.assign(e,re(e,n)),!0}return!1},_t=e=>{let{delegationTool:t}=e,n=mt(t,e.delegationHint),r=()=>{if(e.persist){e.persist();return}e.pi&&y(e.pi,e.getState())};return async(i,a)=>{if(i.toolName===void 0||i.toolName===``)return;let o=e.getState(),{toolName:s}=i,c=Z(o,i,e,t,n);if(c)return c;if(o.reviewMode&&(e.isWriteTool(i)||e.isBashTool(i)))return{block:!0,reason:pt(s)??`Review mode is active. Report findings, do not edit.`};let l=await ht(i,e,a);if(l)return l;gt(o,i,e)&&r()}},vt=e=>({appendEntry:(t,n)=>{e.appendEntry(t,n)},getActiveTools:()=>e.getActiveTools(),on:(t,n)=>{e.on(`tool_call`,async(e,t)=>await n(e,t))}}),yt=(e,t)=>{let n=_t({delegationTool:`subagent`,getActiveTools:()=>e.getActiveTools(),getState:()=>t,isBashTool:e=>e.toolName===`bash`,isMutationTool:e=>e.toolName===`edit`||e.toolName===`write`||e.toolName===`patch`||e.toolName===`bash`,isReadTool:e=>e.toolName===`read`,isWriteTool:e=>e.toolName===`edit`||e.toolName===`write`,persist:()=>{y(e,t)}});e.on(`tool_call`,n)},bt=e=>typeof e==`object`&&!!e,xt=e=>{let t=e?.sessionManager;if(typeof t?.getBranch!=`function`)return null;let n=t.getBranch();return Array.isArray(n)?n:null},Q=e=>{for(let t of Object.keys(e))Reflect.deleteProperty(e,t)},$=(e,t)=>{let n=g(),r=xt(t);if(!r){Q(e),Object.assign(e,n);return}for(let e=r.length-1;e>=0;--e){let t=r[e];if(t.type===`custom`&&t.customType===`maestria_state`){bt(t.data)&&Object.assign(n,t.data);break}}Q(e),Object.assign(e,n)},St=e=>{let t=g(),n=[];Pe(Ne(e),t),je(e,t);let r=Le(t);e.on(`before_agent_start`,(e,t)=>r(e,t)),e.on(`session_start`,(e,n)=>{ne(n),$(t,n)}),e.on(`session_tree`,(e,n)=>{$(t,n)}),C(S(e),t),st(ct(e),t,n),ve(_e(e),t),e.on(`session_shutdown`,()=>{for(let e of n)e();n.length=0}),yt(vt(e),t)};export{St as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maestria/pi",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.7",
|
|
4
4
|
"description": "Maestria extension for the Pi coding agent",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-orchestration",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"@types/node": "^26.2.0",
|
|
34
34
|
"typescript": "^7.0.2",
|
|
35
35
|
"vitest": "4.1.11",
|
|
36
|
-
"@maestria/core": "0.8.
|
|
36
|
+
"@maestria/core": "0.8.5",
|
|
37
37
|
"@maestria/shared-pi": "0.4.0"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
@@ -22,7 +22,7 @@ Cross-platform behavior contract for outcomes, evidence, safety, delegation, rev
|
|
|
22
22
|
- **!!! Match effort to stakes.** Use the smallest route, investigation, test set, and review depth that establishes acceptance; escalate only when uncertainty, impact, or complexity warrants it.
|
|
23
23
|
- **!!! Prefer reuse over reinvention.** Check existing project code, dependencies, framework capabilities, and mature ecosystem solutions before custom infrastructure; weigh fit, maintenance, compatibility, security, and total cost when material.
|
|
24
24
|
- **!!! Exhaust available evidence before asking.** Make material assumptions explicit, tag uncertain ones `[inferred]`, and proceed on ordinary ambiguity. Ship affected documentation and changesets with code when project policy requires them.
|
|
25
|
-
- **!!! Exercise testing judgment, not coverage.**
|
|
25
|
+
- **!!! Exercise testing judgment, not coverage.** Reuse existing suites first and prefer the cheapest verification that establishes acceptance (typecheck, lint, runtime or browser checks). Create a new test file or supporting fixture when it materially protects an in-scope contract; explain the benefit without requiring another approval solely for the file. Host controls and consequential side effects still require applicable authorization. Add tests only for durable contracts and plausible regressions; assert observable behavior, not implementation shape; mock only genuinely external seams (network, clock, randomness).
|
|
26
26
|
- **!!! Keep output self-contained and professional.** Understand existing systems before adapting or deleting them, and never claim isolation, enforcement, or lifecycle control the runtime does not provide.
|
|
27
27
|
- **!!! Human-facing output.** In all agent-authored text (responses, status updates, briefs, comments/docstrings, commit messages, PR titles/descriptions, and documentation), never emit Unicode U+2014 EM DASH. Prefer commas, colons, parentheses, or ASCII hyphen-minus (`-`). Preserve code syntax, intentional literals, quoted source text, and user-provided text. Scan authored output before handoff or delivery.
|
|
28
28
|
|
|
@@ -52,10 +52,12 @@ Default to one independent review and, only when blockers exist, one repair/re-r
|
|
|
52
52
|
|
|
53
53
|
## Authorization, Lifecycle, and Branches
|
|
54
54
|
|
|
55
|
-
Safety and authorization override user intent, methodology, and brevity. Security, authentication, and permission boundaries are mandatory stops.
|
|
55
|
+
Safety and authorization override user intent, methodology, and brevity. Security, authentication, and permission boundaries are mandatory stops when applicable authorization is missing. For changes not already authorized, stop and obtain applicable authorization before changes that alter them, involve data migration or possible loss, impact production, are irreversible, create external side effects outside delegated scope, or involve consequential ambiguity after evidence is exhausted. Ordinary in-scope security defects may be repaired autonomously. Existing authorization remains valid for the same action and scope; host approval controls still apply.
|
|
56
56
|
|
|
57
|
-
The orchestrator owns continuation for implementation and delivery work until the outcome reaches its terminal artifact; incomplete todos, pending handoffs, or specialist messages saying "continue if needed" are not a user checkpoint. Routine delivery is autonomous. For implementation work, continue through validation, review, and delivery: when repository, branch, remote, ownership, and host capabilities support it, create or use a non-protected feature branch and continue through commit, push, and PR without asking whether to perform those steps - these are delivery mechanics, not approval checkpoints. Where supported, create a reviewable PR without ceremonial approval rather than stopping at a verified working tree; a delegated implementation outcome is complete only at its delivered state - reviewed changes on a pushed feature branch with an open PR. Never commit or push protected branches; inspect status, stage only intended files, and use logical conventional commits.
|
|
57
|
+
The orchestrator owns continuation for implementation and delivery work until the outcome reaches its terminal artifact; incomplete todos, pending handoffs, or specialist messages saying "continue if needed" are not a user checkpoint. Routine delivery is autonomous. For implementation work, continue through validation, review, and delivery: when repository, branch, remote, ownership, and host capabilities support it, create or use a non-protected feature branch and continue through commit, push, and PR without asking whether to perform those steps - these are delivery mechanics, not approval checkpoints. Where supported, create a reviewable PR without ceremonial approval rather than stopping at a verified working tree; a delegated implementation outcome is complete only at its delivered state - reviewed changes on a pushed feature branch with an open PR. Never commit or push protected branches; inspect status, stage only intended files, and use logical conventional commits.
|
|
58
|
+
|
|
59
|
+
Merge, release, and production operations remain separate authorization boundaries. Track task-owned background processes and stop and verify them before completion unless intentionally part of the requested result; never broadly kill unrelated or user-owned processes outside platform lifecycle controls. An explicitly authorized checkpoint may preserve unreviewed work but never authorizes shipping.
|
|
58
60
|
|
|
59
61
|
## Canonical Source Invariant
|
|
60
62
|
|
|
61
|
-
|
|
63
|
+
Edit the project's authoritative source and regenerate derived outputs with its documented workflow; never hand-edit generated copies. Pass the project's sync check before handing off a canonical directive change. Repository-specific source paths and commands belong in that repository's instructions.
|
|
@@ -49,7 +49,7 @@ Delegate to `/builder` directly when the task is concrete and atomic. Add reconn
|
|
|
49
49
|
|
|
50
50
|
## Role-Based Pipeline
|
|
51
51
|
|
|
52
|
-
Thinkers (`/adventurer`, `/architect`, `/planner
|
|
52
|
+
Thinkers (`/adventurer`, `/architect`, `/planner`) analyze and plan; `/diagnose` analyzes the bug, applies the minimal fix, and verifies the repair; Workers (`/builder`, `/writer`) produce artifacts; the Verifier (`/reviewer`) independently validates. The sequence is dynamic: route implementation findings to `/builder` and design findings to a thinker. Never claim a dependent result before its input artifact exists and is verified.
|
|
53
53
|
|
|
54
54
|
## Review and Triage
|
|
55
55
|
|
|
@@ -77,10 +77,14 @@ Modes are case-insensitive and per-turn.
|
|
|
77
77
|
|
|
78
78
|
For implementation work, own the delivery path: inspect -> plan -> implement -> validate -> one independent review -> repair material blockers only when required -> targeted validation of repaired scope -> final verification -> commit -> push -> PR.
|
|
79
79
|
|
|
80
|
-
**Routine delivery is autonomous.** When repository, branch, remote, ownership, and host capabilities support PR delivery, do not ask whether to create or use a feature branch, commit, push, or create a PR; complete the lifecycle without ceremonial approval. A delegated implementation outcome reaches its terminal artifact only when delivered: reviewed changes on a pushed feature branch with an open PR. Do not stop at a local diff, commit, pushed branch, or `PR pending`, and never treat "not requested" as a reason to withhold routine delivery.
|
|
80
|
+
**Routine delivery is autonomous.** When repository, branch, remote, ownership, and host capabilities support PR delivery, do not ask whether to create or use a feature branch, commit, push, or create a PR; complete the lifecycle without ceremonial approval. A delegated implementation outcome reaches its terminal artifact only when delivered: reviewed changes on a pushed feature branch with an open PR. Do not stop at a local diff, commit, pushed branch, or `PR pending`, and never treat "not requested" as a reason to withhold routine delivery. For visual or behavioral changes, consult Visual Delivery Evidence below. Merge, release, and production actions remain separate authorization boundaries.
|
|
81
81
|
|
|
82
82
|
The parent session owns continuation until the selected implementation outcome reaches its terminal artifact. Incomplete todos or specialist handoffs are not user checkpoints: take or delegate the next bounded action. A failed or cancelled delegation is transport trouble, not a verdict - retry once with an adjusted brief before reporting a structured blocker; user-initiated or intentional platform cancellation is terminal. Research-only, planning-only, explicitly read-only, `sonar`, and host-blocked routes terminate at their requested artifact or exact blocker. Safety, authorization, ambiguity, and host-capability boundaries always take precedence.
|
|
83
83
|
|
|
84
84
|
Freeze acceptance, non-goals, and repair limits at the start; classify adjacent findings as follow-ups rather than expanding scope or resetting limits.
|
|
85
85
|
|
|
86
86
|
Report briefly at milestones - route chosen, delegations integrated, verification and review results, delivery state - each covering outcome, changed files, evidence, blockers, next step. Do not narrate routine reads, retries, or mechanics between milestones.
|
|
87
|
+
|
|
88
|
+
## Visual Delivery Evidence
|
|
89
|
+
|
|
90
|
+
When a screenshot or short video materially helps PR review, check that the repository host and authenticated delivery tool support attachments and that a capture tool and display are available. Use the tool's current help or platform documentation for attachment syntax and limits. Capture at reasonable cost and attach with descriptive alt text. Skip when prerequisites are missing or review value is low. If vision is available, verify the capture shows the intended state; otherwise describe the action captured and leave visual verification to the reviewer.
|
package/dist/extension.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"extension.mjs","names":["deploySpecialistAgents","__dirname","restoreOriginalState","restoreOriginalState","installCommands","isRecord","isPiModel","installCompactionHandlers","MODE_KEYWORDS","MODE_MARKERS","SHARED_KEYWORDS","SHARED_MARKERS","sharedDetectMode","sharedStripKeyword","installModeAutoDetect","installModeCommands","isRecord","restoreCore","__dirname","COMMANDS_DIR","isRecord","assertTaskContract","isRecord"],"sources":["../../shared/pi/src/subagent-utils.ts","../../shared/pi/src/agent-deployment.ts","../src/agents.ts","../../shared/pi/src/state-core.ts","../../shared/pi/src/review-core.ts","../../shared/pi/src/commands-core.ts","../src/commands.ts","../../shared/pi/src/compaction-core.ts","../src/compaction.ts","../../shared/mode/src/index.ts","../../shared/pi/src/modes-core.ts","../src/state/review.ts","../src/modes.ts","../src/rules.ts","../src/subagent-polling.ts","../src/subagent-events.ts","../src/subagent.ts","../src/subagent-api.ts","../../shared/pi/src/tools-core.ts","../src/tools.ts","../src/extension.ts"],"sourcesContent":["/**\n * Shared subagent validation utilities for Maestria platform packages.\n *\n * Pure TypeScript - no platform-specific dependencies.\n * Imported by both @maestria/omp and @maestria/pi to eliminate duplication.\n *\n * @module\n */\n\n/** Maestria cross-extension event names. */\nexport const MAESTRIA_EVENTS = {\n REVIEW_ACTIVATED: 'maestria:review:activated',\n REVIEW_DEACTIVATED: 'maestria:review:deactivated',\n SUBAGENT_COMPLETED: 'maestria:subagent:completed',\n SUBAGENT_FAILED: 'maestria:subagent:failed',\n SUBAGENT_STARTED: 'maestria:subagent:started',\n} as const;\n\n/** The set of specialist agent types maestria supports. */\nexport const ALLOWED_AGENTS = [\n 'adventurer',\n 'architect',\n 'builder',\n 'diagnose',\n 'planner',\n 'reviewer',\n 'writer',\n] as const;\n\n/** A valid specialist agent name. */\nexport type AllowedAgent = (typeof ALLOWED_AGENTS)[number];\n\n/** The 7-field handoff contract used in delegation. */\nexport const HANDOFF_FIELDS = [\n 'Goal',\n 'Context',\n 'Requirements',\n 'Known problems',\n 'Assumptions documented',\n 'Success criteria',\n 'Next step',\n] as const;\n\n/** Result of validating a handoff document against the contract fields. */\nexport interface HandoffValidation {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Asserts that `agent` is a known maestria specialist.\n * @throws {Error} if the agent name is not in ALLOWED_AGENTS.\n */\nexport const assertValidAgent = (agent: string): asserts agent is AllowedAgent => {\n if (!ALLOWED_AGENTS.some((allowedAgent) => allowedAgent === agent)) {\n throw new Error(`Unknown agent: \"${agent}\". Allowed: ${ALLOWED_AGENTS.join(', ')}`);\n }\n};\n\n/**\n * Asserts that `task` is a non-empty, non-whitespace string.\n * @throws {Error} with the given label if task is falsy or all-whitespace.\n */\nexport const assertNonEmptyTask = (\n task: string | undefined,\n label: string,\n): asserts task is string => {\n if (task === undefined || task === null || task === '' || !task.trim()) {\n throw new Error(label);\n }\n};\n\n/**\n * Validates that a handoff document contains all required fields\n * with non-empty content. Each field is expected in markdown bold format:\n * `**Field:** content`.\n */\nexport const validateHandoff = (handoff: string): HandoffValidation => {\n const errors: string[] = [];\n for (const field of HANDOFF_FIELDS) {\n // Match field header and capture content up to the next field or end of string.\n // This avoids false positives when an empty field is followed by another field's `**` header.\n const pattern = `\\\\*\\\\*${field}:\\\\*\\\\*(?<content>[\\\\s\\\\S]*?)(?=\\\\n\\\\*\\\\*|$)`;\n const match = new RegExp(pattern, 'iu').exec(handoff);\n const content = match?.groups?.content?.trim();\n if (content === undefined || content === '') {\n errors.push(`Missing or empty field: \"${field}\"`);\n }\n }\n return { errors, valid: errors.length === 0 };\n};\n","/**\n * Shared agent deployment logic for Maestria platform packages.\n *\n * Both @maestria/omp and @maestria/pi deploy specialist agent .md files\n * to their respective platform agent directories. This module eliminates\n * the duplication between the two packages.\n *\n * @module\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\nimport { ALLOWED_AGENTS } from './subagent-utils.js';\n\n/**\n * Deploy bundled specialist agent .md files to the given destination directory.\n *\n * Only creates files that don't already exist - never overwrites user-customized agents.\n *\n * @param agentsSrc - Path to the source directory containing specialist .md files\n * @param agentsDest - Absolute path to the platform's agents destination directory\n * (e.g. `join(homedir(), '.omp', 'agent', 'agents')`)\n * @returns The number of agents newly deployed\n */\nexport const deploySpecialistAgents = (agentsSrc: string, agentsDest: string): number => {\n if (!existsSync(agentsSrc)) {\n console.warn('[maestria] Agents source directory not found:', agentsSrc);\n return 0;\n }\n\n try {\n mkdirSync(agentsDest, { recursive: true });\n } catch {\n console.warn('[maestria] Could not create agents directory:', agentsDest);\n return 0;\n }\n\n let deployed = 0;\n for (const name of ALLOWED_AGENTS) {\n const srcFile = path.join(agentsSrc, `${name}.md`);\n const destFile = path.join(agentsDest, `${name}.md`);\n\n if (!existsSync(srcFile)) {\n console.warn(`[maestria] Agent source not found: ${name}.md`);\n continue;\n }\n\n if (existsSync(destFile)) {\n continue;\n }\n\n try {\n const content = readFileSync(srcFile, 'utf-8');\n writeFileSync(destFile, content, 'utf-8');\n deployed += 1;\n } catch (error) {\n console.warn(`[maestria] Failed to deploy agent ${name}:`, error);\n }\n }\n\n if (deployed > 0) {\n console.log(`[maestria] Deployed ${deployed} specialist agents to ${agentsDest}`);\n }\n\n return deployed;\n};\n","import { deploySpecialistAgents as deployAgents } from '@maestria/shared-pi/agent-deployment';\nimport { homedir } from 'node:os';\nimport path from 'node:path';\n\nconst __dirname = import.meta.dirname;\n\nconst AGENTS_SRC = path.join(__dirname, '..', 'agents');\n\n/**\n * Deploy bundled specialist agent .md files to the pi-subagents agents directory.\n *\n * pi-subagents discovers agent types from ~/.pi/agent/agents/*.md on every\n * registry.reload() call (which fires automatically on each tool invocation).\n * This function ensures the files are in place before the first subagent dispatch.\n *\n * Only creates files that don't already exist - never overwrites user-customized agents.\n */\nexport const deploySpecialistAgents = (_ctx?: unknown): void => {\n deployAgents(AGENTS_SRC, path.join(homedir(), '.pi', 'agent', 'agents'));\n};\n","/**\n * Shared state management for Maestria platform packages.\n *\n * Pure TypeScript - no platform-specific dependencies.\n * Provides shared state-management types, transforms, persistence, and rendering\n * consumed directly by @maestria/omp and @maestria/pi.\n *\n * @module\n */\n\n// ── Types ──\n\nexport type ModeKeyword = 'fein' | 'sonar' | 'blitz';\n\nexport const HANDOFF_HISTORY_CAP = 5;\nexport const FILE_HISTORY_CAP = 10;\n\nexport interface HandoffEntry {\n from: string;\n to: string;\n task: string;\n timestamp: number;\n}\n\nexport interface SubagentStatusInfo {\n type: string;\n status: string;\n startedAt: number;\n completedAt?: number;\n}\n\n/**\n * Mirror of the host platform's native goal (e.g. OMP goal mode).\n *\n * Platform-agnostic by design: only the objective text and status are\n * carried so shared state stays free of platform-specific types.\n */\nexport interface NativeGoalMirror {\n objective: string;\n status: string;\n}\n\nexport interface MaestriaState {\n mode: ModeKeyword | null;\n activeTask: string;\n completionPromise: string;\n specialistsDelegated: string[];\n blockers: string[];\n filesModified: string[];\n filesRead: string[];\n handoffHistory: HandoffEntry[];\n reviewMode: boolean;\n originalModel: string | null;\n originalTools: string[] | null;\n subagentStatus: Record<string, SubagentStatusInfo>;\n reviewModel: string | null;\n nativeGoal: NativeGoalMirror | null;\n}\n\n// ── Transforms ──\n\nexport const createInitialState = (): MaestriaState => ({\n activeTask: '',\n blockers: [],\n completionPromise: '',\n filesModified: [],\n filesRead: [],\n handoffHistory: [],\n mode: null,\n nativeGoal: null,\n originalModel: null,\n originalTools: null,\n reviewMode: false,\n reviewModel: null,\n specialistsDelegated: [],\n subagentStatus: {},\n});\n\nconst prependDeduped = (files: string[], path: string, cap: number): string[] => {\n const filtered = files.filter((f) => f !== path);\n return [path, ...filtered].slice(0, cap);\n};\n\nexport const recordHandoff = (\n state: MaestriaState,\n from: string,\n to: string,\n task: string,\n): MaestriaState => {\n const entry: HandoffEntry = { from, task, timestamp: Date.now(), to };\n const history = [entry, ...state.handoffHistory].slice(0, HANDOFF_HISTORY_CAP);\n return { ...state, handoffHistory: history };\n};\n\nexport const recordFileModified = (state: MaestriaState, path: string): MaestriaState => ({\n ...state,\n filesModified: prependDeduped(state.filesModified, path, FILE_HISTORY_CAP),\n});\n\nexport const recordFileRead = (state: MaestriaState, path: string): MaestriaState => ({\n ...state,\n filesRead: prependDeduped(state.filesRead, path, FILE_HISTORY_CAP),\n});\n\nexport const recordSpecialistDelegated = (state: MaestriaState, name: string): MaestriaState => {\n if (state.specialistsDelegated.includes(name)) {\n return state;\n }\n return { ...state, specialistsDelegated: [...state.specialistsDelegated, name] };\n};\n\nexport const recordSubagentStatus = (\n state: MaestriaState,\n id: string,\n info: SubagentStatusInfo,\n): MaestriaState => ({ ...state, subagentStatus: { ...state.subagentStatus, [id]: info } });\n\nexport const setReviewMode = (state: MaestriaState, active: boolean): MaestriaState => ({\n ...state,\n reviewMode: active,\n});\n\nexport const exitReviewMode = (\n state: MaestriaState,\n): {\n state: MaestriaState;\n originalModel: string | null;\n originalTools: string[] | null;\n} => ({\n originalModel: state.originalModel,\n originalTools: state.originalTools,\n state: {\n ...state,\n originalModel: null,\n originalTools: null,\n reviewMode: false,\n },\n});\n\n// ── Persistence ──\n\nexport const persistState = (\n pi: { appendEntry: (type: string, data: unknown) => void },\n state: MaestriaState,\n): void => {\n pi.appendEntry('maestria_state', { ...state });\n};\n\n// ── Render ──\n\nexport const renderMaestriaSummary = (state: MaestriaState): string => {\n const parts: string[] = [];\n\n if (state.mode) {\n parts.push(`**Mode:** ${state.mode.toUpperCase()}`);\n }\n\n if (state.reviewModel !== null && state.reviewModel !== undefined && state.reviewModel !== '') {\n parts.push(`**Review Model:** ${state.reviewModel}`);\n }\n\n if (state.activeTask) {\n parts.push(`**Goal:** ${state.activeTask}`);\n }\n\n if (state.nativeGoal) {\n parts.push(`**Native Goal:** ${state.nativeGoal.objective} (${state.nativeGoal.status})`);\n }\n\n if (state.completionPromise) {\n parts.push(`**Completion Promise:** ${state.completionPromise}`);\n }\n\n if (state.specialistsDelegated.length > 0) {\n parts.push(`**Specialists Delegated:** ${state.specialistsDelegated.join(', ')}`);\n }\n\n if (state.blockers.length > 0) {\n parts.push('**Blockers:**');\n for (const blocker of state.blockers) {\n parts.push(`- ${blocker}`);\n }\n }\n\n const fileSubs: string[] = [];\n if (state.filesModified.length > 0) {\n fileSubs.push(`**Modified:** ${state.filesModified.join(', ')}`);\n }\n if (state.filesRead.length > 0) {\n fileSubs.push(`**Read:** ${state.filesRead.join(', ')}`);\n }\n if (fileSubs.length > 0) {\n parts.push(`**Files:** ${fileSubs.join('; ')}`);\n }\n\n if (state.handoffHistory.length > 0) {\n parts.push('**Recent Handoffs:**');\n for (const entry of state.handoffHistory) {\n parts.push(`- ${entry.from} → ${entry.to}: ${entry.task}`);\n }\n }\n\n return parts.join('\\n\\n');\n};\n","/**\n * Shared review-mode orchestration for Maestria platform packages.\n *\n * Pure TypeScript - no platform-specific dependencies.\n * Consumed by both @maestria/omp and @maestria/pi to eliminate duplication\n * of review-mode model/tool restoration and switching.\n *\n * @module\n */\n\nimport type { MaestriaState } from './state-core.js';\nimport { exitReviewMode } from './state-core.js';\n\n// ── Duck-typed platform interfaces ──\n\ninterface ReviewPi {\n setActiveTools: (tools: string[]) => void | Promise<void>;\n setModel: (model: unknown) => void | Promise<void>;\n}\n\ninterface ReviewCtx {\n modelRegistry: { getAll: () => { id: string }[] };\n ui: { notify: (msg: string) => void };\n}\n\nexport const restoreOriginalState = async (\n pi: ReviewPi,\n ctx: ReviewCtx,\n state: MaestriaState,\n): Promise<void> => {\n const { state: clearedState, originalModel, originalTools } = exitReviewMode(state);\n\n if (originalTools && originalTools.length > 0) {\n await pi.setActiveTools(originalTools);\n }\n\n if (originalModel !== undefined && originalModel !== null && originalModel !== '') {\n try {\n const models = ctx.modelRegistry.getAll();\n const model = models.find((m: { id: string }) => m.id === originalModel);\n if (model) {\n await pi.setModel(model);\n }\n } catch {\n // Best-effort: model restoration is non-critical\n }\n }\n\n Object.assign(state, clearedState);\n};\n\nexport const cycleToReviewModel = async (\n pi: ReviewPi,\n ctx: ReviewCtx,\n state: MaestriaState,\n): Promise<string | null> => {\n const { reviewModel } = state;\n if (reviewModel === undefined || reviewModel === null || reviewModel === '') {\n return null;\n }\n try {\n const models = ctx.modelRegistry.getAll();\n const model = models.find((m) => m.id === reviewModel);\n if (model) {\n await pi.setModel(model);\n return reviewModel;\n }\n ctx.ui.notify(`Review model \"${reviewModel}\" not found in registry, staying on current.`);\n return null;\n } catch {\n ctx.ui.notify(`Could not switch to review model \"${reviewModel}\", staying on current.`);\n return null;\n }\n};\n","/**\n * Shared slash-command installation for Maestria platform packages.\n *\n * Pure TypeScript - no platform-specific dependencies.\n * Consumed by both @maestria/omp and @maestria/pi to eliminate duplication\n * of the maestria-status/review/restore-model/handoff/review-model commands.\n *\n * @module\n */\n\nimport { cycleToReviewModel, restoreOriginalState } from './review-core.js';\nimport type { MaestriaState } from './state-core.js';\nimport { persistState, recordHandoff, renderMaestriaSummary } from './state-core.js';\nimport { MAESTRIA_EVENTS } from './subagent-utils.js';\n\n// ── Duck-typed platform interfaces ──\n\nexport interface CommandsCtx {\n ui: {\n notify: (msg: string) => void;\n setEditorText: (text: string) => void;\n };\n model?: { id: string };\n modelRegistry: { getAll: () => { id: string }[] };\n}\n\nexport interface CommandsPi {\n registerCommand: (\n name: string,\n opts: {\n description: string;\n handler: (args: string, ctx: CommandsCtx) => Promise<void> | void;\n },\n ) => void;\n getActiveTools: () => string[];\n setActiveTools: (tools: string[]) => void | Promise<void>;\n setModel: (model: unknown) => void | Promise<void>;\n sendUserMessage: (text: string, opts: { deliverAs: string }) => void;\n appendEntry: (type: string, data: unknown) => void;\n events?: { emit: (event: string, data: unknown) => void };\n}\n\n/**\n * Read-only tools that let a reviewer inspect code without making changes.\n *\n * - `read`, `grep`, `find`, `ls`, `glob` - all non-destructive.\n * - Excluded: `bash`, `edit`, `write` - these can modify the filesystem.\n *\n * `glob` is included for file pattern matching even though it's not a\n * built-in Pi tool - extensions may register it, and including it is a no-op\n * if absent.\n */\nconst READ_ONLY_TOOLS = ['read', 'grep', 'find', 'ls', 'glob'];\n\nconst registerMaestriaStatus = (pi: CommandsPi, state: MaestriaState): void => {\n pi.registerCommand('maestria-status', {\n description: 'Show current maestria session state including handoff history',\n handler: (_args: string, ctx) => {\n const summary = renderMaestriaSummary(state);\n if (!summary) {\n ctx.ui.notify('No active maestria state to report.');\n return;\n }\n ctx.ui.setEditorText(summary);\n },\n });\n};\n\nconst registerReviewCommand = (pi: CommandsPi, state: MaestriaState): void => {\n pi.registerCommand('review', {\n description: 'Enter review mode. Blocks destructive tools, sets read-only toolset.',\n handler: async (args: string, ctx) => {\n if (!args.trim()) {\n ctx.ui.notify('Usage: /review <target> - describe what to review');\n return;\n }\n const currentModelId = ctx.model?.id ?? null;\n const currentTools = pi.getActiveTools();\n Object.assign(state, {\n ...state,\n originalModel: currentModelId,\n originalTools: currentTools,\n reviewMode: true,\n } as MaestriaState);\n persistState(pi, state);\n if (\n state.reviewModel !== null &&\n state.reviewModel !== undefined &&\n state.reviewModel !== ''\n ) {\n const switched = await cycleToReviewModel(pi, ctx, state);\n if (switched !== null && switched !== undefined && switched !== '') {\n ctx.ui.notify(`Review mode: switched to ${switched}`);\n pi.events?.emit(MAESTRIA_EVENTS.REVIEW_ACTIVATED, {\n originalModel: state.originalModel,\n reviewModel: switched,\n timestamp: Date.now(),\n });\n }\n }\n void pi.setActiveTools(READ_ONLY_TOOLS);\n pi.sendUserMessage(\n [\n `[REVIEW: ${args}]`,\n '',\n `Review: ${args}. Use the reviewer prompt template.`,\n 'Read only, no edits, report findings.',\n ].join('\\n'),\n { deliverAs: 'steer' },\n );\n },\n });\n};\n\nconst registerRestoreModel = (pi: CommandsPi, state: MaestriaState): void => {\n pi.registerCommand('restore-model', {\n description:\n 'Restore the original model and tools that were active before review mode was entered.',\n handler: async (_args: string, ctx) => {\n if (!state.reviewMode) {\n ctx.ui.notify('Not in review mode. Nothing to restore.');\n return;\n }\n const prevOriginalModel = state.originalModel;\n await restoreOriginalState(pi, ctx, state);\n persistState(pi, state);\n ctx.ui.notify('Restored original model and tools.');\n pi.events?.emit(MAESTRIA_EVENTS.REVIEW_DEACTIVATED, {\n originalModel: prevOriginalModel,\n timestamp: Date.now(),\n });\n },\n });\n};\n\nconst registerHandoffCommand = (pi: CommandsPi, state: MaestriaState): void => {\n pi.registerCommand('handoff', {\n description: 'Generate a structured handoff prompt for a new task context',\n handler: (args: string, ctx) => {\n if (!args.trim()) {\n ctx.ui.notify('Usage: /handoff <goal> - describe the task context for handoff');\n return;\n }\n const goal = args.trim();\n const handoffPrompt = [\n `**Goal:** ${goal}`,\n '',\n '**Context:**',\n `- Mode: ${state.mode ?? 'none'}`,\n `- Active task: ${state.activeTask || 'none'}`,\n `- Specialists delegated: ${\n (state.specialistsDelegated?.length ?? 0) > 0\n ? state.specialistsDelegated.join(', ')\n : 'none'\n }`,\n `- Recent handoffs: ${state.handoffHistory?.length ?? 0} entries`,\n `- Files modified: ${\n (state.filesModified?.length ?? 0) > 0 ? state.filesModified.join(', ') : 'none'\n }`,\n '',\n '**Requirements:**',\n '(fill in specific requirements)',\n '',\n '**Known problems:**',\n (state.blockers?.length ?? 0) > 0\n ? state.blockers.map((b: string) => `- ${b}`).join('\\n')\n : '(no known problems documented)',\n '',\n '**Assumptions documented:**',\n '(document assumptions made, tagged [inferred] where uncertain)',\n '',\n '**Success criteria:**',\n '(fill in how to verify completion)',\n '',\n '**Next step:**',\n '(fill in what happens after this task)',\n '',\n '---',\n 'Complete the fields above before sending.',\n ].join('\\n');\n Object.assign(state, recordHandoff(state, 'current', 'next', goal));\n persistState(pi, state);\n pi.sendUserMessage(handoffPrompt, { deliverAs: 'steer' });\n },\n });\n};\n\nconst registerReviewModel = (pi: CommandsPi, state: MaestriaState): void => {\n pi.registerCommand('review-model', {\n description: 'Set which model to use when entering review mode',\n handler: (args: string, ctx) => {\n if (!args.trim()) {\n ctx.ui.notify('Usage: /review-model <model-id>');\n return;\n }\n const modelId = args.trim();\n const models = ctx.modelRegistry.getAll();\n const model = models.find((m) => m.id === modelId);\n if (!model) {\n ctx.ui.notify(\n `Unknown model: \"${modelId}\". Available: ${models.map((m) => m.id).join(', ')}`,\n );\n return;\n }\n state.reviewModel = modelId;\n persistState(pi, state);\n ctx.ui.notify(`Review model set to: ${modelId}`);\n },\n });\n};\n\nexport const installCommands = (pi: CommandsPi, state: MaestriaState): void => {\n registerMaestriaStatus(pi, state);\n registerReviewCommand(pi, state);\n registerRestoreModel(pi, state);\n registerHandoffCommand(pi, state);\n registerReviewModel(pi, state);\n};\n","import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport { installCommands as installCommandsCore } from '@maestria/shared-pi/commands-core';\nimport type { CommandsPi } from '@maestria/shared-pi/commands-core';\n\nimport type { MaestriaState } from '@/state.js';\n\ntype PiModel = Parameters<ExtensionAPI['setModel']>[0];\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst isPiModel = (value: unknown): value is PiModel => {\n if (!isRecord(value)) {\n return false;\n }\n return (\n typeof value.api === 'string' &&\n typeof value.baseUrl === 'string' &&\n typeof value.contextWindow === 'number' &&\n typeof value.cost === 'object' &&\n value.cost !== null &&\n typeof value.id === 'string' &&\n Array.isArray(value.input) &&\n typeof value.maxTokens === 'number' &&\n typeof value.name === 'string' &&\n typeof value.provider === 'string' &&\n typeof value.reasoning === 'boolean'\n );\n};\n\nexport const createCommandsApi = (pi: ExtensionAPI): CommandsPi => ({\n appendEntry: (type, data) => {\n pi.appendEntry(type, data);\n },\n events: pi.events,\n getActiveTools: () => pi.getActiveTools(),\n registerCommand: (name, options) => {\n pi.registerCommand(name, {\n description: options.description,\n handler: async (args, ctx) => {\n await options.handler(args, ctx);\n },\n });\n },\n sendUserMessage: (text, options) => {\n if (options.deliverAs === 'steer' || options.deliverAs === 'followUp') {\n pi.sendUserMessage(text, { deliverAs: options.deliverAs });\n }\n },\n setActiveTools: (tools) => {\n pi.setActiveTools(tools);\n },\n setModel: async (model) => {\n if (isPiModel(model)) {\n await pi.setModel(model);\n }\n },\n});\n\nexport const installCommands = (pi: CommandsPi, state: MaestriaState): void => {\n installCommandsCore(pi, state);\n};\n","/**\n * Shared compaction handlers for Maestria platform packages.\n *\n * Pure TypeScript - no platform-specific dependencies.\n * Imported by both @maestria/omp and @maestria/pi to eliminate duplication.\n *\n * @module\n */\n\nimport { renderMaestriaSummary } from './state-core.js';\nimport type { MaestriaState } from './state-core.js';\n\nexport interface CompactionEvent {\n preparation?: {\n firstKeptEntryId?: string;\n tokensBefore?: number;\n };\n}\n\nexport interface TreeEvent {\n preparation?: {\n userWantsSummary?: boolean;\n };\n}\n\nexport interface CompactionResult {\n compaction?: {\n details?: unknown;\n firstKeptEntryId: string;\n summary: string;\n tokensBefore: number;\n };\n}\n\nexport interface TreeResult {\n summary?: {\n summary: string;\n };\n}\n\nexport type CompactionOn = (\n ...args:\n | ['session_before_compact', (event: CompactionEvent) => CompactionResult]\n | ['session_before_tree', (event: TreeEvent) => TreeResult | undefined]\n) => void;\n\nexport interface CompactionPi {\n on: CompactionOn;\n}\n\n/**\n * Install handlers for session compaction and tree events to persist\n * and restore maestria state across session compaction boundaries.\n */\nexport const installCompactionHandlers = (pi: CompactionPi, state: MaestriaState): void => {\n pi.on('session_before_compact', (event: CompactionEvent) => {\n const prep = event.preparation;\n return {\n compaction: {\n details: { ...state },\n firstKeptEntryId: prep?.firstKeptEntryId ?? '',\n summary: renderMaestriaSummary(state),\n tokensBefore: prep?.tokensBefore ?? 0,\n },\n };\n });\n\n pi.on('session_before_tree', (event: TreeEvent) => {\n const prep = event.preparation;\n return prep?.userWantsSummary === true\n ? {\n summary: {\n summary: renderMaestriaSummary(state),\n },\n }\n : undefined;\n });\n};\n","/**\n * Pi platform compaction handlers.\n *\n * Thin wrapper around the shared compaction-core implementation.\n *\n * @module\n */\n\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport { installCompactionHandlers as installHandlers } from '@maestria/shared-pi/compaction-core';\nimport type {\n CompactionEvent,\n CompactionPi,\n CompactionResult,\n TreeEvent,\n TreeResult,\n} from '@maestria/shared-pi/compaction-core';\n\nimport type { MaestriaState } from '@/state.js';\n\n/**\n * Install session compaction and tree event handlers for Pi.\n * Delegates to the shared implementation which is duck-type compatible\n * with Pi's ExtensionAPI.\n */\nexport const createCompactionApi = (pi: ExtensionAPI): CompactionPi => {\n const on = (\n ...args:\n | ['session_before_compact', (event: CompactionEvent) => CompactionResult]\n | ['session_before_tree', (event: TreeEvent) => TreeResult | undefined]\n ): void => {\n const [event, handler] = args;\n if (event === 'session_before_compact') {\n pi.on('session_before_compact', (eventData) => handler(eventData));\n }\n if (event === 'session_before_tree') {\n pi.on('session_before_tree', (eventData) => handler(eventData));\n }\n };\n return { on };\n};\n\nexport const installCompactionHandlers = (pi: CompactionPi, state: MaestriaState): void => {\n installHandlers(pi, state);\n};\n","/**\n * Private runtime-neutral shared mode mechanics.\n *\n * Pure TypeScript - no host SDKs, no filesystem APIs.\n * Consolidates the duplicated pure logic from:\n * - `packages/opencode/src/modes/index.ts`\n * - `packages/shared/pi/src/modes-core.ts`\n *\n * Consumers (OpenCode, shared-pi) delegate pure detection,\n * stripping, and mode-section extraction to this module while\n * keeping host-specific concerns (lazy file loading, session\n * state, command registration) locally.\n *\n * @module @maestria/shared-mode\n */\n\n// ── Constants ──\n\nexport const MODE_KEYWORDS = ['fein', 'sonar', 'blitz'] as const;\nexport type ModeKeyword = (typeof MODE_KEYWORDS)[number];\n\n/**\n * Backward-compatible alias used by OpenCode (`VALID_KEYWORDS`).\n */\nexport const VALID_KEYWORDS: readonly ModeKeyword[] = MODE_KEYWORDS;\n\nexport const MODE_MARKERS: Record<ModeKeyword, string> = {\n blitz: '[MODE: blitz]',\n fein: '[MODE: fein]',\n sonar: '[MODE: sonar]',\n};\n\n/**\n * Priority mapping for mode keyword restrictiveness.\n * Higher number = more restrictive = wins when multiple keywords are present.\n * fein (3): full pipeline with mandatory gates\n * sonar (2): research only, no code\n * blitz (1): fast implementation, skip optional ceremony; required review remains\n */\nexport const MODE_PRIORITY: Record<ModeKeyword, number> = {\n blitz: 1,\n fein: 3,\n sonar: 2,\n};\n\n// ── Types ──\n\n/**\n * Result of pure mode detection (no prompt/marker).\n * Host wrappers add prompt/marker and stripped text as needed.\n */\nexport interface ModeDetectPure {\n mode: ModeKeyword;\n keyword: string;\n index: number;\n}\n\n// ── Pure helpers ──\n\n/**\n * Regex matching fenced code blocks (```) and inline backtick spans (`).\n * Unclosed fenced blocks (``` without closing ```) are intentionally not\n * excluded - the regex requires matching fences. This is the accepted\n * false-positive behavior documented in ADR-OC-003.\n */\nexport const CODE_BLOCK_RE = /```[\\s\\S]*?```|`[^`]*`/gu;\n\nexport const findCodeBlockRanges = (text: string): [number, number][] => {\n const ranges: [number, number][] = [];\n let match: RegExpExecArray | null;\n // Reset lastIndex in case callers reuse the exported regex\n CODE_BLOCK_RE.lastIndex = 0;\n while ((match = CODE_BLOCK_RE.exec(text)) !== null) {\n ranges.push([match.index, match.index + match[0].length]);\n }\n return ranges;\n};\n\nexport const isInRanges = (index: number, ranges: [number, number][]): boolean =>\n ranges.some(([start, end]) => index >= start && index < end);\n\n/**\n * Extract the `## MODE:` section from a command file's content.\n * Mirrors the logic in both original modules: find `## MODE:`, slice\n * from there, trim trailing whitespace, append a single newline; if\n * no marker is found, normalize trailing whitespace the same way.\n */\nexport const extractModeSection = (content: string): string => {\n const modeIdx = content.indexOf('## MODE:');\n if (modeIdx !== -1) {\n return `${content.slice(modeIdx).replace(/\\s+$/u, '')}\\n`;\n }\n return `${content.replace(/\\s+$/u, '')}\\n`;\n};\n\nconst escapeRegExp = (value: string): string => value.replaceAll(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n\nconst buildKeywordRegex = (keyword: string): RegExp =>\n new RegExp(`\\\\b${escapeRegExp(keyword)}\\\\b`, 'giu');\n\nconst isModeKeyword = (value: string): value is ModeKeyword =>\n (MODE_KEYWORDS as readonly string[]).includes(value);\n\nexport const getModeMarker = (mode: string): string => {\n if (isModeKeyword(mode)) {\n return MODE_MARKERS[mode];\n }\n return '';\n};\n\n// ── Detection ──\n\n/**\n * Detect a workflow mode keyword in the given text.\n *\n * Rules (per ADR-OC-003):\n * - Word-boundary regex matching (`\\bfein\\b`, etc.), case-insensitive\n * - Most restrictive match wins (fein > sonar > blitz) regardless of position\n * - Disabled keywords (case-insensitive) are ignored\n * - Matches inside fenced code blocks (```) and inline backticks (`) are ignored\n * - Unclosed fences are not excluded (accepted false-positive)\n *\n * Returns the pure detection result (mode, matched keyword text, index) or null.\n */\nexport const detectMode = (text: string, disabled?: Set<string>): ModeDetectPure | null => {\n if (!text) {\n return null;\n }\n const codeRanges = findCodeBlockRanges(text);\n const normalizedDisabled = disabled\n ? new Set([...disabled].map((k) => k.toLowerCase()))\n : undefined;\n let best: ModeDetectPure | null = null;\n\n for (const keyword of MODE_KEYWORDS) {\n if (\n normalizedDisabled !== undefined &&\n normalizedDisabled !== null &&\n normalizedDisabled.has(keyword)\n ) {\n continue;\n }\n const regex = buildKeywordRegex(keyword);\n let match: RegExpExecArray | null;\n while ((match = regex.exec(text)) !== null) {\n if (isInRanges(match.index, codeRanges)) {\n continue;\n }\n if (best === null || MODE_PRIORITY[keyword] > MODE_PRIORITY[best.mode]) {\n best = { index: match.index, keyword: match[0], mode: keyword };\n }\n }\n }\n\n return best;\n};\n\n/**\n * Remove the matched keyword from the text, cleaning up a trailing colon\n * and collapsing double spaces.\n *\n * Mirrors both originals: strip a leading colon and surrounding whitespace\n * after the keyword, then collapse double spaces and trim.\n */\nexport const stripKeyword = (text: string, result: { index: number; keyword: string }): string => {\n const before = text.slice(0, result.index);\n const after = text.slice(result.index + result.keyword.length);\n const cleaned = after.replace(/^:\\s*/u, '');\n return (before + cleaned).replaceAll(/ {2,}/gu, ' ').trim();\n};\n","/**\n * Shared mode constants and utilities for Maestria Pi-family packages.\n *\n * Delegates pure mechanics to `@maestria/shared-mode` while preserving\n * host-specific concerns: lazy prompt loading from `commandsDir`,\n * session-state side effects, and platform handler factories.\n *\n * @module\n */\n\nimport {\n extractModeSection,\n MODE_KEYWORDS as SHARED_KEYWORDS,\n MODE_MARKERS as SHARED_MARKERS,\n detectMode as sharedDetectMode,\n stripKeyword as sharedStripKeyword,\n} from '@maestria/shared-mode';\nimport type { ModeKeyword as SharedModeKeyword } from '@maestria/shared-mode';\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\n\nimport type { MaestriaState } from './state-core.js';\n\n// ── Constants (re-exported from shared-mode to preserve public API) ──\n\nexport const MODE_KEYWORDS = SHARED_KEYWORDS;\nexport const MODE_CLEAR_COMMAND = 'mode-clear';\nexport type ModeKeyword = SharedModeKeyword;\n\nexport const MODE_MARKERS: Record<ModeKeyword, string> = SHARED_MARKERS;\n\n// ── Prompt loading ──\n\n/** Lazily cached mode prompts, scoped by commands directory and keyword. */\nconst _promptCache = new Map<string, string>();\n\n/**\n * Load and cache a mode prompt from a commands directory.\n * Delegates `## MODE:` extraction to the neutral shared-mode helper.\n */\nexport const loadModePrompt = (name: string, commandsDir: string): string => {\n const content = readFileSync(path.resolve(commandsDir, `${name}.md`), 'utf-8');\n return extractModeSection(content);\n};\n\n/**\n * Get the full mode prompt (marker + body) for a keyword, loading from\n * the given commands directory on first access.\n */\nexport const getModePrompt = (keyword: ModeKeyword, commandsDir: string): string => {\n const cacheKey = `${path.resolve(commandsDir)}\\0${keyword}`;\n if (!_promptCache.has(cacheKey)) {\n try {\n _promptCache.set(cacheKey, loadModePrompt(keyword, commandsDir));\n } catch (error) {\n console.warn(`[maestria] Failed to load mode prompt \"${keyword}\":`, error);\n _promptCache.set(cacheKey, '');\n }\n }\n return `${MODE_MARKERS[keyword]}\\n\\n${_promptCache.get(cacheKey) ?? ''}`;\n};\n\n// ── Keyword detection ──\n\n/** Result of detecting a mode keyword in text. */\nexport interface ModeDetectResult {\n /** The detected keyword. */\n keyword: ModeKeyword;\n /** The text with the keyword stripped and trimmed. */\n strippedText: string;\n /** The full mode prompt (marker + body). */\n prompt: string;\n}\n\n/**\n * Detect a mode keyword (fein/sonar/blitz) in text as a whole word,\n * case-insensitive. Delegates pure detection (including code-block\n * exclusion, word-boundary, priority, and case-insensitivity) to\n * `@maestria/shared-mode`. The accepted unclosed-fence behavior\n * (ADR-OC-003) is preserved via the shared helper.\n *\n * Lazy prompt loading remains host-specific (reads `commandsDir`).\n * Optional `disabled` set mirrors OpenCode's disabled-keyword support.\n */\nexport const detectModeInText = (\n text: string,\n commandsDir: string,\n disabled?: Set<string>,\n): ModeDetectResult | null => {\n if (!text) {\n return null;\n }\n\n const pure = sharedDetectMode(text, disabled);\n if (pure === null) {\n return null;\n }\n\n const strippedText = sharedStripKeyword(text, pure);\n\n return {\n keyword: pure.mode,\n prompt: getModePrompt(pure.mode, commandsDir),\n strippedText,\n };\n};\n\n/**\n * Build the final text to send to the LLM: prompt + stripped text.\n * If strippedText is empty, returns just the prompt.\n */\nexport const buildModeText = (prompt: string, strippedText: string): string =>\n strippedText ? `${prompt}\\n\\n${strippedText}` : prompt;\n\n// ── Platform handler factories ──\n\n/**\n * Install an input event handler that detects mode keywords (fein/sonar/blitz)\n * in user input, strips them, and injects the mode prompt.\n */\nexport const installModeAutoDetect = <Context, Result>(\n onInput: (handler: (event: { text: string }, ctx: Context) => Promise<Result>) => void,\n state: MaestriaState,\n commandsDir: string,\n opts: {\n /** Exit review mode - calls platform's restoreOriginalState */\n restoreOriginalState: (ctx: Context) => Promise<void>;\n /** Persist state after mode change */\n persistState: () => void;\n /** Return value when no keyword is detected (e.g. Pi: { action: 'continue' }) */\n noMatch: Result;\n /** Build return value from transformed text (e.g. Pi: { action: 'transform', text }) */\n transform: (text: string) => Result;\n },\n): void => {\n onInput(async (event, ctx) => {\n const { text } = event;\n const result = detectModeInText(text, commandsDir);\n if (!result) {\n return opts.noMatch;\n }\n\n if (state.reviewMode) {\n await opts.restoreOriginalState(ctx);\n }\n\n state.mode = result.keyword;\n opts.persistState();\n\n return opts.transform(buildModeText(result.prompt, result.strippedText));\n });\n};\n\n/**\n * Install slash commands for fein/sonar/blitz that set the workflow mode\n * and show a notification. Task description injection is handled by the\n * auto-detect handler instead.\n */\ninterface ModeCommandContext {\n ui: { notify: (msg: string) => void };\n}\n\nexport const installModeCommands = <Context extends ModeCommandContext>(\n registerCommand: (\n name: string,\n options: {\n description: string;\n handler: (args: string, ctx: Context) => Promise<void> | void;\n },\n ) => void,\n state: MaestriaState,\n opts: {\n /** Exit review mode before switching modes */\n restoreOriginalState: (ctx: Context) => Promise<void>;\n /** Persist state after mode change */\n persistState: () => void;\n },\n): void => {\n registerCommand(MODE_CLEAR_COMMAND, {\n description: 'Clear workflow mode and return to neutral routing',\n handler: async (_args: string, ctx: Context) => {\n if (state.reviewMode) {\n await opts.restoreOriginalState(ctx);\n }\n state.mode = null;\n opts.persistState();\n ctx.ui.notify('Workflow mode cleared. Neutral routing is active.');\n },\n });\n\n for (const keyword of MODE_KEYWORDS) {\n registerCommand(keyword, {\n description: `Set workflow mode to ${keyword}`,\n handler: async (_args: string, ctx: Context) => {\n if (state.reviewMode) {\n await opts.restoreOriginalState(ctx);\n }\n\n state.mode = keyword;\n opts.persistState();\n\n ctx.ui.notify(`Mode set to ${keyword}. Describe what you'd like to work on.`);\n },\n });\n }\n};\n","import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport {\n cycleToReviewModel as cycleCore,\n restoreOriginalState as restoreCore,\n} from '@maestria/shared-pi/review-core';\nimport type { MaestriaState } from '@maestria/shared-pi/state-core';\n\ntype PiModel = Parameters<ExtensionAPI['setModel']>[0];\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst isPiModel = (value: unknown): value is PiModel => {\n if (!isRecord(value)) {\n return false;\n }\n return (\n typeof value.api === 'string' &&\n typeof value.baseUrl === 'string' &&\n typeof value.contextWindow === 'number' &&\n typeof value.cost === 'object' &&\n value.cost !== null &&\n typeof value.id === 'string' &&\n Array.isArray(value.input) &&\n typeof value.maxTokens === 'number' &&\n typeof value.name === 'string' &&\n typeof value.provider === 'string' &&\n typeof value.reasoning === 'boolean'\n );\n};\n\nexport interface ReviewModelContext {\n modelRegistry: { getAll: () => { id: string }[] };\n ui: { notify: (message: string) => void };\n}\n\nexport interface ReviewModelApi {\n setActiveTools: ExtensionAPI['setActiveTools'];\n setModel: ExtensionAPI['setModel'];\n}\n\nexport type ReviewApi = ReviewModelApi;\n\nexport const restoreOriginalState = async (\n pi: ReviewApi,\n ctx: ReviewModelContext,\n state: MaestriaState,\n): Promise<void> => {\n await restoreCore(\n {\n setActiveTools: (tools) => {\n pi.setActiveTools(tools);\n },\n setModel: async (model) => {\n if (isPiModel(model)) {\n await pi.setModel(model);\n }\n },\n },\n ctx,\n state,\n );\n};\n\nexport const cycleToReviewModel = async (\n pi: ReviewApi,\n ctx: ReviewModelContext,\n state: MaestriaState,\n): Promise<string | null> =>\n await cycleCore(\n {\n setActiveTools: (tools) => {\n pi.setActiveTools(tools);\n },\n setModel: async (model) => {\n if (isPiModel(model)) {\n await pi.setModel(model);\n }\n },\n },\n ctx,\n state,\n );\n","import type {\n ExtensionAPI,\n ExtensionContext,\n InputEventResult,\n} from '@earendil-works/pi-coding-agent';\nimport {\n installModeAutoDetect as installAutoDetect,\n installModeCommands as installCommands,\n} from '@maestria/shared-pi/modes-core';\nimport path from 'node:path';\n\nimport type { MaestriaState } from '@/state.js';\nimport { persistState, restoreOriginalState } from '@/state.js';\n\nconst __dirname = import.meta.dirname;\nconst COMMANDS_DIR = path.resolve(__dirname, '../agents/commands');\n\nexport const installModeAutoDetect = (pi: ExtensionAPI, state: MaestriaState): void => {\n installAutoDetect<ExtensionContext, InputEventResult>(\n (handler) => {\n pi.on('input', handler);\n },\n state,\n COMMANDS_DIR,\n {\n noMatch: { action: 'continue' as const },\n persistState: () => {\n persistState(pi, state);\n },\n restoreOriginalState: async (ctx) => {\n await restoreOriginalState(pi, ctx, state);\n },\n transform: (text) => ({ action: 'transform' as const, text }),\n },\n );\n};\n\nexport interface ModeCommandContext {\n ui: { notify: (message: string) => void };\n}\n\nexport interface ModeCommandsApi {\n appendEntry: (type: string, data?: unknown) => void;\n registerCommand: (\n name: string,\n options: {\n description: string;\n handler: (args: string, ctx: ModeCommandContext) => Promise<void> | void;\n },\n ) => void;\n setActiveTools: ExtensionAPI['setActiveTools'];\n setModel: ExtensionAPI['setModel'];\n}\n\nconst isExtensionContext = (value: unknown): value is ExtensionContext => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n return 'modelRegistry' in value && 'ui' in value;\n};\n\nexport const createModeCommandsApi = (pi: ExtensionAPI): ModeCommandsApi => ({\n appendEntry: (type, data) => {\n pi.appendEntry(type, data);\n },\n registerCommand: (name, options) => {\n pi.registerCommand(name, {\n description: options.description,\n handler: async (args, ctx) => {\n await options.handler(args, ctx);\n },\n });\n },\n setActiveTools: (tools) => {\n pi.setActiveTools(tools);\n },\n setModel: async (model) => await pi.setModel(model),\n});\n\nexport const installModeCommands = (pi: ModeCommandsApi, state: MaestriaState): void => {\n installCommands<ModeCommandContext>(\n (name, opts) => {\n pi.registerCommand(name, {\n description: opts.description,\n handler: async (args, ctx) => {\n await opts.handler(args, ctx);\n },\n });\n },\n state,\n {\n persistState: () => {\n persistState(pi, state);\n },\n restoreOriginalState: async (ctx) => {\n if (isExtensionContext(ctx)) {\n await restoreOriginalState(pi, ctx, state);\n }\n },\n },\n );\n};\n","import type {\n BeforeAgentStartEvent,\n BeforeAgentStartEventResult,\n} from '@earendil-works/pi-coding-agent';\nimport { getModePrompt } from '@maestria/shared-pi/modes-core';\nimport path from 'node:path';\n\nimport type { MaestriaState } from '@/state.js';\n\nconst __dirname = import.meta.dirname;\nconst COMMANDS_DIR = path.resolve(__dirname, '../agents/commands');\n\n/**\n * Creates a before_agent_start handler that injects workflow mode prompts.\n *\n * This is the only dynamic prompt injection needed from the extension.\n * Static behavioral content (orchestrator prompt + global rules) is\n * auto-injected by Pi's skill system via SKILL.md files registered in\n * the pi.skills manifest field - the standard Pi extension pattern.\n *\n * When no mode is active, the handler returns an empty result (no modification),\n * letting Pi's built-in prompt assembly (skills + context files + tools)\n * stand as-is.\n */\nexport const createModePromptHandler =\n (state: MaestriaState) =>\n (event: BeforeAgentStartEvent, _ctx: object): BeforeAgentStartEventResult => {\n if (state.mode === null) {\n return {};\n }\n\n const parts: string[] = [\n event.systemPrompt,\n '',\n getModePrompt(state.mode, COMMANDS_DIR),\n '',\n `The user has set workflow mode to \"${state.mode}\". ` +\n 'Honor this mode throughout the session until changed via /command.',\n ];\n\n return { systemPrompt: parts.join('\\n') };\n };\n","import { Data, Effect } from 'effect';\n\n/** Terminal subagent statuses - agent will produce no more updates. */\nconst TERMINAL_STATUSES = new Set(['completed', 'steered', 'aborted', 'stopped', 'error']);\n\nexport interface SubagentRecord {\n status: string;\n result?: string;\n error?: string;\n}\n\nexport type SubagentPollFailureReason = 'aborted' | 'timeout' | 'missing';\n\n/**\n * Typed failures from the polling boundary.\n *\n * Keeping these failures in the Effect error channel lets parallel polling\n * interrupt sibling fibers while preserving enough context for the existing\n * tool-level handoff fallback.\n */\nexport class SubagentPollError extends Data.TaggedError('SubagentPollError')<{\n readonly id: string;\n readonly reason: SubagentPollFailureReason;\n readonly message: string;\n}> {}\n\nexport interface SubagentPollingService {\n getRecord: (id: string) => SubagentRecord | undefined;\n abort?: (id: string) => boolean;\n}\n\nexport interface PollSubagentOptions {\n readonly id: string;\n readonly label: string;\n readonly sendUpdates: boolean;\n readonly service: SubagentPollingService;\n readonly signal?: AbortSignal;\n readonly onUpdate?: (result: { content: { type: string; text: string }[] }) => void;\n readonly intervalMs?: number;\n readonly timeoutMs?: number;\n}\n\nconst createPollUpdateEffect = (options: PollSubagentOptions, polls: number) =>\n Effect.sync(() => {\n options.onUpdate?.({\n content: [\n {\n text: `${options.label} running... (${Math.round((polls * (options.intervalMs ?? 500)) / 1000)}s)`,\n type: 'text' as const,\n },\n ],\n });\n });\n\nconst pollLoop = (\n options: PollSubagentOptions,\n): Effect.Effect<SubagentRecord, SubagentPollError> => {\n const intervalMs = options.intervalMs ?? 500;\n const timeoutMs = options.timeoutMs ?? 180_000;\n const maxPolls = Math.ceil(timeoutMs / intervalMs);\n\n return Effect.gen(function* pollLoopEffect() {\n let polls = 0;\n let record = yield* Effect.sync(() => options.service.getRecord(options.id));\n\n while (record && !TERMINAL_STATUSES.has(record.status) && polls < maxPolls) {\n yield* Effect.sleep(intervalMs);\n record = yield* Effect.sync(() => options.service.getRecord(options.id));\n polls += 1;\n\n if (options.sendUpdates) {\n yield* createPollUpdateEffect(options, polls);\n }\n }\n\n if (record && !TERMINAL_STATUSES.has(record.status)) {\n return yield* Effect.fail(\n new SubagentPollError({\n id: options.id,\n message: `Subagent ${options.id} timed out after ${timeoutMs}ms`,\n reason: 'timeout',\n }),\n );\n }\n\n if (!record) {\n return yield* Effect.fail(\n new SubagentPollError({\n id: options.id,\n message: `Subagent ${options.id} was cleaned up before completion`,\n reason: 'missing',\n }),\n );\n }\n\n return record;\n });\n};\n\nconst abortEffect = (id: string, signal: AbortSignal): Effect.Effect<never, SubagentPollError> =>\n Effect.callback<never, SubagentPollError>((resume) => {\n const onAbort = () => {\n resume(\n Effect.fail(\n new SubagentPollError({\n id,\n message: 'Maestria subagent call aborted',\n reason: 'aborted',\n }),\n ),\n );\n };\n\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n\n return Effect.sync(() => {\n signal.removeEventListener('abort', onAbort);\n });\n });\n\n/**\n * Poll one subagent as a cancellable Effect.\n *\n * The host Pi API is Promise-based, so callers cross the boundary with\n * `Effect.runPromise`. Keeping the polling workflow as an Effect gives the\n * parallel dispatcher structured cancellation: a failed or aborted poll\n * interrupts its sibling poll fibers instead of leaving timers running.\n */\nexport const pollSubagentEffect = (\n options: PollSubagentOptions,\n): Effect.Effect<SubagentRecord, SubagentPollError> => {\n const poll = pollLoop(options);\n return options.signal ? Effect.raceFirst(poll, abortEffect(options.id, options.signal)) : poll;\n};\n","import { SUBAGENT_EVENTS } from '@gotgenes/pi-subagents';\nimport { MAESTRIA_EVENTS } from '@maestria/shared-pi/subagent-utils';\n\nimport type { MaestriaState } from '@/state.js';\nimport { persistState } from '@/state.js';\n\nexport interface SubagentEventHost {\n appendEntry: (type: string, data: unknown) => void;\n events?: {\n emit: (event: string, data: unknown) => void;\n on: (event: string, handler: (data: unknown) => void) => () => void;\n } | null;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst getStringField = (value: unknown, key: string): string | undefined => {\n if (!isRecord(value)) {\n return undefined;\n }\n const field = value[key];\n return typeof field === 'string' ? field : undefined;\n};\n\ntype PiEvents = NonNullable<SubagentEventHost['events']>;\n\nconst subscribeStarted = (\n events: PiEvents,\n pi: SubagentEventHost,\n state: MaestriaState,\n): (() => void) =>\n events.on(SUBAGENT_EVENTS.STARTED, (data: unknown) => {\n const id = getStringField(data, 'id');\n const type = getStringField(data, 'type') ?? 'unknown';\n if (id === undefined) {\n return;\n }\n state.subagentStatus[id] = { startedAt: Date.now(), status: 'running', type };\n persistState(pi, state);\n events.emit(MAESTRIA_EVENTS.SUBAGENT_STARTED, { id, timestamp: Date.now(), type });\n });\n\nconst subscribeCompleted = (\n events: PiEvents,\n pi: SubagentEventHost,\n state: MaestriaState,\n): (() => void) =>\n events.on(SUBAGENT_EVENTS.COMPLETED, (data: unknown) => {\n const id = getStringField(data, 'id');\n if (id === undefined) {\n return;\n }\n const existing = state.subagentStatus[id];\n if (existing !== null && existing !== undefined) {\n existing.status = 'completed';\n existing.completedAt = Date.now();\n }\n persistState(pi, state);\n events.emit(MAESTRIA_EVENTS.SUBAGENT_COMPLETED, {\n id,\n timestamp: Date.now(),\n type: existing?.type,\n });\n });\n\nconst subscribeFailed = (\n events: PiEvents,\n pi: SubagentEventHost,\n state: MaestriaState,\n): (() => void) =>\n events.on(SUBAGENT_EVENTS.FAILED, (data: unknown) => {\n const id = getStringField(data, 'id');\n if (id === undefined) {\n return;\n }\n const status = getStringField(data, 'status') ?? 'error';\n const existing = state.subagentStatus[id];\n if (existing !== null && existing !== undefined) {\n existing.status = status;\n existing.completedAt = Date.now();\n }\n persistState(pi, state);\n events.emit(MAESTRIA_EVENTS.SUBAGENT_FAILED, {\n id,\n timestamp: Date.now(),\n type: existing?.type,\n });\n });\n\nconst subscribeSteered = (\n events: PiEvents,\n pi: SubagentEventHost,\n state: MaestriaState,\n): (() => void) =>\n events.on(SUBAGENT_EVENTS.STEERED, (data: unknown) => {\n const id = getStringField(data, 'id');\n if (id === undefined) {\n return;\n }\n state.subagentStatus[id] ??= { startedAt: Date.now(), status: 'running', type: 'unknown' };\n persistState(pi, state);\n });\n\nexport const subscribeSubagentEvents = (\n pi: SubagentEventHost,\n state: MaestriaState,\n cleanups?: (() => void)[],\n): void => {\n const { events } = pi;\n if (events === null || events === undefined) {\n return;\n }\n const subscriptions = [\n subscribeStarted(events, pi, state),\n subscribeCompleted(events, pi, state),\n subscribeFailed(events, pi, state),\n subscribeSteered(events, pi, state),\n ];\n cleanups?.push(...subscriptions);\n};\n","import type { AgentToolUpdateCallback } from '@earendil-works/pi-coding-agent';\nimport {\n ALLOWED_AGENTS,\n assertNonEmptyTask as assertTaskContract,\n assertValidAgent,\n} from '@maestria/shared-pi/subagent-utils';\nimport { Effect } from 'effect';\nimport { Type } from 'typebox';\nimport type { Static } from 'typebox';\n\nimport type { MaestriaState } from '@/state.js';\nimport { persistState, recordHandoff, recordSpecialistDelegated } from '@/state.js';\nimport { pollSubagentEffect } from '@/subagent-polling.js';\nimport type { SubagentPollingService, SubagentRecord } from '@/subagent-polling.js';\nimport { subscribeSubagentEvents } from '@/subagent-events.js';\nimport type { SubagentEventHost } from '@/subagent-events.js';\n\nconst ALLOWED_AGENT_NAMES: readonly string[] = ALLOWED_AGENTS;\n\nexport const POLL_TIMEOUT_MS = 180_000;\nexport const POLL_INTERVAL_MS = 500;\nexport const MAX_PARALLEL_TASKS = 8;\n\ntype SubagentSpawnService = SubagentPollingService & {\n spawn: (\n agent: string,\n task: string,\n opts: { description: string; foreground: boolean; inheritContext: boolean },\n ) => string;\n};\n\ninterface SubagentTask {\n agent: string;\n task: string;\n}\nexport interface SubagentParams {\n agent?: string;\n task?: string;\n tasks?: SubagentTask[];\n mode?: string;\n}\ninterface ToolUpdate {\n content: { type: string; text: string }[];\n details?: Record<string, unknown>;\n}\ntype ToolUpdateHandler = ((result: ToolUpdate) => void) | undefined;\nexport type PiToolUpdateHandler = AgentToolUpdateCallback<Record<string, unknown>> | undefined;\nexport interface ToolResult {\n content: { text: string; type: 'text' }[];\n details: Record<string, unknown>;\n}\n\nexport interface SubagentToolDefinition {\n description: string;\n execute: (\n toolCallId: string,\n params: SubagentParams,\n signal: AbortSignal | undefined,\n onUpdate: PiToolUpdateHandler,\n ctx: unknown,\n ) => Promise<ToolResult>;\n label: string;\n name: string;\n parameters: typeof SUBAGENT_PARAMETERS;\n promptGuidelines?: string[];\n promptSnippet?: string;\n}\n\nexport interface SubagentToolApi extends SubagentEventHost {\n registerTool: (tool: SubagentToolDefinition) => void;\n}\n\nconst assertTask: (task: string | undefined, label: string) => asserts task is string =\n assertTaskContract;\nconst assertAgent: (agent: string) => void = assertValidAgent;\n\nconst abortSubagents = (service: SubagentPollingService, ids: readonly string[]): void => {\n if (typeof service.abort !== 'function') {\n return;\n }\n for (const id of ids) {\n try {\n service.abort(id);\n } catch {\n // Best-effort cleanup\n }\n }\n};\n\nconst pollSubagentOrAbortEffect = (options: Parameters<typeof pollSubagentEffect>[0]) =>\n Effect.tapError(pollSubagentEffect(options), () =>\n Effect.sync(() => {\n abortSubagents(options.service, [options.id]);\n }),\n );\n\nconst recordAndPersist = (\n pi: SubagentEventHost,\n state: MaestriaState,\n agentName: string,\n taskText: string,\n): void => {\n const updatedState = recordSpecialistDelegated(\n recordHandoff(state, 'orchestrator', agentName, taskText),\n agentName,\n );\n Object.assign(state, updatedState);\n persistState(pi, state);\n};\n\nconst validatePiParams = (params: SubagentParams): string => {\n const mode = params.mode ?? 'single';\n if (mode === 'single') {\n if (\n params.agent === undefined ||\n params.agent === null ||\n params.agent === '' ||\n !ALLOWED_AGENT_NAMES.includes(params.agent)\n ) {\n return `Invalid maestria_subagent call: 'agent' is required and must be one of ${ALLOWED_AGENT_NAMES.join(', ')}.`;\n }\n assertTask(params.task, 'Task description is required');\n } else if (mode === 'parallel') {\n if (!params.tasks || params.tasks.length < 2) {\n throw new Error('For parallel mode, tasks array is required with at least 2 items');\n }\n if (params.tasks.length > MAX_PARALLEL_TASKS) {\n throw new Error(\n `For parallel mode, tasks array may have at most ${MAX_PARALLEL_TASKS} items (got ${params.tasks.length})`,\n );\n }\n for (const t of params.tasks) {\n assertAgent(t.agent);\n assertTask(t.task, 'Task description is required for all tasks');\n }\n } else if (mode === 'chain') {\n if (!params.tasks || params.tasks.length < 2) {\n throw new Error('For chain mode, tasks array is required with at least 2 items');\n }\n for (const t of params.tasks) {\n assertAgent(t.agent);\n assertTask(t.task, 'Task description is required for all tasks');\n }\n }\n return mode;\n};\n\nconst handleSingleMode = async (\n pi: SubagentEventHost,\n state: MaestriaState,\n service: SubagentSpawnService,\n agent: string,\n task: string,\n signal: AbortSignal | undefined,\n onUpdate: ToolUpdateHandler,\n): Promise<ToolResult> => {\n const id = service.spawn(agent, task, {\n description: task.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n recordAndPersist(pi, state, agent, task);\n const record = await Effect.runPromise(\n pollSubagentOrAbortEffect({\n id,\n intervalMs: POLL_INTERVAL_MS,\n label: `Subagent ${agent}`,\n onUpdate,\n sendUpdates: true,\n service,\n signal,\n timeoutMs: POLL_TIMEOUT_MS,\n }),\n );\n return {\n content: [{ text: record.result ?? record.error ?? 'No output.', type: 'text' as const }],\n details: { subagentId: id },\n };\n};\n\ntype ParallelOutcome = { error: unknown } | { record: SubagentRecord };\n\nconst spawnParallelSubagents = (\n pi: SubagentEventHost,\n state: MaestriaState,\n service: SubagentSpawnService,\n taskList: SubagentTask[],\n): string[] => {\n const spawnedIds: string[] = [];\n try {\n for (const task of taskList) {\n const id = service.spawn(task.agent, task.task, {\n description: task.task.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n spawnedIds.push(id);\n recordAndPersist(pi, state, task.agent, task.task);\n }\n } catch (error) {\n abortSubagents(service, spawnedIds);\n throw error;\n }\n return spawnedIds;\n};\n\nconst pollParallelSubagents = async (\n spawnedIds: string[],\n taskList: SubagentTask[],\n service: SubagentSpawnService,\n signal: AbortSignal | undefined,\n onUpdate: ToolUpdateHandler,\n): Promise<ParallelOutcome[]> =>\n await Effect.runPromise(\n Effect.all(\n spawnedIds.map((id, index) => {\n const task = taskList[index];\n return Effect.match(\n pollSubagentEffect({\n id,\n intervalMs: POLL_INTERVAL_MS,\n label: `${task.agent} (${index + 1}/${taskList.length})`,\n onUpdate,\n sendUpdates: false,\n service,\n signal,\n timeoutMs: POLL_TIMEOUT_MS,\n }),\n {\n onFailure: (error) => {\n abortSubagents(service, spawnedIds);\n return { error };\n },\n onSuccess: (record) => ({ record }),\n },\n );\n }),\n { concurrency: 'unbounded' },\n ),\n );\n\nconst renderParallelResults = (\n taskList: SubagentTask[],\n spawnedIds: string[],\n outcomes: ParallelOutcome[],\n): ToolResult => {\n const parts = [`## Parallel Results (${taskList.length} tasks)\\n`];\n for (const [index, task] of taskList.entries()) {\n const outcome = outcomes[index];\n parts.push(`### ${index + 1}: ${task.agent}`);\n if ('error' in outcome) {\n parts.push(\n `⚠️ ${outcome.error instanceof Error ? outcome.error.message : String(outcome.error)}`,\n );\n } else {\n parts.push(outcome.record.result ?? outcome.record.error ?? 'No output.');\n }\n }\n return {\n content: [{ text: parts.join('\\n\\n'), type: 'text' as const }],\n details: { subagentIds: spawnedIds },\n };\n};\n\nconst handleParallelMode = async (\n pi: SubagentEventHost,\n state: MaestriaState,\n service: SubagentSpawnService,\n taskList: SubagentTask[],\n signal: AbortSignal | undefined,\n onUpdate: ToolUpdateHandler,\n): Promise<ToolResult> => {\n onUpdate?.({\n content: [{ text: `Spawning ${taskList.length} parallel subagents...`, type: 'text' }],\n });\n const spawnedIds = spawnParallelSubagents(pi, state, service, taskList);\n const outcomes = await pollParallelSubagents(spawnedIds, taskList, service, signal, onUpdate);\n onUpdate?.({\n content: [{ text: `All ${taskList.length} parallel subagents settled.`, type: 'text' }],\n });\n return renderParallelResults(taskList, spawnedIds, outcomes);\n};\n\nconst substitutePreviousResult = (taskText: string, previousResult: string): string =>\n taskText.replaceAll('{previous}', () => previousResult);\n\nconst runChainSteps = async (\n pi: SubagentEventHost,\n state: MaestriaState,\n service: SubagentSpawnService,\n taskList: SubagentTask[],\n signal: AbortSignal | undefined,\n onUpdate: ToolUpdateHandler,\n index: number,\n previousResult: string,\n): Promise<string> => {\n if (index >= taskList.length) {\n return previousResult;\n }\n\n const task = taskList[index];\n const taskText = index > 0 ? substitutePreviousResult(task.task, previousResult) : task.task;\n const id = service.spawn(task.agent, taskText, {\n description: taskText.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n recordAndPersist(pi, state, task.agent, taskText);\n onUpdate?.({\n content: [\n {\n text: `Chain step ${index + 1}/${taskList.length}: ${task.agent} running...`,\n type: 'text',\n },\n ],\n });\n\n let nextResult: string;\n try {\n const record = await Effect.runPromise(\n pollSubagentOrAbortEffect({\n id,\n intervalMs: POLL_INTERVAL_MS,\n label: `Chain step ${index + 1}: ${task.agent}`,\n onUpdate,\n sendUpdates: true,\n service,\n signal,\n timeoutMs: POLL_TIMEOUT_MS,\n }),\n );\n nextResult = record.result ?? record.error ?? 'No output.';\n } catch (error) {\n return `[error] ${error instanceof Error ? error.message : String(error)}`;\n }\n\n if (index < taskList.length - 1) {\n onUpdate?.({\n content: [\n {\n text: `Chain step ${index + 1}/${taskList.length}: ${task.agent} completed. Moving to next step.`,\n type: 'text',\n },\n ],\n });\n }\n\n return await runChainSteps(pi, state, service, taskList, signal, onUpdate, index + 1, nextResult);\n};\n\nconst handleChainMode = async (\n pi: SubagentEventHost,\n state: MaestriaState,\n service: SubagentSpawnService,\n taskList: SubagentTask[],\n signal: AbortSignal | undefined,\n onUpdate: ToolUpdateHandler,\n): Promise<ToolResult> => ({\n content: [\n {\n text: await runChainSteps(pi, state, service, taskList, signal, onUpdate, 0, ''),\n type: 'text',\n },\n ],\n details: { subagentId: 'chain-completed' },\n});\n\nconst dispatchByMode = async (\n pi: SubagentEventHost,\n state: MaestriaState,\n service: SubagentSpawnService,\n params: SubagentParams,\n signal: AbortSignal | undefined,\n onUpdate: ToolUpdateHandler,\n): Promise<ToolResult> => {\n const mode = params.mode ?? 'single';\n if (mode === 'single') {\n if (typeof params.agent !== 'string' || typeof params.task !== 'string') {\n throw new TypeError('Single mode requires an agent and task');\n }\n return await handleSingleMode(pi, state, service, params.agent, params.task, signal, onUpdate);\n }\n if ((mode === 'parallel' || mode === 'chain') && Array.isArray(params.tasks)) {\n return await (mode === 'parallel'\n ? handleParallelMode(pi, state, service, params.tasks, signal, onUpdate)\n : handleChainMode(pi, state, service, params.tasks, signal, onUpdate));\n }\n throw new Error('Unknown dispatch mode');\n};\n\nexport const SUBAGENT_PARAMETERS = Type.Object({\n agent: Type.String({\n description:\n 'Specialist agent name (required): adventurer, architect, builder, diagnose, planner, reviewer, writer',\n }),\n mode: Type.Optional(\n Type.Union([Type.Literal('parallel'), Type.Literal('chain'), Type.Literal('single')]),\n ),\n task: Type.String({ description: 'Task description for the subagent (required)' }),\n tasks: Type.Optional(\n Type.Array(Type.Object({ agent: Type.String(), task: Type.String() }), {\n description: 'Array of task objects for parallel or chain dispatch',\n }),\n ),\n});\n\nexport type SubagentToolParams = Static<typeof SUBAGENT_PARAMETERS>;\n\nconst unavailableResult = (): ToolResult => ({\n content: [\n {\n text: [\n '## Subagent Dispatch Unavailable',\n '',\n 'The `@gotgenes/pi-subagents` extension is required for subagent dispatch but has not been loaded.',\n '',\n 'Install it as a Pi extension:',\n '',\n '```',\n 'pi install npm:@gotgenes/pi-subagents',\n '```',\n '',\n 'Then restart your Pi session.',\n ].join('\\n'),\n type: 'text',\n },\n ],\n details: {},\n});\n\nconst handoffResult = (agentName: string, taskDesc: string): ToolResult => ({\n content: [\n {\n text: [\n '## Subagent Handoff Required',\n '',\n '**From:** orchestrator',\n `**To:** ${agentName}`,\n `**Task:** ${taskDesc}`,\n '',\n 'Subagent dispatch failed. Please delegate this work manually.',\n ].join('\\n'),\n type: 'text',\n },\n ],\n details: {},\n});\n\nconst executeSubagent = async (\n pi: SubagentEventHost,\n state: MaestriaState,\n params: SubagentParams,\n signal: AbortSignal | undefined,\n onUpdate: ToolUpdateHandler,\n): Promise<ToolResult> => {\n const { getSubagentsService } = await import('@gotgenes/pi-subagents');\n const service = getSubagentsService();\n if (!service || typeof service.spawn !== 'function') {\n return unavailableResult();\n }\n try {\n return await dispatchByMode(pi, state, service, params, signal, onUpdate);\n } catch (error) {\n console.warn('[maestria] Subagent dispatch failed:', error);\n const agentName = params.agent ?? params.tasks?.[0]?.agent ?? 'unknown';\n const taskDesc = params.task ?? params.tasks?.map((task) => task.task).join('; ') ?? 'unknown';\n return handoffResult(agentName, taskDesc);\n }\n};\n\nconst createSubagentTool = (\n pi: SubagentEventHost,\n state: MaestriaState,\n): SubagentToolDefinition => ({\n description: 'Dispatch a task to a @gotgenes/pi-subagents specialist subagent',\n async execute(\n _toolCallId: string,\n params: SubagentParams,\n signal: AbortSignal | undefined,\n onUpdate: PiToolUpdateHandler,\n _ctx: unknown,\n ): Promise<ToolResult> {\n if (state.reviewMode) {\n return {\n content: [\n {\n text: 'Subagent dispatch is not available during review mode. Use /restore-model to exit review mode first.',\n type: 'text',\n },\n ],\n details: {},\n };\n }\n const mode = validatePiParams(params);\n if (mode.startsWith('Invalid')) {\n return {\n content: [\n {\n text: `${mode} Re-dispatch with a valid agent name; the orchestrator may continue read-only exploration while the brief is corrected.`,\n type: 'text',\n },\n ],\n details: {},\n };\n }\n const updateHandler: ToolUpdateHandler = onUpdate\n ? (result) => {\n onUpdate({\n content: result.content.map(({ text }) => ({ text, type: 'text' as const })),\n details: result.details ?? {},\n });\n }\n : undefined;\n return await executeSubagent(pi, state, params, signal, updateHandler);\n },\n label: 'Maestria Subagent',\n name: 'maestria_subagent',\n parameters: SUBAGENT_PARAMETERS,\n promptGuidelines: [\n 'Use maestria_subagent when a task MUST be delegated to a specialist subagent rather than handled directly. Each specialist has focused capabilities: adventurer (recon), architect (design), builder (impl), planner (planning), diagnose (bugs), reviewer (QA), writer (docs).',\n ],\n promptSnippet:\n 'Delegate tasks to @maestria specialist subagents (adventurer, architect, builder, planner, diagnose, reviewer, writer)',\n});\n\nexport const installSubagentTool = (\n pi: SubagentToolApi,\n state: MaestriaState,\n cleanups?: (() => void)[],\n): void => {\n pi.registerTool(createSubagentTool(pi, state));\n subscribeSubagentEvents(pi, state, cleanups);\n};\n","import { defineTool } from '@earendil-works/pi-coding-agent';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nimport type {\n PiToolUpdateHandler,\n SubagentToolApi,\n SubagentToolDefinition,\n SubagentToolParams,\n ToolResult,\n} from '@/subagent.js';\n\nexport const createSubagentToolApi = (pi: ExtensionAPI): SubagentToolApi => ({\n appendEntry: (type, data) => {\n pi.appendEntry(type, data);\n },\n events: pi.events,\n registerTool: (tool: SubagentToolDefinition) => {\n pi.registerTool(\n defineTool({\n ...tool,\n async execute(\n toolCallId: string,\n params: SubagentToolParams,\n signal: AbortSignal | undefined,\n onUpdate: PiToolUpdateHandler,\n ctx: ExtensionContext,\n ): Promise<ToolResult> {\n return await tool.execute(toolCallId, params, signal, onUpdate, ctx);\n },\n }),\n );\n },\n});\n","/**\n * Shared tool interceptor utilities for Maestria platform packages.\n *\n * Pure TypeScript - no platform-specific dependencies.\n * Imported by both @maestria/omp and @maestria/pi to eliminate duplication.\n *\n * @module\n */\n\nimport {\n persistState as persistStateCore,\n recordFileModified,\n recordFileRead,\n} from './state-core.js';\nimport type { MaestriaState } from './state-core.js';\n\n/**\n * Dangerous bash command patterns that should always be blocked,\n * regardless of mode or specialist role.\n */\nexport const DANGEROUS_PATTERNS = [\n /rm\\s+-rf\\s+\\//u,\n /dd\\s+if=/u,\n />\\s*\\/dev\\/sd/u,\n /chmod\\s+-R\\s+777\\s+\\//u,\n /mkfs\\.\\w+/u,\n /:\\(\\)\\{ :\\|:& \\};:/u,\n />\\s*\\/etc\\/(?<targetFile>passwd|shadow|sudoers)/u,\n /\\beval\\b/u,\n /wget\\s+-O\\s*-\\s*\\|\\s*(?<wgetShell>bash|sh)/u,\n /curl\\s+.*\\|\\s*(?<curlShell>bash|sh)/u,\n /crontab\\s+-r/u,\n];\n\n/**\n * Read-only bash command prefixes allowed for the orchestrator's recon and\n * verification. Anything not matching - or chaining into a mutation - is\n * blocked; mutations belong to specialists.\n */\nconst READ_ONLY_BASH_PREFIX =\n /^(?<command>ls|cat|head|tail|git status|git diff|git log|git branch|find|grep|rg|pnpm test|npm test|pwd|which)\\b/u;\n\n/**\n * True when a bash command performs no mutation.\n *\n * A naive prefix check is bypassable - `git status && git checkout .` or\n * `ls; rm -rf dist` both pass a prefix-only match - so every segment of a\n * chained command (`;`, `&&`, `||`, `|`, or newline) must itself be\n * read-only, and command substitution (`$(...)`, backticks) and output\n * redirection (`>` / `>>`) are rejected because they can hide a mutation\n * behind a read-only prefix. `2>&1`-style fd redirects are allowed (they\n * don't write).\n */\nexport const isReadOnlyBashCommand = (rawCommand: string): boolean => {\n const command = rawCommand.trim();\n if (command.includes('$(') || command.includes('`')) {\n return false;\n }\n // Strip `2>&1`-style fd redirects first so the `&` inside them is not\n // mistaken for a command separator and the `>` is not counted as output\n // redirection.\n const withoutFdRedirects = command.replaceAll(/\\d?>&[12]/gu, '');\n if (withoutFdRedirects.includes('>')) {\n return false;\n }\n return withoutFdRedirects\n .split(/[\\n;&|]+/u)\n .every((segment) => READ_ONLY_BASH_PREFIX.test(segment.trim()));\n};\n\n// ── Pure helpers ──\n\nexport const findDangerousPattern = (command: string): RegExp | null => {\n for (const pattern of DANGEROUS_PATTERNS) {\n if (pattern.test(command)) {\n return pattern;\n }\n }\n return null;\n};\n\n/** Alias for findDangerousPattern - returns matching pattern or null. */\nexport const isDangerousCommand = findDangerousPattern;\n\nexport const shouldBlockForOrchestrator = (\n state: { mode: unknown },\n activeTools: string[],\n delegationTool: string,\n): boolean => state.mode !== null && activeTools.includes(delegationTool);\n\nexport const getBlockedReviewReason = (toolName: string): string | null => {\n if (toolName === 'edit' || toolName === 'write' || toolName === 'bash') {\n return 'Review mode is active. Report findings, do not edit.';\n }\n return null;\n};\n\nexport const isOrchestratorBlocked = (\n state: { mode: unknown },\n activeTools: string[],\n delegationTool: string,\n): boolean => shouldBlockForOrchestrator(state, activeTools, delegationTool);\n\nexport const findDangerousPatternForCommand = (command: string): RegExp | null =>\n findDangerousPattern(command);\n\n// ── Factory ──\n\nexport interface ToolCallEventLike {\n toolName?: string;\n input?: unknown;\n}\n\nexport interface ToolCallContext {\n hasUI?: boolean;\n ui?: { confirm: (title: string, msg: string) => Promise<boolean> };\n}\n\nexport interface ToolCallResult {\n block: boolean;\n reason: string;\n}\n\nexport type ToolCallHandler = (\n event: ToolCallEventLike,\n ctx: ToolCallContext,\n) => Promise<ToolCallResult | undefined>;\n\nexport interface ToolCallHandlerOptions {\n getState: () => MaestriaState;\n getActiveTools: () => string[];\n delegationTool: string;\n delegationHint?: string;\n extraMutations?: string[];\n isMutationTool?: (event: ToolCallEventLike) => boolean;\n isReadTool: (event: ToolCallEventLike) => boolean;\n isWriteTool: (event: ToolCallEventLike) => boolean;\n isBashTool: (event: ToolCallEventLike) => boolean;\n persist?: () => void;\n pi?: { appendEntry: (type: string, data: unknown) => void };\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst resolveDelegationHint = (delegationTool: string, hint?: string): string =>\n hint ??\n (delegationTool === 'task'\n ? \"Use 'maestria_subagent' or 'task()' to delegate mutations to specialists.\"\n : \"Use 'maestria_subagent' to delegate mutations to specialists.\");\n\nconst checkOrchestratorBlock = (\n state: MaestriaState,\n event: ToolCallEventLike,\n options: ToolCallHandlerOptions,\n delegationTool: string,\n hint: string,\n): { block: boolean; reason: string } | undefined => {\n if (state.mode === null || !options.getActiveTools().some((t) => t === delegationTool)) {\n return undefined;\n }\n const isMutationTool =\n options.isMutationTool ??\n ((e: ToolCallEventLike) => {\n const name = e.toolName ?? '';\n const base = name === 'edit' || name === 'write' || name === 'patch' || name === 'bash';\n if (base) {\n return true;\n }\n return options.extraMutations?.some((m) => m === name) === true;\n });\n if (!isMutationTool(event) || event.toolName === delegationTool) {\n return undefined;\n }\n if (options.isBashTool(event)) {\n const input = isRecord(event.input) ? event.input : undefined;\n const command = typeof input?.command === 'string' ? input.command : '';\n if (isReadOnlyBashCommand(command)) {\n return undefined;\n }\n }\n return {\n block: true,\n reason: `Tool '${event.toolName}' is blocked for the orchestrator. ${hint}`,\n };\n};\n\nconst checkDangerousPattern = async (\n event: ToolCallEventLike,\n options: ToolCallHandlerOptions,\n ctx: ToolCallContext,\n): Promise<{ block: boolean; reason: string } | undefined> => {\n if (!options.isBashTool(event)) {\n return undefined;\n }\n const input = isRecord(event.input) ? event.input : undefined;\n if (!input) {\n return undefined;\n }\n const { command } = input;\n if (typeof command !== 'string' || !command) {\n return undefined;\n }\n const matched = findDangerousPattern(command);\n if (!matched) {\n return undefined;\n }\n if (ctx.hasUI === true && ctx.ui) {\n const confirmed = await ctx.ui.confirm(\n 'Dangerous Pattern Detected',\n `This command matches a dangerous pattern:\\n${command}\\nProceed?`,\n );\n if (confirmed) {\n return undefined;\n }\n }\n return { block: true, reason: `Command matches dangerous pattern: ${matched}` };\n};\n\nconst trackFileAccess = (\n state: MaestriaState,\n event: ToolCallEventLike,\n options: ToolCallHandlerOptions,\n): boolean => {\n if (options.isReadTool(event)) {\n const p = isRecord(event.input) ? event.input.path : undefined;\n if (typeof p === 'string' && p) {\n Object.assign(state, recordFileRead(state, p));\n return true;\n }\n } else if (options.isWriteTool(event)) {\n const p = isRecord(event.input) ? event.input.path : undefined;\n if (typeof p === 'string' && p) {\n Object.assign(state, recordFileModified(state, p));\n return true;\n }\n }\n return false;\n};\n\nexport const createToolCallHandler = (options: ToolCallHandlerOptions): ToolCallHandler => {\n const { delegationTool } = options;\n const hint = resolveDelegationHint(delegationTool, options.delegationHint);\n const doPersist = (): void => {\n if (options.persist) {\n options.persist();\n return;\n }\n if (options.pi) {\n persistStateCore(options.pi, options.getState());\n }\n };\n return async (\n event: ToolCallEventLike,\n ctx: ToolCallContext,\n ): Promise<{ block: boolean; reason: string } | undefined> => {\n if (event.toolName === undefined || event.toolName === '') {\n return undefined;\n }\n const state = options.getState();\n const { toolName } = event;\n const orchestrator = checkOrchestratorBlock(state, event, options, delegationTool, hint);\n if (orchestrator) {\n return orchestrator;\n }\n if (state.reviewMode && (options.isWriteTool(event) || options.isBashTool(event))) {\n const reason =\n getBlockedReviewReason(toolName) ?? 'Review mode is active. Report findings, do not edit.';\n return { block: true, reason };\n }\n const dangerous = await checkDangerousPattern(event, options, ctx);\n if (dangerous) {\n return dangerous;\n }\n if (trackFileAccess(state, event, options)) {\n doPersist();\n }\n return undefined;\n };\n};\n","import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport { createToolCallHandler } from '@maestria/shared-pi/tools-core';\nimport type { ToolCallHandler } from '@maestria/shared-pi/tools-core';\n\nimport type { MaestriaState } from '@/state.js';\nimport { persistState } from '@/state.js';\n\nexport interface ToolApi {\n appendEntry: (type: string, data: unknown) => void;\n getActiveTools: () => string[];\n on: (event: 'tool_call', handler: ToolCallHandler) => void;\n}\n\nexport const createToolApi = (pi: ExtensionAPI): ToolApi => ({\n appendEntry: (type, data) => {\n pi.appendEntry(type, data);\n },\n getActiveTools: () => pi.getActiveTools(),\n on: (_event, handler) => {\n pi.on('tool_call', async (event, ctx) => await handler(event, ctx));\n },\n});\n\nexport const installToolInterceptors = (pi: ToolApi, state: MaestriaState): void => {\n const handler = createToolCallHandler({\n delegationTool: 'subagent',\n getActiveTools: () => pi.getActiveTools(),\n getState: () => state,\n isBashTool: (e) => e.toolName === 'bash',\n isMutationTool: (e) =>\n e.toolName === 'edit' ||\n e.toolName === 'write' ||\n e.toolName === 'patch' ||\n e.toolName === 'bash',\n isReadTool: (e) => e.toolName === 'read',\n isWriteTool: (e) => e.toolName === 'edit' || e.toolName === 'write',\n persist: () => {\n persistState(pi, state);\n },\n });\n pi.on('tool_call', handler);\n};\n","import type {\n ExtensionAPI,\n ExtensionContext,\n SessionStartEvent,\n SessionTreeEvent,\n} from '@earendil-works/pi-coding-agent';\n\nimport { deploySpecialistAgents } from '@/agents.js';\nimport { createCommandsApi, installCommands } from '@/commands.js';\nimport { createCompactionApi, installCompactionHandlers } from '@/compaction.js';\nimport { createModeCommandsApi, installModeAutoDetect, installModeCommands } from '@/modes.js';\nimport { createModePromptHandler } from '@/rules.js';\nimport { createInitialState } from '@/state.js';\nimport type { MaestriaState } from '@/state.js';\nimport { installSubagentTool } from '@/subagent.js';\nimport { createSubagentToolApi } from '@/subagent-api.js';\nimport { createToolApi, installToolInterceptors } from '@/tools.js';\n\ninterface PersistedStateEntry {\n type: string;\n customType?: string;\n data?: unknown;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst currentSessionEntries = (ctx: ExtensionContext): PersistedStateEntry[] | null => {\n // getBranch() is the public current-session view and avoids restoring state\n // from a sibling branch in the same session tree. Never fall back to\n // getEntries(), which spans the entire session tree.\n const sessionManager = ctx?.sessionManager;\n if (typeof sessionManager?.getBranch !== 'function') {\n return null;\n }\n\n const branch = sessionManager.getBranch();\n return Array.isArray(branch) ? branch : null;\n};\n\nconst clearState = (state: MaestriaState): void => {\n for (const key of Object.keys(state)) {\n Reflect.deleteProperty(state, key);\n }\n};\n\nconst restoreStateFromSession = (state: MaestriaState, ctx: ExtensionContext): void => {\n const next = createInitialState();\n const entries = currentSessionEntries(ctx);\n\n if (!entries) {\n clearState(state);\n Object.assign(state, next);\n return;\n }\n\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const entry = entries[i];\n if (entry.type === 'custom' && entry.customType === 'maestria_state') {\n if (isRecord(entry.data)) {\n Object.assign(next, entry.data);\n }\n break;\n }\n }\n\n clearState(state);\n Object.assign(state, next);\n};\n\nconst extension = (pi: ExtensionAPI): void => {\n const state = createInitialState();\n const cleanups: (() => void)[] = [];\n\n // Install mode commands: /fein, /sonar, /blitz\n installModeCommands(createModeCommandsApi(pi), state);\n installModeAutoDetect(pi, state);\n\n // Inject mode prompt when a workflow mode is active\n const handleModePrompt = createModePromptHandler(state);\n\n pi.on('before_agent_start', (event, ctx) => handleModePrompt(event, ctx));\n\n // Deploy specialist agent files for pi-subagents discovery\n pi.on('session_start', (_event: SessionStartEvent, ctx) => {\n deploySpecialistAgents(ctx);\n\n // Restore persisted state on session start (reload/resume/fork)\n restoreStateFromSession(state, ctx);\n });\n\n // Rehydrate state when navigating the session tree to a different branch\n pi.on('session_tree', (_event: SessionTreeEvent, ctx) => {\n restoreStateFromSession(state, ctx);\n });\n\n // Install compaction preservation handlers\n installCompactionHandlers(createCompactionApi(pi), state);\n\n // Install orchestration hooks: subagent tool and commands\n installSubagentTool(createSubagentToolApi(pi), state, cleanups);\n installCommands(createCommandsApi(pi), state);\n\n // Cleanup subscriptions on shutdown\n pi.on('session_shutdown', () => {\n for (const cleanup of cleanups) {\n cleanup();\n }\n cleanups.length = 0;\n });\n\n // Install tool call interceptors for review mode and dangerous patterns\n installToolInterceptors(createToolApi(pi), state);\n};\n\nexport default extension;\n"],"mappings":"mVAUA,MAAa,EAAkB,CAC7B,iBAAkB,4BAClB,mBAAoB,8BACpB,mBAAoB,8BACpB,gBAAiB,2BACjB,iBAAkB,2BACpB,EAGa,EAAiB,CAC5B,aACA,YACA,UACA,WACA,UACA,WACA,QACF,EA0Ba,EAAoB,GAAiD,CAChF,GAAI,CAAC,EAAe,KAAM,GAAiB,IAAiB,CAAK,EAC/D,M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