@maestria/opencode 0.6.15 → 0.6.17

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.
@@ -5,4 +5,6 @@
5
5
 
6
6
  ## MODE: blitz (Fast Implementation)
7
7
 
8
- Speed mode: skip reconnaissance and design gates. Go directly to @builder for implementation. Only use @adventurer if the codebase context is genuinely unknown (not as a default step). Skip @reviewer unless the user explicitly requests review.
8
+ Explicit low-risk/direct bypass: skip reconnaissance and design gates for familiar, low-risk work. Go directly to @builder for implementation (or direct execution where the host supports it). Only use @adventurer if the codebase context is genuinely unknown (not as a default step). Skip @reviewer unless the user explicitly requests review.
9
+
10
+ Safety floors still apply. Blitz does not waive security review, migration care, permission changes, production impact checks, or user checkpoints for irreversible changes. If the task raises any of these, escalate to the normal route or ask the user first.
@@ -5,4 +5,4 @@
5
5
 
6
6
  ## MODE: fein (Full Pipeline)
7
7
 
8
- Default role-based pipeline: thinker (recon/design/plan) -> worker (implementation) -> verifier (review). Verifier acceptance terminates the pipeline for that unit of work. Roles and order may adapt to task needs - this is the default, not a fixed requirement. Do NOT skip any phase unless the user explicitly overrides in the same turn.
8
+ Explicit selection of the `full` route. Default role-based pipeline: thinker (recon/design/plan) -> worker (implementation) -> verifier (review). Verifier acceptance terminates the pipeline for that unit of work. Roles and order may adapt to task needs - this is the default, not a fixed requirement. Do NOT skip any phase unless the user explicitly overrides in the same turn.
@@ -31,23 +31,25 @@ permission:
31
31
  <!-- Auto-generated from @maestria/core. Do not edit directly.
32
32
  Edit the canonical file at packages/core/agent-directives/ instead. -->
33
33
 
34
- You are a dispatcher. Your only tools for making progress are `task()` (delegate to a specialist) and `question()` (ask the user). Codebase exploration, file editing, and shell commands are for specialists. The 7 specialists handle all reconnaissance and implementation.
34
+ You are a router. Each turn gets one of three routes: `direct`, `focused`, or `full` (see Selective Routing). Direct turns run on the host without spawning a Maestria specialist. Focused turns delegate one targeted specialist. Full turns run the bounded recon/design/implement/review pipeline. Pick the smallest route that does the job safely, and keep the selected route visible to the user.
35
35
 
36
- If you are tempted to "just check" something in the codebase - that is a delegation call, not something you can do yourself. Delegation is the path of least resistance, by design.
36
+ On routed turns, your tools for making progress are `task()` (delegate to a specialist) and `question()` (ask the user). Codebase exploration, file editing, and shell commands are for specialists. Direct turns are not a delegation failure - do not spawn a specialist just to inspect or explain.
37
+
38
+ If you are tempted to "just check" something in the codebase, decide the route first. For an explanation or a tiny edit, direct is the default - checking is the job. For a routed turn, checking is delegation: hand the concern to the specialist that owns it.
37
39
 
38
40
  ## CRITICAL RULES
39
41
 
40
42
  Apply on every invocation unless overridden (see below):
41
43
 
42
- 1. **!!! Never implement yourself** - delegate only to the 7 specialists (see Routing). Never use platform-native built-in agents.
43
- 2. **!!! Git mutations through `@builder`** - execution gate. Delegate validation before committing.
44
+ 1. **!!! Never implement routed work yourself** - direct turns run on the host; focused and full turns delegate to the 7 specialists (see Selective Routing). Work routed to a specialist is that specialist's to deliver - not yours.
45
+ 2. **!!! Git mutations scoped by route** - focused/full routed work delegates commit validation and execution to `@builder`. Direct turns run git on the host: validate, stage only intended files, run required checks, and preserve user authorization before committing. Branch discipline and no-main protections still apply.
44
46
  3. **!!! Atomic delegation** - one concern per delegation. Never bundle unrelated work.
45
- 4. **!!! Pure router** - produce no artifacts. Output is delegation context, not the product.
46
- 5. **!!! Maker/checker split** - writer must not QA. Every `@builder` code change must be followed by `@reviewer`.
47
+ 4. **!!! Pure router on routed turns** - produce no artifacts. Output is delegation context, not the product. Direct turns produce their own output.
48
+ 5. **!!! Maker/checker split** - writer must not QA. In focused and full routes, every `@builder` code change is followed by `@reviewer`; the reviewer is never the agent that implemented. Where the host cannot enforce separate sessions (e.g. Kimi, Pi, OMP, Hermes), the split is advisory - state the limitation, do not claim enforcement.
47
49
  6. **!!! Ship docs with code** - docs audit (Commit Protocol step 2) before every commit. Non-negotiable.
48
50
  7. **!!! Don't anthropomorphize effort** - delegate at machine scale. Choose by trade-off, not perceived effort.
49
51
  8. **!!! Set iteration limits** - define max rounds and termination condition. Prevents agent ping-pong.
50
- 9. **!!! Default to most specialized specialist** - most tasks need `@adventurer`, `@architect`, `@planner`, `@diagnose`, `@reviewer`, or `@writer` before code. Builder bias is the most common failure mode.
52
+ 9. **!!! Default to the most specialized specialist in routed turns** - when a focused or full route selects a specialist, pick the one that owns the concern. Builder bias is the most common failure mode in routed work. Direct turns need no specialist.
51
53
  10. **!!! Check your branch** - on an unrecognized branch, ask first. Worktrees isolated - proceed directly.
52
54
  11. **!!! Use Work Results format after every builder task** - full table from Work Results section. Overrides "write for humans".
53
55
  12. **!!! Prefer deterministic agents over exploration** - define checkpoints, success criteria, and termination conditions. A defined output contract is more predictable. For high-uncertainty, use experiment framing (see Complexity Classification).
@@ -58,7 +60,7 @@ The rules above optimize for the common case. Override when:
58
60
 
59
61
  1. **User explicitly asks to skip a step** - "just implement it", "skip review". Flag the risk, ask for explicit confirmation ("Are you sure you want to proceed without review?"), then comply. Confirmation persists for the same skip-request type within the session.
60
62
  2. **Safety over speed** - security, data loss, irreversible production changes. Default: pause and ask first.
61
- 3. **Mode keyword active** - workflow mode overrides the pipeline for this turn (see Workflow Mode Override below).
63
+ 3. **Mode keyword active** - an explicit user mode overrides the route for this turn, subject to safety constraints (see Workflow Mode Override below).
62
64
  4. **User frustration detected** - two consecutive rejections means stop the current approach and escalate. Don't iterate harder (see Session Flow rule #4).
63
65
  5. **Rules conflict with each other** - tiebreak: safety > user intent > methodology purity > brevity.
64
66
  6. **Explaining vs. doing** - when the user asks "explain X" or "why Y", explanation-first is correct. Don't force action-first framing.
@@ -67,7 +69,38 @@ Even when overriding, still document the override and why. Transparency > strict
67
69
 
68
70
  ## Routing
69
71
 
70
- Route tasks to the most specialized agent. Avoid builder bias - touch code only after recon, design, planning, diagnosis, or review are complete.
72
+ ### Selective Routing
73
+
74
+ Pick a route per turn. The full pipeline is an explicit option for complex or high-risk work and for explicit `fein` requests - it is not the universal default. If model economics are unknown, prefer `direct` or `focused`; do not default to full fan-out.
75
+
76
+ | Route | What happens | Default for |
77
+ | --- | --- | --- |
78
+ | `direct` | The host executes the turn. No Maestria specialist spawn. If the host cannot safely execute, use the platform's native build/direct capability or switch to focused/full. | Explanation, discovery, tiny edits, familiar low-risk changes |
79
+ | `focused` | One targeted specialist. One `@reviewer` for non-trivial work. | Ordinary code changes, discovery in unfamiliar code |
80
+ | `full` | Bounded recon, design, implementation, and review. Independent review where the host supports it. | Complex or high-risk work; explicit `fein` |
81
+
82
+ **Route by task class:**
83
+
84
+ | Task class | Default route | Escalate to |
85
+ | --- | --- | --- |
86
+ | Explanation or discovery | `direct` for explanation. One targeted specialist (`@adventurer`, `@diagnose`, `@architect`) only when codebase exploration is genuinely needed. | `focused`. Never `full` by default. |
87
+ | Tiny edit | `direct` or native builder. No automatic recon or review. | Security, migrations, permissions, production impact, or ambiguity. |
88
+ | Ordinary code change | `focused`: one specialist; one reviewer for non-trivial work. | `full` when the change spans packages, has unclear requirements, or carries real risk. |
89
+ | Complex or high-risk | `full` with independent review where the host supports it. | A second review or more planning only when new risk appears. |
90
+
91
+ **Scaling guardrails** (bounds, not measured savings):
92
+
93
+ | Lever | `direct` | `focused` | `full` on cheap/fast models | `full` on expensive/slow models |
94
+ | --- | --- | --- | --- | --- |
95
+ | Child spawns | 0 | 1-2 | up to existing caps | one sequential path |
96
+ | Review | none | 1 pass on non-trivial work | existing max 3 cycles | 1 pass, then fail loud |
97
+ | Architect/planner | not used | only when design is the task | as the task demands | folded into one delegation |
98
+ | Parallel fan-out | 0 | 1-2 | 3-5 | 0-1 |
99
+ | Context compaction | none | as the session grows | as the session grows | aggressive; briefings over history |
100
+
101
+ ### Specialist Table
102
+
103
+ Route the concern to the specialist that owns it. Avoid builder bias - touch code only after recon, design, planning, diagnosis, or review are complete.
71
104
 
72
105
  | Agent | Role | Delegate when you see |
73
106
  | --- | --- | --- |
@@ -83,11 +116,11 @@ Delegate to `@builder` ONLY when the task is concrete, atomic, free of design am
83
116
 
84
117
  ### Complexity Classification
85
118
 
86
- | Classification | Pipeline | User questions |
119
+ | Classification | Default route | User questions |
87
120
  | --- | --- | --- |
88
- | **SIMPLE** | adventurer (recon) -> builder (implement) -> reviewer (verify) | No questions - proceed on existing patterns |
89
- | **COMPLEX** | adventurer (recon) -> architect (design with assumptions documented) -> builder (implement) -> reviewer (verify) | No questions - architect exhausts data and documents assumptions. Ask user only for irreversible decisions |
90
- | **EXPERIMENT** | adventurer (recon) -> builder (prototype) -> reviewer (evaluate findings) | Explicit hypothesis and termination condition set upfront. Output is a validated (or invalidated) claim, not shipped code |
121
+ | **SIMPLE** | `direct` or `focused` - known files, obvious change, no automatic recon or review | No questions - proceed on existing patterns |
122
+ | **COMPLEX** | `focused` or `full` - unfamiliar or cross-cutting work | No questions - architect exhausts data and documents assumptions. Ask user only for irreversible decisions |
123
+ | **EXPERIMENT** | `focused` with explicit hypothesis and termination condition set upfront | Output is a validated (or invalidated) claim, not shipped code |
91
124
 
92
125
  ## Role-Based Pipeline
93
126
 
@@ -99,11 +132,13 @@ For multi-step tasks, route work through three cognitive roles:
99
132
 
100
133
  **Dynamic Sequencing:** Order is not fixed. Default: Thinker -> Worker -> Verifier. Deviate when the task demands. Route verifier failures back to Worker (impl flaws) or Thinker (design flaws). For high-risk, consider Thinker -> Verifier -> Worker - validate design before implementation.
101
134
 
135
+ The role pipeline is the shape of `full` routes and multi-specialist `focused` routes. `direct` routes do not run it.
136
+
102
137
  ## Review Protocol
103
138
 
104
139
  ### Automatic Review Loop
105
140
 
106
- After every `@builder` task, run the review loop automatically:
141
+ In `focused` and `full` routes, after every `@builder` task, run the review loop automatically. Direct routes run no automatic review loop.
107
142
 
108
143
  1. **Build** - run validation (checks, tests) via `@builder`.
109
144
  2. **Review** - dispatch `@reviewer` for quality review.
@@ -125,13 +160,15 @@ After max 3 cycles with only `[dismiss]` and `[escalate]` items remaining, the p
125
160
 
126
161
  ### Multi-Lens Review Swarm
127
162
 
128
- For non-trivial changes, fan out parallel `@reviewer` passes:
163
+ In the `full` route, for non-trivial changes, fan out parallel `@reviewer` passes:
129
164
 
130
165
  - **When to use:** multi-concern, security-sensitive, performance-critical, or large diffs.
131
166
  - **Dispatch:** 3-5 parallel lenses: security, architecture, performance, UX, general.
132
167
  - **Lens exclusivity:** one reviewer per lens per change.
133
168
  - **Model diversity:** assign different models/sizes when supported.
134
169
 
170
+ On expensive/slow models, prefer one review pass per the scaling guardrails instead of a swarm.
171
+
135
172
  ### Review Triage
136
173
 
137
174
  After all lens reviews return:
@@ -161,6 +198,8 @@ Every delegation must be a complete briefing:
161
198
 
162
199
  **Always end with:** "If anything is unclear, exhaust available data, document your assumption, and proceed."
163
200
 
201
+ Handoffs make no platform assumptions. Context inheritance, dispatch behavior, and maker/checker enforcement differ across platforms; platform capabilities determine what is guaranteed versus advisory. Do not claim clean context or identical dispatch where the platform does not provide it.
202
+
164
203
  ### Blind Review for Verifiers
165
204
 
166
205
  When delegating to `@reviewer`, the reviewer reviews against the acceptance criteria (completions promise) and the diff -- not against the builder's explanation of what was done. The reviewer must be able to answer: "does the code satisfy the requirements?" without having read the builder's claim that it does. If the reviewer cannot determine this from the requirements + diff alone, the requirements are insufficient -- that is a finding, not an excuse to read the builder's narrative.
@@ -189,7 +228,7 @@ Specify **what** to achieve, not **how**. Activity specs constrain judgment and
189
228
 
190
229
  ### Parallel Fan-Out
191
230
 
192
- Delegate independent tasks in parallel. Max 3-5 per turn.
231
+ Delegate independent tasks in parallel, scaled to the route: `focused` 1-2, `full` up to 3-5 on cheap/fast models and 0-1 on expensive/slow models. These are guardrails, not measured savings.
193
232
 
194
233
  - **Pure recon/design:** recon + architect same turn.
195
234
  - **Mixed:** recon + implement + validate one turn.
@@ -201,14 +240,14 @@ Delegate independent tasks in parallel. Max 3-5 per turn.
201
240
 
202
241
  Commit incrementally - group by logical context, not file count. When implementation is done and tests pass, execute autonomously:
203
242
 
204
- 1. **Inspect** - `@adventurer`: check git status and recent commits.
243
+ 1. **Inspect** - routed work: `@adventurer` checks git status and recent commits. Direct turns inspect on the host - no specialist spawn.
205
244
  - **Learn from corrections:** scan commit log for patterns in the user's past corrections (type changes, scope fixes, push rejections). Apply without asking.
206
245
  2. **!!! Docs Audit** - audit all documentation categories:
207
246
  - **!!! Changeset** - Any `packages/` change or behavior-affecting change MUST have a corresponding changeset. Check existing entries; create if none. Non-negotiable.
208
247
  - **Internal docs** (docs/, ADRs, references).
209
248
  - **User-facing docs site** and **changelog** (release notes, not auto-generated files).
210
249
  3. **Compose Commit Message** - Conventional Commits. Default: `refactor`. Use `fix`/`feat` for user-facing only, `chore`/`docs`/`ci`/`test` otherwise. If no new user-facing capability, it's `refactor`, not `feat`. Base on actual diff.
211
- 4. **Execute** - `@builder`: exact message, files to stage, run validation before committing.
250
+ 4. **Execute** - routed work: `@builder` stages the intended files and runs validation before committing. Direct turns commit on the host with the same gate: exact message, stage only intended files, run required checks, and preserve user authorization.
212
251
  5. **Stop & Report** - Work Results table. Don't chain commits. If review already complete (per Review Protocol), skip `@reviewer` dispatch - proceed to push.
213
252
  6. **Push** - Check branch first: `git branch --show-current`. Never push to main/master - checkout a feature branch. Push automatically on non-main branches when a meaningful batch is ready.
214
253
  7. **PR** - Auto-create on first push to a feature branch. Detect platform from remote. Don't ask.
@@ -231,13 +270,21 @@ PR descriptions, changelogs, commits: describe what changed and why. Omit resear
231
270
 
232
271
  ## Workflow Mode Override
233
272
 
234
- Modes override the default delegation pipeline for one turn. A mode keyword in your message activates the corresponding workflow for that turn only. Detection is case-insensitive.
273
+ Modes override the default route for one turn. A mode keyword in your message activates the corresponding workflow for that turn only. Detection is case-insensitive.
235
274
 
236
- | Mode | Pipeline | When to use |
275
+ | Mode | Route | When to use |
237
276
  | --- | --- | --- |
238
- | `fein` | Thinker -> Worker -> Verifier (dynamic role pipeline) | Production-grade, non-trivial changes |
239
- | `sonar` | `@adventurer` -> `@architect`/`@planner` -> STOP | Discovery, research, feasibility |
240
- | `blitz` | `@builder` directly - skip recon/design/review unless codebase is genuinely unknown | Quick fixes, prototypes, known territory |
277
+ | `fein` | `full` - Thinker -> Worker -> Verifier (dynamic role pipeline) | Explicit request for the full production pipeline: complex, high-risk, or production-grade work |
278
+ | `sonar` | Research only - `@adventurer` -> `@architect`/`@planner` -> STOP | Discovery, research, feasibility. Does not implement |
279
+ | `blitz` | `direct` bypass for low-risk work | Quick fixes, prototypes, known territory |
280
+
281
+ Mode semantics:
282
+
283
+ - **`fein` explicitly requests the full production pipeline.** It selects the `full` route.
284
+ - **`sonar` is research-only.** It does not implement, write code, or create production files.
285
+ - **`blitz` is an explicit low-risk/direct bypass**, not a universal excuse to skip safety floors. Security, migrations, permissions, production impact, and ambiguity still require care; irreversible changes still need user checkpoints.
286
+ - **If the user explicitly chooses a mode, honor it subject to safety constraints.** Safety beats mode on the tiebreak.
287
+ - **Do not claim all platforms enforce modes identically or provide clean isolated contexts.** Platform capabilities determine what is guaranteed versus advisory.
241
288
 
242
289
  **Precedence:** Mode markers override any conflicting intent inferred from trigger phrases. If no mode is present, normal trigger-phrase matching applies. Mode is per-turn - each message independently activates its own mode. If a mode keyword is disabled by platform configuration, it passes through as plain text.
243
290
 
@@ -249,7 +296,7 @@ Projects can define custom workflow instructions in `.maestria/workflow.md` (rel
249
296
 
250
297
  **Usage:** Include relevant workflow context in the access list and context sections of each delegation prompt. When `.maestria/rules.md` is present, include its contents in the Known Problems section to ensure subagents follow project-specific constraints.
251
298
 
252
- **Precedence:** Core rules (delegate don't implement, maker/checker split, commit protocol, etc.) always take precedence over project instructions. If a conflict arises, the core rule wins.
299
+ **Precedence:** Core rules (never implement routed work yourself, maker/checker split, commit protocol, etc.) always take precedence over project instructions. If a conflict arises, the core rule wins.
253
300
 
254
301
  ## Work Results
255
302
 
@@ -286,7 +333,11 @@ After each task:
286
333
 
287
334
  ## Skills for Subagents
288
335
 
289
- Subagents start with zero skills - the delegation prompt is the only conduit for skill loading. **Always load:** `humanizer` - the orchestrator writes user-facing text. Load on every invocation.
336
+ Skill loading is trigger-based, scoped to the selected route and task class.
337
+
338
+ **Your own loads:** `humanizer` always - you write user-facing text. Do not load architecture, planning, review, or documentation skills for a `direct` turn that does not use those roles.
339
+
340
+ **Routed turns:** subagents start with zero skills - the delegation prompt is the only conduit for skill loading. Include the skill names matching the specialist's role in the delegation prompt; the specialist loads its prescription.
290
341
 
291
342
  **Proactive path (before every delegation):**
292
343
 
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import{readFileSync as e,readdirSync as t}from"fs";import{basename as n,join as r}from"path";import{parse as i}from"yaml";import{z as a}from"zod";import{escapeRegExp as o}from"es-toolkit";import{readFileSync as s}from"node:fs";import{dirname as c,join as l,resolve as u}from"node:path";import{fileURLToPath as d}from"node:url";const f=a.enum([`fein`,`sonar`,`blitz`]),p=a.object({modes:a.object({disabledKeywords:a.array(f).optional()}).optional()}),m=u(c(d(import.meta.url)),`..`),h=l(m,`agents`),g=l(m,`agents`,`commands`),_=l(m,`rules`,`AGENTS.md`),v=[`fein`,`sonar`,`blitz`];function y(e){let t=s(u(g,`${e}.md`),`utf-8`),n=t.indexOf(`## MODE:`);return n===-1?t.replace(/\s+$/,``)+`
1
+ import{escapeRegExp as e,merge as t}from"es-toolkit";import{readFileSync as n,readdirSync as r}from"fs";import{basename as i,join as a}from"path";import{parse as o}from"yaml";import{z as s}from"zod";import{readFileSync as c}from"node:fs";import{dirname as l,join as u,resolve as d}from"node:path";import{fileURLToPath as f}from"node:url";const p=s.enum([`fein`,`sonar`,`blitz`]),m=s.object({modes:s.object({disabledKeywords:s.array(p).optional()}).optional()}),h=d(l(f(import.meta.url)),`..`),g=u(h,`agents`),_=u(h,`agents`,`commands`),v=u(h,`rules`,`AGENTS.md`),y=[`fein`,`sonar`,`blitz`];function b(e){let t=c(d(_,`${e}.md`),`utf-8`),n=t.indexOf(`## MODE:`);return n===-1?t.replace(/\s+$/,``)+`
2
2
  `:t.slice(n).replace(/\s+$/,``)+`
3
- `}const b=new Proxy({},{get(e,t,n){if(typeof t==`string`&&v.includes(t)){if(!(t in e))try{e[t]=y(t)}catch(n){console.warn(`[maestria] Failed to load mode prompt "${t}":`,n),e[t]=``}return e[t]}return Reflect.get(e,t,n)}}),x={fein:`[MODE: fein]`,sonar:`[MODE: sonar]`,blitz:`[MODE: blitz]`},S={fein:3,sonar:2,blitz:1},C=/```[\s\S]*?```|`[^`]*`/g;function w(e){let t=[],n;for(;(n=C.exec(e))!==null;)t.push([n.index,n.index+n[0].length]);return t}function T(e,t){return t.some(([t,n])=>e>=t&&e<n)}function E(e){return RegExp(`\\b${o(e)}\\b`,`gi`)}function D(e,t){let n=w(e),r=t?new Set(Array.from(t).map(e=>e.toLowerCase())):void 0,i=null;for(let t of v){if(r?.has(t))continue;let a=E(t),o;for(;(o=a.exec(e))!==null;)T(o.index,n)||(i===null||S[t]>S[i.mode])&&(i={keyword:o[0],index:o.index,mode:t})}return i===null?null:{mode:i.mode,keyword:i.keyword,index:i.index,prompt:b[i.mode],marker:x[i.mode]}}function O(e,t){return(e.slice(0,t.index)+e.slice(t.index+t.keyword.length).replace(/^:\s*/,``)).replace(/ {2,}/g,` `).trim()}function k(e){return j(e)?b[e]:``}function A(e){return j(e)?x[e]:``}function j(e){return v.includes(e)}function M(e){let t=i(e);return{description:t.description||``,mode:t.mode||`subagent`,permission:t.permission||{},color:t.color,maxSteps:t.maxSteps?Number(t.maxSteps):void 0}}function N(t){let r=e(t,`utf-8`),i=n(t,`.md`),a=r.split(`---`);if(a.length<3)throw Error(`Invalid agent file: ${t} - missing frontmatter`);let o=M(a[1].trim()),s=a.slice(2).join(`---`).trim(),c={description:o.description,mode:o.mode,prompt:s,permission:o.permission};return o.color&&(c.color=o.color),o.maxSteps&&(c.maxSteps=o.maxSteps),{name:i,config:c}}function P(){try{let e=t(h).filter(e=>e.endsWith(`.md`)),n={};for(let t of e)try{let{name:e,config:i}=N(r(h,t));n[e]=i}catch(e){console.warn(`[maestria] Failed to parse agent file "${t}":`,e)}return n}catch(e){throw console.error(`[maestria] Failed to read agents directory:`,e),Error(`[maestria] Failed to load agents from "${h}": `+(e instanceof Error?e.message:String(e)))}}const F=async(e,t)=>{let n=p.parse(t??{}),r=new Set((n.modes?.disabledKeywords??[]).map(e=>e.toLowerCase())),i=P();return{config:async e=>{e.agent={...e.agent,...i},e.instructions=[...e.instructions??[],_]},"experimental.session.compacting":async(e,t)=>{t.context.push(`Session was compacted. Task tracking is maintained via todowrite. Active context (files, decisions, blockers) was captured before compaction. Continue where you left off.`)},"chat.message":async(e,t)=>{if(e.agent!==`orchestrator`)return;let n=t.parts.find(e=>e.type===`text`);if(!n)return;let i=D(n.text,r);i&&(n.text=[A(i.mode),``,k(i.mode),``,O(n.text,i)].join(`
4
- `))}}};export{F as MaestriaPlugin,F as default};
3
+ `}const x=new Proxy({},{get(e,t,n){if(typeof t==`string`&&y.includes(t)){if(!(t in e))try{e[t]=b(t)}catch(n){console.warn(`[maestria] Failed to load mode prompt "${t}":`,n),e[t]=``}return e[t]}return Reflect.get(e,t,n)}}),S={fein:`[MODE: fein]`,sonar:`[MODE: sonar]`,blitz:`[MODE: blitz]`},C={fein:3,sonar:2,blitz:1},w=/```[\s\S]*?```|`[^`]*`/g;function T(e){let t=[],n;for(;(n=w.exec(e))!==null;)t.push([n.index,n.index+n[0].length]);return t}function E(e,t){return t.some(([t,n])=>e>=t&&e<n)}function D(t){return RegExp(`\\b${e(t)}\\b`,`gi`)}function O(e,t){let n=T(e),r=t?new Set(Array.from(t).map(e=>e.toLowerCase())):void 0,i=null;for(let t of y){if(r?.has(t))continue;let a=D(t),o;for(;(o=a.exec(e))!==null;)E(o.index,n)||(i===null||C[t]>C[i.mode])&&(i={keyword:o[0],index:o.index,mode:t})}return i===null?null:{mode:i.mode,keyword:i.keyword,index:i.index,prompt:x[i.mode],marker:S[i.mode]}}function k(e,t){return(e.slice(0,t.index)+e.slice(t.index+t.keyword.length).replace(/^:\s*/,``)).replace(/ {2,}/g,` `).trim()}function A(e){return M(e)?x[e]:``}function j(e){return M(e)?S[e]:``}function M(e){return y.includes(e)}function N(e){let t=o(e);return{description:t.description||``,mode:t.mode||`subagent`,permission:t.permission||{},color:t.color,maxSteps:t.maxSteps?Number(t.maxSteps):void 0}}function P(e){let t=n(e,`utf-8`),r=i(e,`.md`),a=t.split(`---`);if(a.length<3)throw Error(`Invalid agent file: ${e} - missing frontmatter`);let o=N(a[1].trim()),s=a.slice(2).join(`---`).trim(),c={description:o.description,mode:o.mode,prompt:s,permission:o.permission};return o.color&&(c.color=o.color),o.maxSteps&&(c.maxSteps=o.maxSteps),{name:r,config:c}}function F(){try{let e=r(g).filter(e=>e.endsWith(`.md`)),t={};for(let n of e)try{let{name:e,config:r}=P(a(g,n));t[e]=r}catch(e){console.warn(`[maestria] Failed to parse agent file "${n}":`,e)}return t}catch(e){throw console.error(`[maestria] Failed to read agents directory:`,e),Error(`[maestria] Failed to load agents from "${g}": `+(e instanceof Error?e.message:String(e)))}}const I=async(e,n)=>{let r=m.parse(n??{}),i=new Set((r.modes?.disabledKeywords??[]).map(e=>e.toLowerCase())),a=F();return{config:async e=>{e.agent=t(e.agent??{},a),e.instructions=[...e.instructions??[],v]},"experimental.session.compacting":async(e,t)=>{t.context.push(`Session was compacted. Task tracking is maintained via todowrite. Active context (files, decisions, blockers) was captured before compaction. Continue where you left off.`)},"chat.message":async(e,t)=>{if(e.agent!==`orchestrator`)return;let n=t.parts.find(e=>e.type===`text`);if(!n)return;let r=O(n.text,i);r&&(n.text=[j(r.mode),``,A(r.mode),``,k(n.text,r)].join(`
4
+ `))}}};export{I as MaestriaPlugin,I as default};
5
5
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["join","readFileSync","parseYaml"],"sources":["../src/modes/types.ts","../src/root.ts","../src/modes/prompts.ts","../src/modes/index.ts","../src/index.ts"],"sourcesContent":["/**\n * Types for keyword-triggered workflow modes.\n *\n * @see ADR-OC-003 for full design context.\n */\n\nimport { z } from 'zod';\n\n/**\n * Valid mode keywords.\n *\n * - `\"fein\"` -- Full pipeline (recon -> design -> build -> review)\n * - `\"sonar\"` -- Research only (recon + design, stop before build)\n * - `\"blitz\"` -- Fast implementation (builder direct, skip recon/design/review)\n */\nexport const modeKeywordSchema = z.enum(['fein', 'sonar', 'blitz']);\nexport type ModeKeyword = z.infer<typeof modeKeywordSchema>;\n\n/**\n * Plugin-level options for @maestria/opencode.\n */\nexport const maestriaOptionsSchema = z.object({\n modes: z\n .object({\n disabledKeywords: z.array(modeKeywordSchema).optional(),\n })\n .optional(),\n});\nexport type MaestriaPluginOptions = z.infer<typeof maestriaOptionsSchema>;\n\n/**\n * Result returned when a mode keyword is detected in a message.\n */\nexport interface ModeResult {\n /** The resolved mode keyword (lowercase). */\n mode: ModeKeyword;\n /** The keyword string as matched in the original text. */\n keyword: string;\n /** The character index where the keyword starts in the original text. */\n index: number;\n /** The mode prompt text to inject. */\n prompt: string;\n /** The mode marker string like `[MODE: fein]`. */\n marker: string;\n}\n","import { fileURLToPath } from 'node:url';\nimport { dirname, resolve, join } from 'node:path';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nexport const PACKAGE_ROOT = resolve(__dirname, '..');\nexport const AGENTS_DIR = join(PACKAGE_ROOT, 'agents');\nexport const COMMANDS_DIR = join(PACKAGE_ROOT, 'agents', 'commands');\nexport const RULES_PATH = join(PACKAGE_ROOT, 'rules', 'AGENTS.md');\n","import { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { COMMANDS_DIR } from '@/root.js';\nimport type { ModeKeyword } from '@/modes/types.js';\n\nconst VALID_KEYWORDS: readonly ModeKeyword[] = ['fein', 'sonar', 'blitz'];\n\nfunction loadModePrompt(name: string): string {\n const content = readFileSync(resolve(COMMANDS_DIR, `${name}.md`), 'utf-8');\n // Find the `## MODE:` heading which marks the start of the actual prompt text.\n // The synced command files start with an HTML comment (`<!-- Auto-generated... -->`),\n // not YAML frontmatter (`---`), so a frontmatter regex would never match.\n const modeIdx = content.indexOf('## MODE:');\n if (modeIdx !== -1) {\n return content.slice(modeIdx).replace(/\\s+$/, '') + '\\n';\n }\n return content.replace(/\\s+$/, '') + '\\n';\n}\n\n/**\n * Mode prompt text for each keyword, lazily loaded on first access.\n * If a prompt file is missing or unreadable, logs a warning and caches\n * an empty string — never throws at module evaluation time.\n *\n * @see ADR-OC-003 (section \"Mode Prompts\")\n */\nexport const MODE_PROMPTS: Record<ModeKeyword, string> = new Proxy(\n {} as Record<ModeKeyword, string>,\n {\n get(target, key, receiver) {\n if (typeof key === 'string' && (VALID_KEYWORDS as readonly string[]).includes(key)) {\n if (!(key in target)) {\n try {\n (target as Record<string, string>)[key] = loadModePrompt(key);\n } catch (e) {\n console.warn(`[maestria] Failed to load mode prompt \"${key}\":`, e);\n (target as Record<string, string>)[key] = '';\n }\n }\n return (target as Record<string, string>)[key as string];\n }\n return Reflect.get(target, key, receiver);\n },\n },\n);\n\n/**\n * Marker strings for each mode keyword, used to signal the active mode.\n * Format: `[MODE: <keyword>]`\n */\nexport const MODE_MARKERS: Record<ModeKeyword, string> = {\n fein: '[MODE: fein]',\n sonar: '[MODE: sonar]',\n blitz: '[MODE: blitz]',\n};\n\n/**\n * Array of all valid mode keywords for runtime iteration.\n */\nexport { VALID_KEYWORDS };\n","import { escapeRegExp } from 'es-toolkit';\nimport { MODE_PROMPTS, MODE_MARKERS, VALID_KEYWORDS } from '@/modes/prompts.js';\nimport type { ModeKeyword, ModeResult } from '@/modes/types.js';\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 all gates\n */\nconst MODE_PRIORITY: Record<ModeKeyword, number> = {\n fein: 3,\n sonar: 2,\n blitz: 1,\n};\n\n/**\n * Regex matching fenced code blocks (```) and inline backtick spans (`).\n * Used to exclude keyword matches inside code spans.\n */\n// Note: Unclosed fenced code blocks (``` without closing ```) are not\n// excluded - the regex requires matching fences. This is an accepted\n// false-positive risk (see ADR-OC-003 consequences).\nconst CODE_BLOCK_RE = /```[\\s\\S]*?```|`[^`]*`/g;\n\n/**\n * Find ranges of code blocks and inline code spans in text.\n * Returns [start, end) positions. Keywords inside these ranges\n * are ignored during detection.\n */\nfunction findAllCodeBlockRanges(text: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n let match: RegExpExecArray | null;\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\nfunction isInRanges(index: number, ranges: Array<[number, number]>): boolean {\n return ranges.some(([start, end]) => index >= start && index < end);\n}\n\n/**\n * Build a regex pattern for word-boundary matching of the given keyword.\n *\n * The pattern uses `\\b` word boundaries to ensure we match whole words only,\n * and is case-insensitive so `Fein`, `FEIN`, `fein` all match.\n */\nfunction buildKeywordRegex(keyword: string): RegExp {\n return new RegExp(`\\\\b${escapeRegExp(keyword)}\\\\b`, 'gi');\n}\n\n/**\n * Detect a workflow mode keyword in the given text.\n *\n * Detection rules (per ADR-OC-003):\n * - Word-boundary regex matching (`\\bfein\\b`, `\\bsonar\\b`, `\\bblitz\\b`)\n * - Most restrictive match wins (fein > sonar > blitz)\n * - Case-insensitive\n * - Disabled keywords are ignored\n * - Matches inside fenced code blocks (```) and inline backticks (`) are ignored\n *\n * @param text The user message to scan.\n * @param disabled Optional set of disabled mode keywords (lowercase).\n * @returns A `ModeResult` if a keyword was detected, or `null`.\n */\nexport function detectMode(text: string, disabled?: Set<string>): ModeResult | null {\n const codeRanges = findAllCodeBlockRanges(text);\n // Normalize disabled keywords to lowercase for case-insensitive comparison\n const normalizedDisabled = disabled\n ? new Set(Array.from(disabled).map((k) => k.toLowerCase()))\n : undefined;\n let bestMatch: { keyword: string; index: number; mode: ModeKeyword } | null = null;\n\n for (const keyword of VALID_KEYWORDS) {\n if (normalizedDisabled?.has(keyword)) continue;\n\n const regex = buildKeywordRegex(keyword);\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(text)) !== null) {\n if (isInRanges(match.index, codeRanges)) continue;\n // Most-restrictive wins: prefer higher-priority mode over position\n if (bestMatch === null || MODE_PRIORITY[keyword] > MODE_PRIORITY[bestMatch.mode]) {\n bestMatch = {\n keyword: match[0],\n index: match.index,\n mode: keyword,\n };\n }\n }\n }\n\n if (bestMatch === null) return null;\n\n return {\n mode: bestMatch.mode,\n keyword: bestMatch.keyword,\n index: bestMatch.index,\n prompt: MODE_PROMPTS[bestMatch.mode],\n marker: MODE_MARKERS[bestMatch.mode],\n };\n}\n\n/**\n * Remove the matched keyword from the text, cleaning up any trailing colon\n * or whitespace that may follow it.\n *\n * @param text The original message text.\n * @param result The `ModeResult` from `detectMode()`.\n * @returns The text with the keyword stripped.\n */\nexport function stripKeyword(text: string, result: ModeResult): string {\n const before = text.slice(0, result.index);\n const after = text.slice(result.index + result.keyword.length);\n\n // Remove any colon + optional whitespace after the keyword\n // (e.g. \"fein: do this\" -> \"do this\")\n const cleaned = after.replace(/^:\\s*/, '');\n\n // Collapse double spaces and trim both ends (handles keyword at start,\n // end, or middle of text, plus extra whitespace around colon)\n return (before + cleaned).replace(/ {2,}/g, ' ').trim();\n}\n\n/**\n * Get the mode prompt text for a given mode name.\n *\n * @param mode The mode keyword (e.g. \"fein\", \"sonar\", \"blitz\").\n * @returns The prompt string, or empty string if mode is unknown.\n */\nexport function getModePrompt(mode: string): string {\n if (isModeKeyword(mode)) {\n return MODE_PROMPTS[mode];\n }\n return '';\n}\n\n/**\n * Get the mode marker string for a given mode name.\n *\n * @param mode The mode keyword (e.g. \"fein\", \"sonar\", \"blitz\").\n * @returns The marker string (e.g. `[MODE: fein]`), or empty string if unknown.\n */\nexport function getModeMarker(mode: string): string {\n if (isModeKeyword(mode)) {\n return MODE_MARKERS[mode];\n }\n return '';\n}\n\n/**\n * Type guard to check if a string is a valid ModeKeyword.\n */\nfunction isModeKeyword(value: string): value is ModeKeyword {\n return (VALID_KEYWORDS as readonly string[]).includes(value);\n}\n","import type { Plugin } from '@opencode-ai/plugin';\nimport { readFileSync, readdirSync } from 'fs';\nimport { join, basename } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport { type MaestriaPluginOptions, maestriaOptionsSchema } from '@/modes/types.js';\nimport { detectMode, stripKeyword, getModeMarker, getModePrompt } from '@/modes/index.js';\nimport { AGENTS_DIR, RULES_PATH } from '@/root.js';\n\ninterface AgentFrontmatter {\n description: string;\n mode: string;\n permission: Record<string, unknown>;\n color?: string;\n maxSteps?: number;\n}\n\nfunction parseFrontmatter(yamlStr: string): AgentFrontmatter {\n const result = parseYaml(yamlStr) as Record<string, unknown>;\n return {\n description: (result.description as string) || '',\n mode: (result.mode as string) || 'subagent',\n permission: (result.permission as Record<string, unknown>) || {},\n color: result.color as string | undefined,\n maxSteps: result.maxSteps ? Number(result.maxSteps) : undefined,\n };\n}\n\n/**\n * Read an agent markdown file and split into frontmatter + prompt.\n */\nfunction parseAgentFile(filePath: string): { name: string; config: Record<string, unknown> } {\n const content = readFileSync(filePath, 'utf-8');\n const name = basename(filePath, '.md');\n\n // Split on ---\n const parts = content.split('---');\n if (parts.length < 3) {\n throw new Error(`Invalid agent file: ${filePath} - missing frontmatter`);\n }\n\n const frontmatter = parseFrontmatter(parts[1].trim());\n const prompt = parts.slice(2).join('---').trim();\n\n const config: Record<string, unknown> = {\n description: frontmatter.description,\n mode: frontmatter.mode,\n prompt,\n permission: frontmatter.permission,\n };\n\n if (frontmatter.color) config.color = frontmatter.color;\n if (frontmatter.maxSteps) config.maxSteps = frontmatter.maxSteps;\n\n return { name, config };\n}\n\n/**\n * Load all agent configs from the bundled agents/ directory.\n * Returns partial results if some agent files fail to load.\n */\nfunction loadAgents(): Record<string, Record<string, unknown>> {\n try {\n const files = readdirSync(AGENTS_DIR).filter((f) => f.endsWith('.md'));\n const agents: Record<string, Record<string, unknown>> = {};\n\n for (const file of files) {\n try {\n const { name, config } = parseAgentFile(join(AGENTS_DIR, file));\n agents[name] = config;\n } catch (err) {\n console.warn(`[maestria] Failed to parse agent file \"${file}\":`, err);\n }\n }\n\n return agents;\n } catch (err) {\n console.error(`[maestria] Failed to read agents directory:`, err);\n throw new Error(\n `[maestria] Failed to load agents from \"${AGENTS_DIR}\": ` +\n (err instanceof Error ? err.message : String(err)),\n );\n }\n}\n\nexport const MaestriaPlugin: Plugin = async (_input, options?: MaestriaPluginOptions) => {\n // Validate and parse options with zod\n const parsed = maestriaOptionsSchema.parse(options ?? {});\n const disabledKeywords = new Set<string>(\n (parsed.modes?.disabledKeywords ?? []).map((k) => k.toLowerCase()),\n );\n const agents = loadAgents();\n\n return {\n config: async (input) => {\n input.agent = {\n ...input.agent,\n ...agents,\n };\n input.instructions = [...(input.instructions ?? []), RULES_PATH];\n },\n 'experimental.session.compacting': async (_input, output) => {\n output.context.push(\n 'Session was compacted. Task tracking is maintained via todowrite. ' +\n 'Active context (files, decisions, blockers) was captured before compaction. ' +\n 'Continue where you left off.',\n );\n },\n 'chat.message': async (hookInput, hookOutput) => {\n // Only fire for the orchestrator agent\n if (hookInput.agent !== 'orchestrator') return;\n\n // Find the first text part with user content\n const textPart = hookOutput.parts.find((p) => p.type === 'text') as\n | { text: string; type: 'text' }\n | undefined;\n if (!textPart) return;\n\n // Detect keyword in the text\n const result = detectMode(textPart.text, disabledKeywords);\n if (!result) return;\n\n // Strip keyword from text and prepend mode marker + prompt inline.\n // We embed everything in the existing text part rather than injecting\n // a second text part into `parts`, because the OpenCode runtime does\n // not handle multiple text parts per message (causes a hang).\n textPart.text = [\n getModeMarker(result.mode),\n '',\n getModePrompt(result.mode),\n '',\n stripKeyword(textPart.text, result),\n ].join('\\n');\n },\n };\n};\n\nexport default MaestriaPlugin;\n"],"mappings":"uUAeA,MAAa,EAAoB,EAAE,KAAK,CAAC,OAAQ,QAAS,OAAO,CAAC,EAMrD,EAAwB,EAAE,OAAO,CAC5C,MAAO,EACJ,OAAO,CACN,iBAAkB,EAAE,MAAM,CAAiB,CAAC,CAAC,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EAAyB,MAAO,EAAQ,IAAoC,CAEvF,IAAM,EAAS,EAAsB,MAAM,GAAW,CAAC,CAAC,EAClD,EAAmB,IAAI,KAC1B,EAAO,OAAO,kBAAoB,CAAC,EAAA,CAAG,IAAK,GAAM,EAAE,YAAY,CAAC,CACnE,EACM,EAAS,EAAW,EAE1B,MAAO,CACL,OAAQ,KAAO,IAAU,CACvB,EAAM,MAAQ,CACZ,GAAG,EAAM,MACT,GAAG,CACL,EACA,EAAM,aAAe,CAAC,GAAI,EAAM,cAAgB,CAAC,EAAI,CAAU,CACjE,EACA,kCAAmC,MAAO,EAAQ,IAAW,CAC3D,EAAO,QAAQ,KACb,4KAGF,CACF,EACA,eAAgB,MAAO,EAAW,IAAe,CAE/C,GAAI,EAAU,QAAU,eAAgB,OAGxC,IAAM,EAAW,EAAW,MAAM,KAAM,GAAM,EAAE,OAAS,MAAM,EAG/D,GAAI,CAAC,EAAU,OAGf,IAAM,EAAS,EAAW,EAAS,KAAM,CAAgB,EACpD,IAML,EAAS,KAAO,CACd,EAAc,EAAO,IAAI,EACzB,GACA,EAAc,EAAO,IAAI,EACzB,GACA,EAAa,EAAS,KAAM,CAAM,CACpC,CAAC,CAAC,KAAK;CAAI,EACb,CACF,CACF"}
1
+ {"version":3,"file":"index.js","names":["join","readFileSync","parseYaml"],"sources":["../src/modes/types.ts","../src/root.ts","../src/modes/prompts.ts","../src/modes/index.ts","../src/index.ts"],"sourcesContent":["/**\n * Types for keyword-triggered workflow modes.\n *\n * @see ADR-OC-003 for full design context.\n */\n\nimport { z } from 'zod';\n\n/**\n * Valid mode keywords.\n *\n * - `\"fein\"` -- Full pipeline (recon -> design -> build -> review)\n * - `\"sonar\"` -- Research only (recon + design, stop before build)\n * - `\"blitz\"` -- Fast implementation (builder direct, skip recon/design/review)\n */\nexport const modeKeywordSchema = z.enum(['fein', 'sonar', 'blitz']);\nexport type ModeKeyword = z.infer<typeof modeKeywordSchema>;\n\n/**\n * Plugin-level options for @maestria/opencode.\n */\nexport const maestriaOptionsSchema = z.object({\n modes: z\n .object({\n disabledKeywords: z.array(modeKeywordSchema).optional(),\n })\n .optional(),\n});\nexport type MaestriaPluginOptions = z.infer<typeof maestriaOptionsSchema>;\n\n/**\n * Result returned when a mode keyword is detected in a message.\n */\nexport interface ModeResult {\n /** The resolved mode keyword (lowercase). */\n mode: ModeKeyword;\n /** The keyword string as matched in the original text. */\n keyword: string;\n /** The character index where the keyword starts in the original text. */\n index: number;\n /** The mode prompt text to inject. */\n prompt: string;\n /** The mode marker string like `[MODE: fein]`. */\n marker: string;\n}\n","import { fileURLToPath } from 'node:url';\nimport { dirname, resolve, join } from 'node:path';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nexport const PACKAGE_ROOT = resolve(__dirname, '..');\nexport const AGENTS_DIR = join(PACKAGE_ROOT, 'agents');\nexport const COMMANDS_DIR = join(PACKAGE_ROOT, 'agents', 'commands');\nexport const RULES_PATH = join(PACKAGE_ROOT, 'rules', 'AGENTS.md');\n","import { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { COMMANDS_DIR } from '@/root.js';\nimport type { ModeKeyword } from '@/modes/types.js';\n\nconst VALID_KEYWORDS: readonly ModeKeyword[] = ['fein', 'sonar', 'blitz'];\n\nfunction loadModePrompt(name: string): string {\n const content = readFileSync(resolve(COMMANDS_DIR, `${name}.md`), 'utf-8');\n // Find the `## MODE:` heading which marks the start of the actual prompt text.\n // The synced command files start with an HTML comment (`<!-- Auto-generated... -->`),\n // not YAML frontmatter (`---`), so a frontmatter regex would never match.\n const modeIdx = content.indexOf('## MODE:');\n if (modeIdx !== -1) {\n return content.slice(modeIdx).replace(/\\s+$/, '') + '\\n';\n }\n return content.replace(/\\s+$/, '') + '\\n';\n}\n\n/**\n * Mode prompt text for each keyword, lazily loaded on first access.\n * If a prompt file is missing or unreadable, logs a warning and caches\n * an empty string — never throws at module evaluation time.\n *\n * @see ADR-OC-003 (section \"Mode Prompts\")\n */\nexport const MODE_PROMPTS: Record<ModeKeyword, string> = new Proxy(\n {} as Record<ModeKeyword, string>,\n {\n get(target, key, receiver) {\n if (typeof key === 'string' && (VALID_KEYWORDS as readonly string[]).includes(key)) {\n if (!(key in target)) {\n try {\n (target as Record<string, string>)[key] = loadModePrompt(key);\n } catch (e) {\n console.warn(`[maestria] Failed to load mode prompt \"${key}\":`, e);\n (target as Record<string, string>)[key] = '';\n }\n }\n return (target as Record<string, string>)[key as string];\n }\n return Reflect.get(target, key, receiver);\n },\n },\n);\n\n/**\n * Marker strings for each mode keyword, used to signal the active mode.\n * Format: `[MODE: <keyword>]`\n */\nexport const MODE_MARKERS: Record<ModeKeyword, string> = {\n fein: '[MODE: fein]',\n sonar: '[MODE: sonar]',\n blitz: '[MODE: blitz]',\n};\n\n/**\n * Array of all valid mode keywords for runtime iteration.\n */\nexport { VALID_KEYWORDS };\n","import { escapeRegExp } from 'es-toolkit';\nimport { MODE_PROMPTS, MODE_MARKERS, VALID_KEYWORDS } from '@/modes/prompts.js';\nimport type { ModeKeyword, ModeResult } from '@/modes/types.js';\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 all gates\n */\nconst MODE_PRIORITY: Record<ModeKeyword, number> = {\n fein: 3,\n sonar: 2,\n blitz: 1,\n};\n\n/**\n * Regex matching fenced code blocks (```) and inline backtick spans (`).\n * Used to exclude keyword matches inside code spans.\n */\n// Note: Unclosed fenced code blocks (``` without closing ```) are not\n// excluded - the regex requires matching fences. This is an accepted\n// false-positive risk (see ADR-OC-003 consequences).\nconst CODE_BLOCK_RE = /```[\\s\\S]*?```|`[^`]*`/g;\n\n/**\n * Find ranges of code blocks and inline code spans in text.\n * Returns [start, end) positions. Keywords inside these ranges\n * are ignored during detection.\n */\nfunction findAllCodeBlockRanges(text: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n let match: RegExpExecArray | null;\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\nfunction isInRanges(index: number, ranges: Array<[number, number]>): boolean {\n return ranges.some(([start, end]) => index >= start && index < end);\n}\n\n/**\n * Build a regex pattern for word-boundary matching of the given keyword.\n *\n * The pattern uses `\\b` word boundaries to ensure we match whole words only,\n * and is case-insensitive so `Fein`, `FEIN`, `fein` all match.\n */\nfunction buildKeywordRegex(keyword: string): RegExp {\n return new RegExp(`\\\\b${escapeRegExp(keyword)}\\\\b`, 'gi');\n}\n\n/**\n * Detect a workflow mode keyword in the given text.\n *\n * Detection rules (per ADR-OC-003):\n * - Word-boundary regex matching (`\\bfein\\b`, `\\bsonar\\b`, `\\bblitz\\b`)\n * - Most restrictive match wins (fein > sonar > blitz)\n * - Case-insensitive\n * - Disabled keywords are ignored\n * - Matches inside fenced code blocks (```) and inline backticks (`) are ignored\n *\n * @param text The user message to scan.\n * @param disabled Optional set of disabled mode keywords (lowercase).\n * @returns A `ModeResult` if a keyword was detected, or `null`.\n */\nexport function detectMode(text: string, disabled?: Set<string>): ModeResult | null {\n const codeRanges = findAllCodeBlockRanges(text);\n // Normalize disabled keywords to lowercase for case-insensitive comparison\n const normalizedDisabled = disabled\n ? new Set(Array.from(disabled).map((k) => k.toLowerCase()))\n : undefined;\n let bestMatch: { keyword: string; index: number; mode: ModeKeyword } | null = null;\n\n for (const keyword of VALID_KEYWORDS) {\n if (normalizedDisabled?.has(keyword)) continue;\n\n const regex = buildKeywordRegex(keyword);\n let match: RegExpExecArray | null;\n\n while ((match = regex.exec(text)) !== null) {\n if (isInRanges(match.index, codeRanges)) continue;\n // Most-restrictive wins: prefer higher-priority mode over position\n if (bestMatch === null || MODE_PRIORITY[keyword] > MODE_PRIORITY[bestMatch.mode]) {\n bestMatch = {\n keyword: match[0],\n index: match.index,\n mode: keyword,\n };\n }\n }\n }\n\n if (bestMatch === null) return null;\n\n return {\n mode: bestMatch.mode,\n keyword: bestMatch.keyword,\n index: bestMatch.index,\n prompt: MODE_PROMPTS[bestMatch.mode],\n marker: MODE_MARKERS[bestMatch.mode],\n };\n}\n\n/**\n * Remove the matched keyword from the text, cleaning up any trailing colon\n * or whitespace that may follow it.\n *\n * @param text The original message text.\n * @param result The `ModeResult` from `detectMode()`.\n * @returns The text with the keyword stripped.\n */\nexport function stripKeyword(text: string, result: ModeResult): string {\n const before = text.slice(0, result.index);\n const after = text.slice(result.index + result.keyword.length);\n\n // Remove any colon + optional whitespace after the keyword\n // (e.g. \"fein: do this\" -> \"do this\")\n const cleaned = after.replace(/^:\\s*/, '');\n\n // Collapse double spaces and trim both ends (handles keyword at start,\n // end, or middle of text, plus extra whitespace around colon)\n return (before + cleaned).replace(/ {2,}/g, ' ').trim();\n}\n\n/**\n * Get the mode prompt text for a given mode name.\n *\n * @param mode The mode keyword (e.g. \"fein\", \"sonar\", \"blitz\").\n * @returns The prompt string, or empty string if mode is unknown.\n */\nexport function getModePrompt(mode: string): string {\n if (isModeKeyword(mode)) {\n return MODE_PROMPTS[mode];\n }\n return '';\n}\n\n/**\n * Get the mode marker string for a given mode name.\n *\n * @param mode The mode keyword (e.g. \"fein\", \"sonar\", \"blitz\").\n * @returns The marker string (e.g. `[MODE: fein]`), or empty string if unknown.\n */\nexport function getModeMarker(mode: string): string {\n if (isModeKeyword(mode)) {\n return MODE_MARKERS[mode];\n }\n return '';\n}\n\n/**\n * Type guard to check if a string is a valid ModeKeyword.\n */\nfunction isModeKeyword(value: string): value is ModeKeyword {\n return (VALID_KEYWORDS as readonly string[]).includes(value);\n}\n","import type { Plugin } from '@opencode-ai/plugin';\nimport { merge } from 'es-toolkit';\nimport { readFileSync, readdirSync } from 'fs';\nimport { join, basename } from 'path';\nimport { parse as parseYaml } from 'yaml';\nimport { type MaestriaPluginOptions, maestriaOptionsSchema } from '@/modes/types.js';\nimport { detectMode, stripKeyword, getModeMarker, getModePrompt } from '@/modes/index.js';\nimport { AGENTS_DIR, RULES_PATH } from '@/root.js';\n\ninterface AgentFrontmatter {\n description: string;\n mode: string;\n permission: Record<string, unknown>;\n color?: string;\n maxSteps?: number;\n}\n\nfunction parseFrontmatter(yamlStr: string): AgentFrontmatter {\n const result = parseYaml(yamlStr) as Record<string, unknown>;\n return {\n description: (result.description as string) || '',\n mode: (result.mode as string) || 'subagent',\n permission: (result.permission as Record<string, unknown>) || {},\n color: result.color as string | undefined,\n maxSteps: result.maxSteps ? Number(result.maxSteps) : undefined,\n };\n}\n\n/**\n * Read an agent markdown file and split into frontmatter + prompt.\n */\nfunction parseAgentFile(filePath: string): { name: string; config: Record<string, unknown> } {\n const content = readFileSync(filePath, 'utf-8');\n const name = basename(filePath, '.md');\n\n // Split on ---\n const parts = content.split('---');\n if (parts.length < 3) {\n throw new Error(`Invalid agent file: ${filePath} - missing frontmatter`);\n }\n\n const frontmatter = parseFrontmatter(parts[1].trim());\n const prompt = parts.slice(2).join('---').trim();\n\n const config: Record<string, unknown> = {\n description: frontmatter.description,\n mode: frontmatter.mode,\n prompt,\n permission: frontmatter.permission,\n };\n\n if (frontmatter.color) config.color = frontmatter.color;\n if (frontmatter.maxSteps) config.maxSteps = frontmatter.maxSteps;\n\n return { name, config };\n}\n\n/**\n * Load all agent configs from the bundled agents/ directory.\n * Returns partial results if some agent files fail to load.\n */\nfunction loadAgents(): Record<string, Record<string, unknown>> {\n try {\n const files = readdirSync(AGENTS_DIR).filter((f) => f.endsWith('.md'));\n const agents: Record<string, Record<string, unknown>> = {};\n\n for (const file of files) {\n try {\n const { name, config } = parseAgentFile(join(AGENTS_DIR, file));\n agents[name] = config;\n } catch (err) {\n console.warn(`[maestria] Failed to parse agent file \"${file}\":`, err);\n }\n }\n\n return agents;\n } catch (err) {\n console.error(`[maestria] Failed to read agents directory:`, err);\n throw new Error(\n `[maestria] Failed to load agents from \"${AGENTS_DIR}\": ` +\n (err instanceof Error ? err.message : String(err)),\n );\n }\n}\n\nexport const MaestriaPlugin: Plugin = async (_input, options?: MaestriaPluginOptions) => {\n // Validate and parse options with zod\n const parsed = maestriaOptionsSchema.parse(options ?? {});\n const disabledKeywords = new Set<string>(\n (parsed.modes?.disabledKeywords ?? []).map((k) => k.toLowerCase()),\n );\n const agents = loadAgents();\n\n return {\n config: async (input) => {\n // Deep-merge plugin agent defaults over the user's agent entries. A\n // shallow `{ ...input.agent, ...agents }` would replace each entry\n // wholesale, dropping user-set keys (model, variant, temperature) for\n // the 8 maestria agent names. Plugin defaults win on conflict; user\n // keys the plugin does not set survive.\n input.agent = merge(input.agent ?? {}, agents);\n input.instructions = [...(input.instructions ?? []), RULES_PATH];\n },\n 'experimental.session.compacting': async (_input, output) => {\n output.context.push(\n 'Session was compacted. Task tracking is maintained via todowrite. ' +\n 'Active context (files, decisions, blockers) was captured before compaction. ' +\n 'Continue where you left off.',\n );\n },\n 'chat.message': async (hookInput, hookOutput) => {\n // Only fire for the orchestrator agent\n if (hookInput.agent !== 'orchestrator') return;\n\n // Find the first text part with user content\n const textPart = hookOutput.parts.find((p) => p.type === 'text') as\n | { text: string; type: 'text' }\n | undefined;\n if (!textPart) return;\n\n // Detect keyword in the text\n const result = detectMode(textPart.text, disabledKeywords);\n if (!result) return;\n\n // Strip keyword from text and prepend mode marker + prompt inline.\n // We embed everything in the existing text part rather than injecting\n // a second text part into `parts`, because the OpenCode runtime does\n // not handle multiple text parts per message (causes a hang).\n textPart.text = [\n getModeMarker(result.mode),\n '',\n getModePrompt(result.mode),\n '',\n stripKeyword(textPart.text, result),\n ].join('\\n');\n },\n };\n};\n\nexport default MaestriaPlugin;\n"],"mappings":"kVAeA,MAAa,EAAoB,EAAE,KAAK,CAAC,OAAQ,QAAS,OAAO,CAAC,EAMrD,EAAwB,EAAE,OAAO,CAC5C,MAAO,EACJ,OAAO,CACN,iBAAkB,EAAE,MAAM,CAAiB,CAAC,CAAC,SAAS,CACxD,CAAC,CAAC,CACD,SAAS,CACd,CAAC,ECvBY,EAAe,EADV,EAAQ,EAAc,OAAO,KAAK,GA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IAAI,KAC1B,EAAO,OAAO,kBAAoB,CAAC,EAAA,CAAG,IAAK,GAAM,EAAE,YAAY,CAAC,CACnE,EACM,EAAS,EAAW,EAE1B,MAAO,CACL,OAAQ,KAAO,IAAU,CAMvB,EAAM,MAAQ,EAAM,EAAM,OAAS,CAAC,EAAG,CAAM,EAC7C,EAAM,aAAe,CAAC,GAAI,EAAM,cAAgB,CAAC,EAAI,CAAU,CACjE,EACA,kCAAmC,MAAO,EAAQ,IAAW,CAC3D,EAAO,QAAQ,KACb,4KAGF,CACF,EACA,eAAgB,MAAO,EAAW,IAAe,CAE/C,GAAI,EAAU,QAAU,eAAgB,OAGxC,IAAM,EAAW,EAAW,MAAM,KAAM,GAAM,EAAE,OAAS,MAAM,EAG/D,GAAI,CAAC,EAAU,OAGf,IAAM,EAAS,EAAW,EAAS,KAAM,CAAgB,EACpD,IAML,EAAS,KAAO,CACd,EAAc,EAAO,IAAI,EACzB,GACA,EAAc,EAAO,IAAI,EACzB,GACA,EAAa,EAAS,KAAM,CAAM,CACpC,CAAC,CAAC,KAAK;CAAI,EACb,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maestria/opencode",
3
- "version": "0.6.15",
3
+ "version": "0.6.17",
4
4
  "description": "OpenCode plugin encoding AI engineering praxis: rules, agents, and workflow discipline.",
5
5
  "keywords": [
6
6
  "agents",
package/rules/AGENTS.md CHANGED
@@ -17,7 +17,8 @@
17
17
  - **Report errors matter-of-factly** - State the problem, its cause, and the fix. No hedging ("perhaps", "might"), no drama ("uh oh", "there seems to be"), no self-deprecation. The user trusts you to diagnose, not to soften the blow.
18
18
  - **Lead with the action** - First line of every response: something the reader can act on. Not context, not preamble, not a plan announcement. Context follows the action, never precedes it. Exception: when the reader explicitly asks for explanation first.
19
19
  - **!!! Never delete what you didn't create** - If something exists and you want to change or remove it, adapt don't delete. Existing code is there for a reason, even if that reason isn't obvious. Deleting existing systems without understanding them is the #1 trust killer.
20
- - **Workflow modes** - keywords `fein` (full pipeline), `sonar` (research only), `blitz` (fast implementation) activate per-turn workflow overrides. See the orchestrator prompt for details.
20
+ - **Workflow modes** - `fein` explicitly requests the full production pipeline; `sonar` is research-only and does not implement; `blitz` is an explicit low-risk/direct bypass, not a license to skip safety floors. Honor an explicit user mode subject to safety constraints. Mode mechanics are not identical across platforms - do not claim platform guarantees that do not exist. See the orchestrator prompt for details.
21
+ - **Never claim platform guarantees that do not exist** - tool enforcement, context isolation, and maker/checker separation vary by platform. State what is guaranteed versus advisory on the platform you run.
21
22
  - **Project `.maestria/`** - `.maestria/workflow.md` and `.maestria/rules.md` in the project root define project-specific workflow sequencing and non-negotiable rules. The orchestrator loads them on start; rules are propagated to all agents via delegation prompts. See the orchestrator prompt for details.
22
23
 
23
24
  ### Tool Routing
@@ -44,11 +45,12 @@ These rules govern every specialist's output back to the orchestrator:
44
45
  - **Ambiguity -> assumptions, not questions** - exhaust available data first (codebase patterns, ADRs, `.maestria/rules.md`, environment state), then document each assumption with its supporting evidence (tagged `[inferred]` where required by your role's format) and proceed. The reviewer validates assumptions.
45
46
  - **Iteration limits** - define a verifiable termination condition for your task and stop when met. Max 3 attempts at the same failing approach before escalating.
46
47
  - **Escalation format:** "Tried X, Y, Z. Blocked by [cause]. Need [input] to proceed."
48
+ - **Handoffs assume nothing about the platform** - context inheritance, dispatch behavior, and maker/checker enforcement differ across platforms. Platform capabilities determine what is guaranteed versus advisory. Do not assume clean context or identical dispatch.
47
49
  - **Before reporting done:** verify termination condition met (cite evidence), assumptions tagged `[verified]`/`[inferred]`, escalation format used if blocked.
48
50
 
49
51
  ## Delegation
50
52
 
51
- When delegating work, use only the 7 specialists below. **Never delegate to `explore` or `general`** - they are built-in, not part of the pipeline.
53
+ Delegation is route-scoped. Direct routes execute in the current host session. If the host cannot safely perform the work, use the platform's native build/direct capability or switch to a focused or full route - do not spawn a Maestria specialist. Focused and full routes delegate only to the 7 specialists below - do not substitute `explore` or `general` for them.
52
54
 
53
55
  | Agent | Role | When to Delegate |
54
56
  | --- | --- | --- |
@@ -84,12 +86,12 @@ Parallelize independent tasks across **different scopes** only. Same scope requi
84
86
  ## Commit Policy
85
87
 
86
88
  - **Only the orchestrator authorizes commits.** Subagents must refuse commit requests and redirect to the orchestrator.
87
- - **Builders executing commits** must follow the orchestrator's exact instructions (message, files, validation commands `check`/`test`). Flag it if the orchestrator's instructions skip the commit protocol.
89
+ - **Commit execution is route-scoped.** Routed work delegates execution to `@builder`, which follows the orchestrator's exact instructions (message, files, validation commands `check`/`test`) and flags it if the instructions skip the commit protocol. Direct turns execute commits on the host with the same gate: validate, stage only intended files, run required checks, and preserve user authorization before committing.
88
90
  - **Plans must not include implicit commit steps.** Commit is a separate orchestrator step triggered autonomously when work is complete, not bundled into the plan.
89
91
 
90
92
  ## Pipeline Patterns
91
93
 
92
- The orchestrator prompt defines the canonical Role-Based Pipeline with thinker/worker/verifier roles and dynamic sequencing.
94
+ The orchestrator prompt defines the canonical Role-Based Pipeline with thinker/worker/verifier roles and dynamic sequencing, and the selective routing contract (`direct`, `focused`, `full`) that scopes when the pipeline runs. The full pipeline is an explicit option for complex or high-risk work, not the universal default.
93
95
 
94
96
  ## Branch Discipline
95
97