@maestria/pi 0.6.3 → 0.6.5
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 +3 -10
- package/agents/architect.md +1 -16
- package/agents/builder.md +2 -15
- package/agents/commands/blitz.md +1 -3
- package/agents/commands/fein.md +1 -1
- package/agents/commands/sonar.md +1 -1
- package/agents/diagnose.md +4 -11
- package/agents/planner.md +3 -14
- package/agents/reviewer.md +2 -9
- package/agents/writer.md +3 -6
- package/dist/extension.mjs +9 -9
- package/dist/extension.mjs.map +1 -1
- package/package.json +2 -2
- package/skills/global-rules/SKILL.md +48 -77
- package/skills/handoff/SKILL.md +9 -12
- package/skills/iteration-limits/SKILL.md +8 -5
- package/skills/orchestrator/SKILL.md +57 -275
package/dist/extension.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension.mjs","names":["deploySpecialistAgents","installModeAutoDetect","installModeCommands","COMMANDS_DIR","installCompactionHandlers"],"sources":["../../shared/pi/src/state-core.ts","../src/state/review.ts","../../shared/pi/src/subagent-utils.ts","../../shared/pi/src/agent-deployment.ts","../src/agents.ts","../../shared/pi/src/modes-core.ts","../src/modes.ts","../src/rules.ts","../../shared/pi/src/compaction-core.ts","../src/compaction.ts","../src/subagent.ts","../src/commands.ts","../../shared/pi/src/tools-core.ts","../src/tools.ts","../src/extension.ts"],"sourcesContent":["/**\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 function createInitialState(): MaestriaState {\n return {\n mode: null,\n activeTask: '',\n completionPromise: '',\n specialistsDelegated: [],\n blockers: [],\n filesModified: [],\n filesRead: [],\n handoffHistory: [],\n reviewMode: false,\n originalModel: null,\n originalTools: null,\n subagentStatus: {},\n reviewModel: null,\n nativeGoal: null,\n };\n}\n\nfunction 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 function recordHandoff(\n state: MaestriaState,\n from: string,\n to: string,\n task: string,\n): MaestriaState {\n const entry: HandoffEntry = { from, to, task, timestamp: Date.now() };\n const history = [entry, ...state.handoffHistory].slice(0, HANDOFF_HISTORY_CAP);\n return { ...state, handoffHistory: history };\n}\n\nexport function recordFileModified(state: MaestriaState, path: string): MaestriaState {\n return { ...state, filesModified: prependDeduped(state.filesModified, path, FILE_HISTORY_CAP) };\n}\n\nexport function recordFileRead(state: MaestriaState, path: string): MaestriaState {\n return { ...state, filesRead: prependDeduped(state.filesRead, path, FILE_HISTORY_CAP) };\n}\n\nexport function recordSubagentStatus(\n state: MaestriaState,\n id: string,\n info: SubagentStatusInfo,\n): MaestriaState {\n return { ...state, subagentStatus: { ...state.subagentStatus, [id]: info } };\n}\n\nexport function setReviewMode(state: MaestriaState, active: boolean): MaestriaState {\n return { ...state, reviewMode: active };\n}\n\nexport function exitReviewMode(state: MaestriaState): {\n state: MaestriaState;\n originalModel: string | null;\n originalTools: string[] | null;\n} {\n return {\n state: {\n ...state,\n reviewMode: false,\n originalModel: null,\n originalTools: null,\n },\n originalModel: state.originalModel,\n originalTools: state.originalTools,\n };\n}\n\n// ── Persistence ──\n\nexport function 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 function 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) {\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","import type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@maestria/shared-pi/state-core';\nimport { exitReviewMode } from '@maestria/shared-pi/state-core';\n\nexport async function restoreOriginalState(\n pi: ExtensionAPI,\n ctx: ExtensionContext,\n state: MaestriaState,\n): Promise<void> {\n const { state: clearedState, originalModel, originalTools } = exitReviewMode(state);\n\n if (originalTools && originalTools.length > 0) {\n pi.setActiveTools(originalTools);\n }\n\n if (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 async function cycleToReviewModel(\n pi: ExtensionAPI,\n ctx: ExtensionCommandContext,\n state: MaestriaState,\n): Promise<string | null> {\n const reviewModel = state.reviewModel;\n if (!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 } else {\n ctx.ui.notify(`Review model \"${reviewModel}\" not found in registry, staying on current.`);\n return null;\n }\n } catch {\n ctx.ui.notify(`Could not switch to review model \"${reviewModel}\", staying on current.`);\n return null;\n }\n}\n","/**\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_STARTED: 'maestria:subagent:started',\n SUBAGENT_COMPLETED: 'maestria:subagent:completed',\n SUBAGENT_FAILED: 'maestria:subagent:failed',\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 function assertValidAgent(agent: string): asserts agent is AllowedAgent {\n if (!ALLOWED_AGENTS.includes(agent as AllowedAgent)) {\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 function assertNonEmptyTask(\n task: string | undefined,\n label: string,\n): asserts task is string {\n if (!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 function 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}:\\\\*\\\\*([\\\\s\\\\S]*?)(?=\\\n\\\\*\\\\*|$)`;\n const match = handoff.match(new RegExp(pattern, 'i'));\n if (!match || !match[1] || !match[1].trim()) {\n errors.push(`Missing or empty field: \"${field}\"`);\n }\n }\n return { valid: errors.length === 0, errors };\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 { readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\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 function 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 = join(agentsSrc, `${name}.md`);\n const destFile = 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)) continue;\n\n try {\n const content = readFileSync(srcFile, 'utf-8');\n writeFileSync(destFile, content, 'utf-8');\n deployed++;\n } catch (err) {\n console.warn(`[maestria] Failed to deploy agent ${name}:`, err);\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 { homedir } from 'node:os';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { deploySpecialistAgents as deployAgents } from '@maestria/shared-pi/agent-deployment';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst AGENTS_SRC = 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 */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function deploySpecialistAgents(_ctx?: unknown): void {\n deployAgents(AGENTS_SRC, join(homedir(), '.pi', 'agent', 'agents'));\n}\n","/**\n * Shared mode constants and 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 * in mode prompt loading, keyword detection, and text transformation.\n *\n * @module\n */\n\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport type { MaestriaState } from './state-core.js';\n\n// ── Constants ──\n\nexport const MODE_KEYWORDS = ['fein', 'sonar', 'blitz'] as const;\nexport type ModeKeyword = (typeof MODE_KEYWORDS)[number];\n\nexport const MODE_MARKERS: Record<ModeKeyword, string> = {\n fein: '[MODE: fein]',\n sonar: '[MODE: sonar]',\n blitz: '[MODE: blitz]',\n};\n\n// ── Prompt loading ──\n\n/** Lazily cached mode prompts — shared across platforms. */\nconst _promptCache: Partial<Record<ModeKeyword, string>> = {};\n\n/**\n * Load and cache a mode prompt from a commands directory.\n * The commandsDir should point to a directory containing `fein.md`,\n * `sonar.md`, and `blitz.md` files.\n */\nexport function loadModePrompt(name: string, commandsDir: string): string {\n const content = readFileSync(resolve(commandsDir, `${name}.md`), 'utf-8');\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 * Get the full mode prompt (marker + body) for a keyword, loading from\n * the given commands directory on first access.\n */\nexport function getModePrompt(keyword: ModeKeyword, commandsDir: string): string {\n if (!(keyword in _promptCache)) {\n try {\n _promptCache[keyword] = loadModePrompt(keyword, commandsDir);\n } catch (e) {\n console.warn(`[maestria] Failed to load mode prompt \"${keyword}\":`, e);\n _promptCache[keyword] = '';\n }\n }\n return `${MODE_MARKERS[keyword]}\\n\\n${_promptCache[keyword]}`;\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/** Regex matching fenced code blocks (```) and inline backtick spans (`). */\nconst CODE_BLOCK_RE = /```[\\s\\S]*?```|`[^`]*`/g;\n\n/**\n * Find ranges of fenced code blocks and inline code spans in text.\n * Returns [start, end) positions. Keywords inside these ranges are\n * ignored during detection (per ADR-OC-003).\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 * 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 * Detect a mode keyword (fein/sonar/blitz) in text as a whole word,\n * case-insensitive. 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 * - Matches inside fenced code blocks (```) and inline backticks (`) are ignored\n */\nexport function detectModeInText(text: string, commandsDir: string): ModeDetectResult | null {\n if (!text) return null;\n\n const codeRanges = findAllCodeBlockRanges(text);\n let best: { keyword: ModeKeyword; index: number } | null = null;\n\n for (const keyword of MODE_KEYWORDS) {\n const regex = new RegExp(`\\\\b${keyword}\\\\b`, 'gi');\n let match: RegExpExecArray | null;\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 (best === null || MODE_PRIORITY[keyword] > MODE_PRIORITY[best.keyword]) {\n best = { keyword, index: match.index };\n }\n }\n }\n\n if (best === null) return null;\n\n // Strip the matched keyword, cleaning up a trailing colon and collapsing\n // double spaces (mirrors opencode's stripKeyword behavior).\n const before = text.slice(0, best.index);\n const after = text.slice(best.index + best.keyword.length).replace(/^:\\s*/, '');\n const strippedText = (before + after).replace(/ {2,}/g, ' ').trim();\n\n return {\n keyword: best.keyword,\n strippedText,\n prompt: getModePrompt(best.keyword, commandsDir),\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 function buildModeText(prompt: string, strippedText: string): string {\n return strippedText ? `${prompt}\\n\\n${strippedText}` : prompt;\n}\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 *\n * @param onInput - Platform's `pi.on('input', handler)` method\n * @param state - Shared maestria state\n * @param commandsDir - Path to directory containing fein.md/sonar.md/blitz.md\n * @param opts - Platform-specific callbacks and result builders\n */\nexport function installModeAutoDetect(\n onInput: (handler: (event: unknown, ctx: unknown) => unknown) => void,\n state: MaestriaState,\n commandsDir: string,\n opts: {\n /** Exit review mode — calls platform's restoreOriginalState */\n restoreOriginalState: (ctx: unknown) => 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: unknown;\n /** Build return value from transformed text (e.g. Pi: { action: 'transform', text }) */\n transform: (text: string) => unknown;\n },\n): void {\n onInput(async (event: unknown, ctx: unknown) => {\n const text = ((event as Record<string, unknown>).text as string) ?? '';\n const result = detectModeInText(text, commandsDir);\n if (!result) return opts.noMatch;\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 *\n * @param registerCommand - Platform's `pi.registerCommand(name, opts)` method\n * @param state - Shared maestria state\n * @param opts - Platform-specific callbacks\n */\nexport function installModeCommands(\n registerCommand: (\n name: string,\n options: { description: string; handler: (...args: unknown[]) => unknown },\n ) => void,\n state: MaestriaState,\n opts: {\n /** Exit review mode before switching modes */\n restoreOriginalState: (ctx: unknown) => Promise<void>;\n /** Persist state after mode change */\n persistState: () => void;\n },\n): void {\n for (const keyword of MODE_KEYWORDS) {\n registerCommand(keyword, {\n description: `Set workflow mode to ${keyword}`,\n handler: async (_args: unknown, ctx: unknown) => {\n if (state.reviewMode) {\n await opts.restoreOriginalState(ctx);\n }\n\n state.mode = keyword;\n opts.persistState();\n\n ((ctx as Record<string, unknown>).ui as { notify: (msg: string) => void }).notify(\n `Mode set to ${keyword}. Describe what you'd like to work on.`,\n );\n },\n });\n }\n}\n","import { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { persistState, restoreOriginalState } from '@/state.js';\nimport {\n installModeAutoDetect as installAutoDetect,\n installModeCommands as installCommands,\n} from '@maestria/shared-pi/modes-core';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst COMMANDS_DIR = resolve(__dirname, '../agents/commands');\n\nexport function installModeAutoDetect(pi: ExtensionAPI, state: MaestriaState): void {\n installAutoDetect((handler) => pi.on('input', handler as never), state, COMMANDS_DIR, {\n restoreOriginalState: (ctx) => restoreOriginalState(pi, ctx as ExtensionContext, state),\n persistState: () => persistState(pi, state),\n noMatch: { action: 'continue' as const },\n transform: (text) => ({ action: 'transform' as const, text }),\n });\n}\n\nexport function installModeCommands(pi: ExtensionAPI, state: MaestriaState): void {\n installCommands((name, opts) => pi.registerCommand(name, opts as never), state, {\n restoreOriginalState: (ctx) => restoreOriginalState(pi, ctx as ExtensionContext, state),\n persistState: () => persistState(pi, state),\n });\n}\n","import { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type {\n BeforeAgentStartEvent,\n BeforeAgentStartEventResult,\n ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { getModePrompt } from '@maestria/shared-pi/modes-core';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst COMMANDS_DIR = 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 void (no modification),\n * letting Pi's built-in prompt assembly (skills + context files + tools)\n * stand as-is.\n */\nexport function createModePromptHandler(state: MaestriaState) {\n return (\n event: BeforeAgentStartEvent,\n _ctx: ExtensionContext,\n ): BeforeAgentStartEventResult | void => {\n if (!state.mode) return;\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}\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\n/**\n * Install handlers for session compaction and tree events to persist\n * and restore maestria state across session compaction boundaries.\n *\n * Uses duck-typed `pi` parameter — both Pi and OMP ExtensionAPI types\n * satisfy the `{ on(event: string, handler): void }` shape needed here.\n */\nexport function installCompactionHandlers(\n pi: {\n on: (event: string, handler: (...args: unknown[]) => unknown) => void;\n },\n state: MaestriaState,\n): void {\n pi.on('session_before_compact', (event: unknown) => {\n const prep = (event as Record<string, unknown>).preparation as\n | Record<string, unknown>\n | undefined;\n return {\n compaction: {\n summary: renderMaestriaSummary(state),\n details: { ...state },\n firstKeptEntryId: prep?.firstKeptEntryId,\n tokensBefore: prep?.tokensBefore,\n },\n };\n });\n\n pi.on('session_before_tree', (event: unknown) => {\n const prep = (event as Record<string, unknown>).preparation as\n | Record<string, unknown>\n | undefined;\n if (prep?.userWantsSummary) {\n return {\n summary: {\n summary: renderMaestriaSummary(state),\n },\n };\n }\n return undefined;\n });\n}\n","/**\n * Pi platform compaction handlers.\n *\n * Thin wrapper around the shared implementation in\n * @maestria/shared-pi/compaction-core.\n *\n * @module\n */\n\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { installCompactionHandlers as installHandlers } from '@maestria/shared-pi/compaction-core';\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 function installCompactionHandlers(pi: ExtensionAPI, state: MaestriaState): void {\n // Bridge: ExtensionAPI.on has overloaded event types incompatible with\n // the duck-typed { on: (event: string, handler) => void } in the shared\n // module. The as-never cast is safe at runtime — both SDKs share the same\n // event shapes.\n installHandlers(\n {\n on: (event, handler) => {\n pi.on(event as never, handler as never);\n },\n },\n state,\n );\n}\n","import { Type } from 'typebox';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport { SUBAGENT_EVENTS } from '@gotgenes/pi-subagents';\nimport type { MaestriaState } from '@/state.js';\nimport { persistState, recordHandoff } from '@/state.js';\nimport {\n assertValidAgent,\n assertNonEmptyTask,\n MAESTRIA_EVENTS,\n} from '@maestria/shared-pi/subagent-utils';\n\n/** Terminal subagent statuses - agent will produce no more updates. */\nconst TERMINAL_STATUSES = new Set(['completed', 'steered', 'aborted', 'stopped', 'error']);\n\n/** Maximum time to wait for a subagent to complete, in milliseconds. */\nexport const POLL_TIMEOUT_MS = 60_000;\n\n/** Interval between subagent status checks, in milliseconds. */\nexport const POLL_INTERVAL_MS = 500;\n\n/** Maximum number of tasks allowed in parallel dispatch. */\nexport const MAX_PARALLEL_TASKS = 8;\n\n// ── Polling helper ───────────────────────────────────────────────\n\ntype SubagentRecord = { status: string; result?: string; error?: string };\n\nasync function pollSubagent(\n id: string,\n label: string,\n sendUpdates: boolean,\n service: { getRecord(id: string): SubagentRecord | undefined },\n signal: AbortSignal | undefined,\n onUpdate: ((result: { content: Array<{ type: string; text: string }> }) => void) | undefined,\n): Promise<SubagentRecord> {\n const maxPolls = POLL_TIMEOUT_MS / POLL_INTERVAL_MS;\n let polls = 0;\n let record = service.getRecord(id);\n while (record && !TERMINAL_STATUSES.has(record.status) && polls < maxPolls) {\n if (signal?.aborted) throw new Error('Maestria subagent call aborted');\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n record = service.getRecord(id);\n polls++;\n if (sendUpdates) {\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `${label} running... (${Math.round((polls * POLL_INTERVAL_MS) / 1000)}s)`,\n },\n ],\n });\n }\n }\n if (record && !TERMINAL_STATUSES.has(record.status)) {\n throw new Error(`Subagent ${id} timed out after ${POLL_TIMEOUT_MS}ms`);\n }\n if (!record) {\n throw new Error(`Subagent ${id} was cleaned up before completion`);\n }\n return record;\n}\n\n// ── Handoff recording helper ────────────────────────────────────\n\nfunction recordAndPersist(\n pi: ExtensionAPI,\n state: MaestriaState,\n agentName: string,\n taskText: string,\n): void {\n const updatedState = recordHandoff(state, 'orchestrator', agentName, taskText);\n Object.assign(state, updatedState);\n pi.appendEntry('maestria_state', state);\n}\n\nexport function installSubagentTool(\n pi: ExtensionAPI,\n state: MaestriaState,\n cleanups?: Array<() => void>,\n): void {\n pi.registerTool({\n name: 'maestria_subagent',\n label: 'Maestria Subagent',\n description: 'Dispatch a task to a @maestria specialist subagent',\n promptSnippet:\n 'Delegate tasks to @maestria specialist subagents (adventurer, architect, builder, planner, diagnose, reviewer, writer)',\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 prepareArguments(args: unknown) {\n return args;\n },\n parameters: Type.Object({\n agent: Type.Optional(Type.String({ description: 'Specialist agent name' })),\n task: Type.Optional(Type.String({ description: 'Task description for the subagent' })),\n tasks: Type.Optional(\n Type.Array(\n Type.Object({\n agent: Type.String(),\n task: Type.String(),\n }),\n { description: 'Array of task objects for parallel or chain dispatch' },\n ),\n ),\n mode: Type.Optional(\n Type.Union([Type.Literal('parallel'), Type.Literal('chain'), Type.Literal('single')]),\n ),\n }),\n async execute(\n _toolCallId: string,\n params: {\n agent?: string;\n task?: string;\n tasks?: Array<{ agent: string; task: string }>;\n mode?: 'parallel' | 'chain' | 'single';\n },\n signal: AbortSignal | undefined,\n onUpdate: ((result: { content: Array<{ type: string; text: string }> }) => void) | undefined,\n _ctx: ExtensionContext,\n ) {\n // Block subagent dispatch when in review mode\n if (state.reviewMode) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'Subagent dispatch is not available during review mode. Use /restore-model to exit review mode first.',\n },\n ],\n };\n }\n\n // Determine dispatch mode (default to 'single' for backward compat)\n const mode = params.mode ?? 'single';\n\n // Validate parameters based on mode\n if (mode === 'single') {\n assertValidAgent(params.agent!);\n assertNonEmptyTask(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 assertValidAgent(t.agent);\n assertNonEmptyTask(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 assertValidAgent(t.agent);\n assertNonEmptyTask(t.task, 'Task description is required for all tasks');\n }\n }\n\n // Attempt to dispatch via @gotgenes/pi-subagents; handle missing service\n const { getSubagentsService } = await import('@gotgenes/pi-subagents');\n const service = getSubagentsService();\n if (!service || typeof service.spawn !== 'function') {\n return {\n content: [\n {\n type: 'text' as const,\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 },\n ],\n };\n }\n\n try {\n // --- SINGLE MODE ---\n if (mode === 'single') {\n const agent = params.agent!;\n const task = params.task!;\n\n // Spawn in foreground - returns subagent ID synchronously\n const id = service.spawn(agent, task, {\n description: task.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n\n // Record handoff in state and persist (only after spawn succeeds)\n recordAndPersist(pi, state, agent, task);\n\n // Poll for completion\n const record = await pollSubagent(\n id,\n `Subagent ${agent}`,\n true,\n service,\n signal,\n onUpdate,\n );\n\n const resultText = record.result ?? record.error ?? 'No output.';\n\n return {\n content: [{ type: 'text' as const, text: resultText }],\n details: { subagentId: id },\n };\n }\n\n // --- PARALLEL MODE ---\n if (mode === 'parallel') {\n const taskList = params.tasks!;\n\n onUpdate?.({\n content: [\n { type: 'text' as const, text: `Spawning ${taskList.length} parallel subagents...` },\n ],\n });\n\n // Spawn all tasks\n const spawnedIds: string[] = [];\n for (const t of taskList) {\n const id = service.spawn(t.agent, t.task, {\n description: t.task.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n spawnedIds.push(id);\n\n // Record each handoff\n recordAndPersist(pi, state, t.agent, t.task);\n }\n\n // Poll all concurrently\n const records = await Promise.all(\n spawnedIds.map((id, i) =>\n pollSubagent(\n id,\n `${taskList[i].agent} (${i + 1}/${taskList.length})`,\n false,\n service,\n signal,\n onUpdate,\n ),\n ),\n );\n\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `All ${taskList.length} parallel subagents completed.`,\n },\n ],\n });\n\n // Aggregate results\n const parts = [`## Parallel Results (${taskList.length} tasks)\\n`];\n for (let i = 0; i < taskList.length; i++) {\n const t = taskList[i];\n const rec = records[i];\n const resultText = rec.result ?? rec.error ?? 'No output.';\n parts.push(`### ${i + 1}: ${t.agent}`);\n parts.push(resultText);\n }\n\n return {\n content: [{ type: 'text' as const, text: parts.join('\\n\\n') }],\n details: { subagentIds: spawnedIds },\n };\n }\n\n // --- CHAIN MODE ---\n if (mode === 'chain') {\n const taskList = params.tasks!;\n let previousResult = '';\n\n for (let i = 0; i < taskList.length; i++) {\n const t = taskList[i];\n let taskText = t.task;\n\n // Substitute {previous} placeholder with previous result\n if (i > 0 && taskText.includes('{previous}')) {\n taskText = taskText.replace(/\\{previous\\}/g, previousResult);\n }\n\n const id = service.spawn(t.agent, taskText, {\n description: taskText.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n\n // Record handoff\n recordAndPersist(pi, state, t.agent, taskText);\n\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `Chain step ${i + 1}/${taskList.length}: ${t.agent} running...`,\n },\n ],\n });\n\n // Poll for completion\n const record = await pollSubagent(\n id,\n `Chain step ${i + 1}: ${t.agent}`,\n true,\n service,\n signal,\n onUpdate,\n );\n\n previousResult = record.result ?? record.error ?? 'No output.';\n\n if (i < taskList.length - 1) {\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `Chain step ${i + 1}/${taskList.length}: ${t.agent} completed. Moving to next step.`,\n },\n ],\n });\n }\n }\n\n return {\n content: [{ type: 'text' as const, text: previousResult }],\n details: { subagentId: 'chain-completed' },\n };\n }\n\n // Should not reach here - all modes are handled above\n throw new Error('Unknown dispatch mode');\n } catch (err) {\n console.warn('[maestria] Subagent dispatch failed:', err);\n // Return handoff payload as structured text when dispatch fails\n const agentName = params.agent ?? params.tasks?.[0]?.agent ?? 'unknown';\n const taskDesc = params.task ?? params.tasks?.map((t) => t.task).join('; ') ?? 'unknown';\n const handoffInfo = [\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\n return {\n content: [{ type: 'text' as const, text: handoffInfo }],\n };\n }\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any); // TypeBox inferred types don't match ToolDefinition exactly\n\n // Subscribe to subagent lifecycle events for accurate state tracking.\n // These subscriptions are set up once at extension init, not on every tool call.\n // pi.events is the shared EventBus - distinct from pi.on() lifecycle hooks.\n if (pi.events) {\n const unsubStarted = pi.events.on(SUBAGENT_EVENTS.STARTED, (data: unknown) => {\n const { id, type } = data as { id: string; type: string };\n state.subagentStatus[id] = { type, status: 'running', startedAt: Date.now() };\n persistState(pi, state);\n pi.events?.emit(MAESTRIA_EVENTS.SUBAGENT_STARTED, {\n id,\n type,\n timestamp: Date.now(),\n });\n });\n\n const unsubCompleted = pi.events.on(SUBAGENT_EVENTS.COMPLETED, (data: unknown) => {\n const { id } = data as { id: string };\n const existing = state.subagentStatus[id];\n if (existing) {\n existing.status = 'completed';\n existing.completedAt = Date.now();\n }\n persistState(pi, state);\n pi.events?.emit(MAESTRIA_EVENTS.SUBAGENT_COMPLETED, {\n id,\n type: existing?.type,\n timestamp: Date.now(),\n });\n });\n\n const unsubFailed = pi.events.on(SUBAGENT_EVENTS.FAILED, (data: unknown) => {\n const { id, status } = data as { id: string; status: string };\n const existing = state.subagentStatus[id];\n if (existing) {\n existing.status = status ?? 'error';\n existing.completedAt = Date.now();\n }\n persistState(pi, state);\n pi.events?.emit(MAESTRIA_EVENTS.SUBAGENT_FAILED, {\n id,\n type: existing?.type,\n timestamp: Date.now(),\n });\n });\n\n const unsubSteered = pi.events.on(SUBAGENT_EVENTS.STEERED, (data: unknown) => {\n // Steering is informational - no status transition, but ensure\n // the agent is tracked as running if it wasn't already observed.\n const { id } = data as { id: string };\n if (!state.subagentStatus[id]) {\n state.subagentStatus[id] = { type: 'unknown', status: 'running', startedAt: Date.now() };\n }\n persistState(pi, state);\n });\n\n if (cleanups) {\n cleanups.push(unsubStarted, unsubCompleted, unsubFailed, unsubSteered);\n }\n }\n}\n","import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport {\n cycleToReviewModel,\n persistState,\n renderMaestriaSummary,\n restoreOriginalState,\n} from '@/state.js';\nimport { MAESTRIA_EVENTS } from '@maestria/shared-pi/subagent-utils';\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\nexport function installCommands(pi: ExtensionAPI, state: MaestriaState): void {\n pi.registerCommand('maestria-status', {\n description: 'Show current maestria session state including handoff history',\n handler: async (_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 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\n // 1. Save current model and tools for later restoration\n const currentModelId = ctx.model?.id ?? null;\n const currentTools = pi.getActiveTools();\n\n // 2. Update state: mark review mode, store originals\n const updatedState: MaestriaState = {\n ...state,\n reviewMode: true,\n originalModel: currentModelId,\n originalTools: currentTools,\n };\n Object.assign(state, updatedState);\n persistState(pi, state);\n\n // 3. Switch to review model if configured\n if (state.reviewModel) {\n const switched = await cycleToReviewModel(pi, ctx, state);\n if (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\n // 4. Restrict to read-only tools\n pi.setActiveTools(READ_ONLY_TOOLS);\n\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 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 pi.registerCommand('handoff', {\n description: 'Generate a structured handoff prompt for a new task context',\n handler: async (args: string, ctx) => {\n if (!args.trim()) {\n ctx.ui.notify('Usage: /handoff <goal> - describe the task context for handoff');\n return;\n }\n\n // Build a structured handoff document with 7 fields\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 '- Recent handoffs: ' + (state.handoffHistory?.length ?? 0) + ' entries',\n '- Files modified: ' +\n ((state.filesModified?.length ?? 0) > 0 ? state.filesModified.join(', ') : 'none'),\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\n // Record in state\n state.handoffHistory = [\n { from: 'current', to: 'next', task: goal, timestamp: Date.now() },\n ...(state.handoffHistory ?? []),\n ].slice(0, 5);\n\n // Persist state\n persistState(pi, state);\n\n // Send as user message with steer delivery\n pi.sendUserMessage(handoffPrompt, { deliverAs: 'steer' });\n },\n });\n\n pi.registerCommand('review-model', {\n description: 'Set which model to use when entering review mode',\n handler: async (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","/**\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\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+\\//,\n /dd\\s+if=/,\n />\\s*\\/dev\\/sd/,\n /chmod\\s+-R\\s+777\\s+\\//,\n /mkfs\\.\\w+/,\n /:(){ :\\|:& };:/,\n />\\s*\\/etc\\/(passwd|shadow|sudoers)/,\n /\\beval\\b/,\n /wget\\s+-O\\s*-\\s*\\|\\s*(bash|sh)/,\n /curl\\s+.*\\|\\s*(bash|sh)/,\n /crontab\\s+-r/,\n];\n","import {\n isToolCallEventType,\n type ExtensionAPI,\n type ToolCallEvent,\n type ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { DANGEROUS_PATTERNS } from '@maestria/shared-pi/tools-core';\n\nexport function installToolInterceptors(pi: ExtensionAPI, state: MaestriaState): void {\n pi.on('tool_call', async (event: ToolCallEvent, ctx: ExtensionContext) => {\n if (!event || !event.toolName) return;\n\n // ── Pure dispatcher enforcement ──\n // When a maestria workflow mode is active, restrict the root session\n // (orchestrator) to ONLY the maestria_subagent delegation tool.\n // Subagent sessions are detected by the absence of the pi-subagents\n // 'subagent' tool (stripped by applyRecursionGuard in child sessions).\n if (state.mode !== null && pi.getActiveTools().includes('subagent')) {\n if (event.toolName !== 'maestria_subagent') {\n return {\n block: true,\n reason:\n `Tool '${event.toolName}' is blocked for the orchestrator. ` +\n `Use 'maestria_subagent' to delegate tasks to specialists.`,\n };\n }\n }\n\n // Block destructive tools in review mode\n if (state.reviewMode) {\n if (\n isToolCallEventType('edit', event) ||\n isToolCallEventType('write', event) ||\n isToolCallEventType('bash', event)\n ) {\n return {\n block: true,\n reason: 'Review mode is active. Report findings, do not edit.',\n };\n }\n }\n\n // Block dangerous bash patterns regardless of mode\n if (isToolCallEventType('bash', event)) {\n if (!event.input || typeof event.input !== 'object') return undefined;\n const command = event.input.command;\n if (command) {\n for (const pattern of DANGEROUS_PATTERNS) {\n if (pattern.test(command)) {\n if (ctx.hasUI) {\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) return undefined;\n }\n return {\n block: true,\n reason: `Command matches dangerous pattern: ${pattern}`,\n };\n }\n }\n }\n }\n\n return undefined; // allow\n });\n}\n","import type { ExtensionAPI, SessionStartEvent } from '@earendil-works/pi-coding-agent';\nimport { createInitialState } from '@/state.js';\nimport { deploySpecialistAgents } from '@/agents.js';\nimport { installModeCommands, installModeAutoDetect } from '@/modes.js';\nimport { createModePromptHandler } from '@/rules.js';\nimport { installCompactionHandlers } from '@/compaction.js';\nimport { installSubagentTool } from '@/subagent.js';\nimport { installCommands } from '@/commands.js';\nimport { installToolInterceptors } from '@/tools.js';\n\nexport default function (pi: ExtensionAPI): void {\n const state = createInitialState();\n const cleanups: Array<() => void> = [];\n\n // Install mode commands: /fein, /sonar, /blitz\n installModeCommands(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) => {\n return handleModePrompt(event, ctx);\n });\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 if (!ctx.sessionManager?.getEntries) return;\n const entries = ctx.sessionManager.getEntries();\n // Walk from newest to oldest, find the last persisted maestria_state entry\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i];\n if (entry.type === 'custom' && entry.customType === 'maestria_state') {\n const data = entry.data;\n if (data && typeof data === 'object') {\n Object.assign(state, data);\n }\n break;\n }\n }\n });\n\n // Install compaction preservation handlers\n installCompactionHandlers(pi, state);\n\n // Install orchestration hooks: subagent tool and commands\n installSubagentTool(pi, state, cleanups);\n installCommands(pi, state);\n\n // Cleanup subscriptions on shutdown\n pi.on('session_shutdown', () => {\n for (const cleanup of cleanups) cleanup();\n cleanups.length = 0;\n });\n\n // Install tool call interceptors for review mode and dangerous patterns\n installToolInterceptors(pi, state);\n}\n"],"mappings":"6XA6DA,SAAgB,GAAoC,CAClD,MAAO,CACL,KAAM,KACN,WAAY,GACZ,kBAAmB,GACnB,qBAAsB,CAAC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I,GAAG,QAC7B,6BACA,8CAA8C,EAAQ,WACxD,EACe,OAEV,CACL,MAAO,GACP,OAAQ,sCAAsC,GAChD,CACF,CAGN,CAtCE,CAyCJ,CAAC,CACH,CC1DA,SAAA,GAAyB,EAAwB,CAC/C,IAAM,EAAQ,EAAmB,EAC3B,EAA8B,CAAC,EAGrC,EAAoB,EAAI,CAAK,EAC7B,EAAsB,EAAI,CAAK,EAG/B,IAAM,EAAmB,EAAwB,CAAK,EAEtD,EAAG,GAAG,sBAAuB,EAAO,IAC3B,EAAiB,EAAO,CAAG,CACnC,EAGD,EAAG,GAAG,iBAAkB,EAA2B,IAAQ,CAIzD,GAHA,EAAuB,CAAG,EAGtB,CAAC,EAAI,gBAAgB,WAAY,OACrC,IAAM,EAAU,EAAI,eAAe,WAAW,EAE9C,IAAK,IAAI,EAAI,EAAQ,OAAS,EAAG,GAAK,EAAG,IAAK,CAC5C,IAAM,EAAQ,EAAQ,GACtB,GAAI,EAAM,OAAS,UAAY,EAAM,aAAe,iBAAkB,CACpE,IAAM,EAAO,EAAM,KACf,GAAQ,OAAO,GAAS,UAC1B,OAAO,OAAO,EAAO,CAAI,EAE3B,KACF,CACF,CACF,CAAC,EAGD,EAA0B,EAAI,CAAK,EAGnC,EAAoB,EAAI,EAAO,CAAQ,EACvC,EAAgB,EAAI,CAAK,EAGzB,EAAG,GAAG,uBAA0B,CAC9B,IAAK,IAAM,KAAW,EAAU,EAAQ,EACxC,EAAS,OAAS,CACpB,CAAC,EAGD,EAAwB,EAAI,CAAK,CACnC"}
|
|
1
|
+
{"version":3,"file":"extension.mjs","names":["deploySpecialistAgents","installModeAutoDetect","installModeCommands","COMMANDS_DIR","installCompactionHandlers"],"sources":["../../shared/pi/src/state-core.ts","../src/state/review.ts","../../shared/pi/src/subagent-utils.ts","../../shared/pi/src/agent-deployment.ts","../src/agents.ts","../../shared/pi/src/modes-core.ts","../src/modes.ts","../src/rules.ts","../../shared/pi/src/compaction-core.ts","../src/compaction.ts","../src/subagent.ts","../src/commands.ts","../../shared/pi/src/tools-core.ts","../src/tools.ts","../src/extension.ts"],"sourcesContent":["/**\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 function createInitialState(): MaestriaState {\n return {\n mode: null,\n activeTask: '',\n completionPromise: '',\n specialistsDelegated: [],\n blockers: [],\n filesModified: [],\n filesRead: [],\n handoffHistory: [],\n reviewMode: false,\n originalModel: null,\n originalTools: null,\n subagentStatus: {},\n reviewModel: null,\n nativeGoal: null,\n };\n}\n\nfunction 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 function recordHandoff(\n state: MaestriaState,\n from: string,\n to: string,\n task: string,\n): MaestriaState {\n const entry: HandoffEntry = { from, to, task, timestamp: Date.now() };\n const history = [entry, ...state.handoffHistory].slice(0, HANDOFF_HISTORY_CAP);\n return { ...state, handoffHistory: history };\n}\n\nexport function recordFileModified(state: MaestriaState, path: string): MaestriaState {\n return { ...state, filesModified: prependDeduped(state.filesModified, path, FILE_HISTORY_CAP) };\n}\n\nexport function recordFileRead(state: MaestriaState, path: string): MaestriaState {\n return { ...state, filesRead: prependDeduped(state.filesRead, path, FILE_HISTORY_CAP) };\n}\n\nexport function recordSpecialistDelegated(state: MaestriaState, name: string): MaestriaState {\n if (state.specialistsDelegated.includes(name)) return state;\n return { ...state, specialistsDelegated: [...state.specialistsDelegated, name] };\n}\n\nexport function recordSubagentStatus(\n state: MaestriaState,\n id: string,\n info: SubagentStatusInfo,\n): MaestriaState {\n return { ...state, subagentStatus: { ...state.subagentStatus, [id]: info } };\n}\n\nexport function setReviewMode(state: MaestriaState, active: boolean): MaestriaState {\n return { ...state, reviewMode: active };\n}\n\nexport function exitReviewMode(state: MaestriaState): {\n state: MaestriaState;\n originalModel: string | null;\n originalTools: string[] | null;\n} {\n return {\n state: {\n ...state,\n reviewMode: false,\n originalModel: null,\n originalTools: null,\n },\n originalModel: state.originalModel,\n originalTools: state.originalTools,\n };\n}\n\n// ── Persistence ──\n\nexport function 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 function 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) {\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","import type {\n ExtensionAPI,\n ExtensionCommandContext,\n ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@maestria/shared-pi/state-core';\nimport { exitReviewMode } from '@maestria/shared-pi/state-core';\n\nexport async function restoreOriginalState(\n pi: ExtensionAPI,\n ctx: ExtensionContext,\n state: MaestriaState,\n): Promise<void> {\n const { state: clearedState, originalModel, originalTools } = exitReviewMode(state);\n\n if (originalTools && originalTools.length > 0) {\n pi.setActiveTools(originalTools);\n }\n\n if (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 async function cycleToReviewModel(\n pi: ExtensionAPI,\n ctx: ExtensionCommandContext,\n state: MaestriaState,\n): Promise<string | null> {\n const reviewModel = state.reviewModel;\n if (!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 } else {\n ctx.ui.notify(`Review model \"${reviewModel}\" not found in registry, staying on current.`);\n return null;\n }\n } catch {\n ctx.ui.notify(`Could not switch to review model \"${reviewModel}\", staying on current.`);\n return null;\n }\n}\n","/**\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_STARTED: 'maestria:subagent:started',\n SUBAGENT_COMPLETED: 'maestria:subagent:completed',\n SUBAGENT_FAILED: 'maestria:subagent:failed',\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 function assertValidAgent(agent: string): asserts agent is AllowedAgent {\n if (!ALLOWED_AGENTS.includes(agent as AllowedAgent)) {\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 function assertNonEmptyTask(\n task: string | undefined,\n label: string,\n): asserts task is string {\n if (!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 function 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}:\\\\*\\\\*([\\\\s\\\\S]*?)(?=\\\n\\\\*\\\\*|$)`;\n const match = handoff.match(new RegExp(pattern, 'i'));\n if (!match || !match[1] || !match[1].trim()) {\n errors.push(`Missing or empty field: \"${field}\"`);\n }\n }\n return { valid: errors.length === 0, errors };\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 { readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\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 function 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 = join(agentsSrc, `${name}.md`);\n const destFile = 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)) continue;\n\n try {\n const content = readFileSync(srcFile, 'utf-8');\n writeFileSync(destFile, content, 'utf-8');\n deployed++;\n } catch (err) {\n console.warn(`[maestria] Failed to deploy agent ${name}:`, err);\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 { homedir } from 'node:os';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { deploySpecialistAgents as deployAgents } from '@maestria/shared-pi/agent-deployment';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst AGENTS_SRC = 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 */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function deploySpecialistAgents(_ctx?: unknown): void {\n deployAgents(AGENTS_SRC, join(homedir(), '.pi', 'agent', 'agents'));\n}\n","/**\n * Shared mode constants and 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 * in mode prompt loading, keyword detection, and text transformation.\n *\n * @module\n */\n\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport type { MaestriaState } from './state-core.js';\n\n// ── Constants ──\n\nexport const MODE_KEYWORDS = ['fein', 'sonar', 'blitz'] as const;\nexport const MODE_CLEAR_COMMAND = 'mode-clear';\nexport type ModeKeyword = (typeof MODE_KEYWORDS)[number];\n\nexport const MODE_MARKERS: Record<ModeKeyword, string> = {\n fein: '[MODE: fein]',\n sonar: '[MODE: sonar]',\n blitz: '[MODE: blitz]',\n};\n\n// ── Prompt loading ──\n\n/** Lazily cached mode prompts — shared across platforms. */\nconst _promptCache: Partial<Record<ModeKeyword, string>> = {};\n\n/**\n * Load and cache a mode prompt from a commands directory.\n * The commandsDir should point to a directory containing `fein.md`,\n * `sonar.md`, and `blitz.md` files.\n */\nexport function loadModePrompt(name: string, commandsDir: string): string {\n const content = readFileSync(resolve(commandsDir, `${name}.md`), 'utf-8');\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 * Get the full mode prompt (marker + body) for a keyword, loading from\n * the given commands directory on first access.\n */\nexport function getModePrompt(keyword: ModeKeyword, commandsDir: string): string {\n if (!(keyword in _promptCache)) {\n try {\n _promptCache[keyword] = loadModePrompt(keyword, commandsDir);\n } catch (e) {\n console.warn(`[maestria] Failed to load mode prompt \"${keyword}\":`, e);\n _promptCache[keyword] = '';\n }\n }\n return `${MODE_MARKERS[keyword]}\\n\\n${_promptCache[keyword]}`;\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/** Regex matching fenced code blocks (```) and inline backtick spans (`). */\nconst CODE_BLOCK_RE = /```[\\s\\S]*?```|`[^`]*`/g;\n\n/**\n * Find ranges of fenced code blocks and inline code spans in text.\n * Returns [start, end) positions. Keywords inside these ranges are\n * ignored during detection (per ADR-OC-003).\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 * 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 */\nconst MODE_PRIORITY: Record<ModeKeyword, number> = {\n fein: 3,\n sonar: 2,\n blitz: 1,\n};\n\n/**\n * Detect a mode keyword (fein/sonar/blitz) in text as a whole word,\n * case-insensitive. 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 * - Matches inside fenced code blocks (```) and inline backticks (`) are ignored\n */\nexport function detectModeInText(text: string, commandsDir: string): ModeDetectResult | null {\n if (!text) return null;\n\n const codeRanges = findAllCodeBlockRanges(text);\n let best: { keyword: ModeKeyword; index: number } | null = null;\n\n for (const keyword of MODE_KEYWORDS) {\n const regex = new RegExp(`\\\\b${keyword}\\\\b`, 'gi');\n let match: RegExpExecArray | null;\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 (best === null || MODE_PRIORITY[keyword] > MODE_PRIORITY[best.keyword]) {\n best = { keyword, index: match.index };\n }\n }\n }\n\n if (best === null) return null;\n\n // Strip the matched keyword, cleaning up a trailing colon and collapsing\n // double spaces (mirrors opencode's stripKeyword behavior).\n const before = text.slice(0, best.index);\n const after = text.slice(best.index + best.keyword.length).replace(/^:\\s*/, '');\n const strippedText = (before + after).replace(/ {2,}/g, ' ').trim();\n\n return {\n keyword: best.keyword,\n strippedText,\n prompt: getModePrompt(best.keyword, commandsDir),\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 function buildModeText(prompt: string, strippedText: string): string {\n return strippedText ? `${prompt}\\n\\n${strippedText}` : prompt;\n}\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 *\n * @param onInput - Platform's `pi.on('input', handler)` method\n * @param state - Shared maestria state\n * @param commandsDir - Path to directory containing fein.md/sonar.md/blitz.md\n * @param opts - Platform-specific callbacks and result builders\n */\nexport function installModeAutoDetect(\n onInput: (handler: (event: unknown, ctx: unknown) => unknown) => void,\n state: MaestriaState,\n commandsDir: string,\n opts: {\n /** Exit review mode — calls platform's restoreOriginalState */\n restoreOriginalState: (ctx: unknown) => 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: unknown;\n /** Build return value from transformed text (e.g. Pi: { action: 'transform', text }) */\n transform: (text: string) => unknown;\n },\n): void {\n onInput(async (event: unknown, ctx: unknown) => {\n const text = ((event as Record<string, unknown>).text as string) ?? '';\n const result = detectModeInText(text, commandsDir);\n if (!result) return opts.noMatch;\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 *\n * @param registerCommand - Platform's `pi.registerCommand(name, opts)` method\n * @param state - Shared maestria state\n * @param opts - Platform-specific callbacks\n */\nexport function installModeCommands(\n registerCommand: (\n name: string,\n options: { description: string; handler: (...args: unknown[]) => unknown },\n ) => void,\n state: MaestriaState,\n opts: {\n /** Exit review mode before switching modes */\n restoreOriginalState: (ctx: unknown) => 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: unknown, ctx: unknown) => {\n if (state.reviewMode) {\n await opts.restoreOriginalState(ctx);\n }\n state.mode = null;\n opts.persistState();\n ((ctx as Record<string, unknown>).ui as { notify: (msg: string) => void }).notify(\n 'Workflow mode cleared. Neutral routing is active.',\n );\n },\n });\n\n for (const keyword of MODE_KEYWORDS) {\n registerCommand(keyword, {\n description: `Set workflow mode to ${keyword}`,\n handler: async (_args: unknown, ctx: unknown) => {\n if (state.reviewMode) {\n await opts.restoreOriginalState(ctx);\n }\n\n state.mode = keyword;\n opts.persistState();\n\n ((ctx as Record<string, unknown>).ui as { notify: (msg: string) => void }).notify(\n `Mode set to ${keyword}. Describe what you'd like to work on.`,\n );\n },\n });\n }\n}\n","import { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { persistState, restoreOriginalState } from '@/state.js';\nimport {\n installModeAutoDetect as installAutoDetect,\n installModeCommands as installCommands,\n} from '@maestria/shared-pi/modes-core';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst COMMANDS_DIR = resolve(__dirname, '../agents/commands');\n\nexport function installModeAutoDetect(pi: ExtensionAPI, state: MaestriaState): void {\n installAutoDetect((handler) => pi.on('input', handler as never), state, COMMANDS_DIR, {\n restoreOriginalState: (ctx) => restoreOriginalState(pi, ctx as ExtensionContext, state),\n persistState: () => persistState(pi, state),\n noMatch: { action: 'continue' as const },\n transform: (text) => ({ action: 'transform' as const, text }),\n });\n}\n\nexport function installModeCommands(pi: ExtensionAPI, state: MaestriaState): void {\n installCommands((name, opts) => pi.registerCommand(name, opts as never), state, {\n restoreOriginalState: (ctx) => restoreOriginalState(pi, ctx as ExtensionContext, state),\n persistState: () => persistState(pi, state),\n });\n}\n","import { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type {\n BeforeAgentStartEvent,\n BeforeAgentStartEventResult,\n ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { getModePrompt } from '@maestria/shared-pi/modes-core';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst COMMANDS_DIR = 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 void (no modification),\n * letting Pi's built-in prompt assembly (skills + context files + tools)\n * stand as-is.\n */\nexport function createModePromptHandler(state: MaestriaState) {\n return (\n event: BeforeAgentStartEvent,\n _ctx: ExtensionContext,\n ): BeforeAgentStartEventResult | void => {\n if (!state.mode) return;\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}\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\n/**\n * Install handlers for session compaction and tree events to persist\n * and restore maestria state across session compaction boundaries.\n *\n * Uses duck-typed `pi` parameter — both Pi and OMP ExtensionAPI types\n * satisfy the `{ on(event: string, handler): void }` shape needed here.\n */\nexport function installCompactionHandlers(\n pi: {\n on: (event: string, handler: (...args: unknown[]) => unknown) => void;\n },\n state: MaestriaState,\n): void {\n pi.on('session_before_compact', (event: unknown) => {\n const prep = (event as Record<string, unknown>).preparation as\n | Record<string, unknown>\n | undefined;\n return {\n compaction: {\n summary: renderMaestriaSummary(state),\n details: { ...state },\n firstKeptEntryId: prep?.firstKeptEntryId,\n tokensBefore: prep?.tokensBefore,\n },\n };\n });\n\n pi.on('session_before_tree', (event: unknown) => {\n const prep = (event as Record<string, unknown>).preparation as\n | Record<string, unknown>\n | undefined;\n if (prep?.userWantsSummary) {\n return {\n summary: {\n summary: renderMaestriaSummary(state),\n },\n };\n }\n return undefined;\n });\n}\n","/**\n * Pi platform compaction handlers.\n *\n * Thin wrapper around the shared implementation in\n * @maestria/shared-pi/compaction-core.\n *\n * @module\n */\n\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { installCompactionHandlers as installHandlers } from '@maestria/shared-pi/compaction-core';\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 function installCompactionHandlers(pi: ExtensionAPI, state: MaestriaState): void {\n // Bridge: ExtensionAPI.on has overloaded event types incompatible with\n // the duck-typed { on: (event: string, handler) => void } in the shared\n // module. The as-never cast is safe at runtime — both SDKs share the same\n // event shapes.\n installHandlers(\n {\n on: (event, handler) => {\n pi.on(event as never, handler as never);\n },\n },\n state,\n );\n}\n","import { Type } from 'typebox';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport { SUBAGENT_EVENTS } from '@gotgenes/pi-subagents';\nimport type { MaestriaState } from '@/state.js';\nimport { persistState, recordHandoff, recordSpecialistDelegated } from '@/state.js';\nimport {\n ALLOWED_AGENTS,\n assertValidAgent,\n assertNonEmptyTask,\n MAESTRIA_EVENTS,\n} from '@maestria/shared-pi/subagent-utils';\n\nconst ALLOWED_AGENT_NAMES: ReadonlyArray<string> = ALLOWED_AGENTS;\n\n/** Terminal subagent statuses - agent will produce no more updates. */\nconst TERMINAL_STATUSES = new Set(['completed', 'steered', 'aborted', 'stopped', 'error']);\n\n/** Maximum time to wait for a subagent to complete, in milliseconds. */\nexport const POLL_TIMEOUT_MS = 180_000;\n\n/** Interval between subagent status checks, in milliseconds. */\nexport const POLL_INTERVAL_MS = 500;\n\n/** Maximum number of tasks allowed in parallel dispatch. */\nexport const MAX_PARALLEL_TASKS = 8;\n\n// ── Polling helper ───────────────────────────────────────────────\n\ntype SubagentRecord = { status: string; result?: string; error?: string };\n\nasync function pollSubagent(\n id: string,\n label: string,\n sendUpdates: boolean,\n service: { getRecord(id: string): SubagentRecord | undefined },\n signal: AbortSignal | undefined,\n onUpdate: ((result: { content: Array<{ type: string; text: string }> }) => void) | undefined,\n): Promise<SubagentRecord> {\n const maxPolls = POLL_TIMEOUT_MS / POLL_INTERVAL_MS;\n let polls = 0;\n let record = service.getRecord(id);\n while (record && !TERMINAL_STATUSES.has(record.status) && polls < maxPolls) {\n if (signal?.aborted) throw new Error('Maestria subagent call aborted');\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n record = service.getRecord(id);\n polls++;\n if (sendUpdates) {\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `${label} running... (${Math.round((polls * POLL_INTERVAL_MS) / 1000)}s)`,\n },\n ],\n });\n }\n }\n if (record && !TERMINAL_STATUSES.has(record.status)) {\n throw new Error(`Subagent ${id} timed out after ${POLL_TIMEOUT_MS}ms`);\n }\n if (!record) {\n throw new Error(`Subagent ${id} was cleaned up before completion`);\n }\n return record;\n}\n\n// ── Handoff recording helper ────────────────────────────────────\n\nfunction recordAndPersist(\n pi: ExtensionAPI,\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\nexport function installSubagentTool(\n pi: ExtensionAPI,\n state: MaestriaState,\n cleanups?: Array<() => void>,\n): void {\n pi.registerTool({\n name: 'maestria_subagent',\n label: 'Maestria Subagent',\n description: 'Dispatch a task to a @maestria specialist subagent',\n promptSnippet:\n 'Delegate tasks to @maestria specialist subagents (adventurer, architect, builder, planner, diagnose, reviewer, writer)',\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 prepareArguments(args: unknown) {\n return args;\n },\n parameters: Type.Object({\n agent: Type.String({\n description:\n 'Specialist agent name (required): adventurer, architect, builder, diagnose, planner, reviewer, writer',\n }),\n task: Type.String({ description: 'Task description for the subagent (required)' }),\n tasks: Type.Optional(\n Type.Array(\n Type.Object({\n agent: Type.String(),\n task: Type.String(),\n }),\n { description: 'Array of task objects for parallel or chain dispatch' },\n ),\n ),\n mode: Type.Optional(\n Type.Union([Type.Literal('parallel'), Type.Literal('chain'), Type.Literal('single')]),\n ),\n }),\n async execute(\n _toolCallId: string,\n params: {\n agent?: string;\n task?: string;\n tasks?: Array<{ agent: string; task: string }>;\n mode?: 'parallel' | 'chain' | 'single';\n },\n signal: AbortSignal | undefined,\n onUpdate: ((result: { content: Array<{ type: string; text: string }> }) => void) | undefined,\n _ctx: ExtensionContext,\n ) {\n // Block subagent dispatch when in review mode\n if (state.reviewMode) {\n return {\n content: [\n {\n type: 'text' as const,\n text: 'Subagent dispatch is not available during review mode. Use /restore-model to exit review mode first.',\n },\n ],\n };\n }\n\n // Determine dispatch mode (default to 'single' for backward compat)\n const mode = params.mode ?? 'single';\n\n // Validate parameters based on mode\n if (mode === 'single') {\n if (!params.agent || !ALLOWED_AGENT_NAMES.includes(params.agent)) {\n return {\n content: [\n {\n type: 'text' as const,\n text:\n `Invalid maestria_subagent call: 'agent' is required and must be one of ` +\n `${ALLOWED_AGENT_NAMES.join(', ')}. ` +\n `Re-dispatch with a valid agent name; the orchestrator may continue read-only exploration while the brief is corrected.`,\n },\n ],\n };\n }\n assertNonEmptyTask(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 assertValidAgent(t.agent);\n assertNonEmptyTask(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 assertValidAgent(t.agent);\n assertNonEmptyTask(t.task, 'Task description is required for all tasks');\n }\n }\n\n // Attempt to dispatch via @gotgenes/pi-subagents; handle missing service\n const { getSubagentsService } = await import('@gotgenes/pi-subagents');\n const service = getSubagentsService();\n if (!service || typeof service.spawn !== 'function') {\n return {\n content: [\n {\n type: 'text' as const,\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 },\n ],\n };\n }\n\n try {\n // --- SINGLE MODE ---\n if (mode === 'single') {\n const agent = params.agent!;\n const task = params.task!;\n\n // Spawn in foreground - returns subagent ID synchronously\n const id = service.spawn(agent, task, {\n description: task.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n\n // Record handoff in state and persist (only after spawn succeeds)\n recordAndPersist(pi, state, agent, task);\n\n // Poll for completion\n const record = await pollSubagent(\n id,\n `Subagent ${agent}`,\n true,\n service,\n signal,\n onUpdate,\n );\n\n const resultText = record.result ?? record.error ?? 'No output.';\n\n return {\n content: [{ type: 'text' as const, text: resultText }],\n details: { subagentId: id },\n };\n }\n\n // --- PARALLEL MODE ---\n if (mode === 'parallel') {\n const taskList = params.tasks!;\n\n onUpdate?.({\n content: [\n { type: 'text' as const, text: `Spawning ${taskList.length} parallel subagents...` },\n ],\n });\n\n // Spawn all tasks\n const spawnedIds: string[] = [];\n for (const t of taskList) {\n const id = service.spawn(t.agent, t.task, {\n description: t.task.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n spawnedIds.push(id);\n\n // Record each handoff\n recordAndPersist(pi, state, t.agent, t.task);\n }\n\n // Poll all concurrently\n const records = await Promise.all(\n spawnedIds.map((id, i) =>\n pollSubagent(\n id,\n `${taskList[i].agent} (${i + 1}/${taskList.length})`,\n false,\n service,\n signal,\n onUpdate,\n ),\n ),\n );\n\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `All ${taskList.length} parallel subagents completed.`,\n },\n ],\n });\n\n // Aggregate results\n const parts = [`## Parallel Results (${taskList.length} tasks)\\n`];\n for (let i = 0; i < taskList.length; i++) {\n const t = taskList[i];\n const rec = records[i];\n const resultText = rec.result ?? rec.error ?? 'No output.';\n parts.push(`### ${i + 1}: ${t.agent}`);\n parts.push(resultText);\n }\n\n return {\n content: [{ type: 'text' as const, text: parts.join('\\n\\n') }],\n details: { subagentIds: spawnedIds },\n };\n }\n\n // --- CHAIN MODE ---\n if (mode === 'chain') {\n const taskList = params.tasks!;\n let previousResult = '';\n\n for (let i = 0; i < taskList.length; i++) {\n const t = taskList[i];\n let taskText = t.task;\n\n // Substitute {previous} placeholder with previous result\n if (i > 0 && taskText.includes('{previous}')) {\n taskText = taskText.replace(/\\{previous\\}/g, previousResult);\n }\n\n const id = service.spawn(t.agent, taskText, {\n description: taskText.slice(0, 80),\n foreground: true,\n inheritContext: true,\n });\n\n // Record handoff\n recordAndPersist(pi, state, t.agent, taskText);\n\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `Chain step ${i + 1}/${taskList.length}: ${t.agent} running...`,\n },\n ],\n });\n\n // Poll for completion\n const record = await pollSubagent(\n id,\n `Chain step ${i + 1}: ${t.agent}`,\n true,\n service,\n signal,\n onUpdate,\n );\n\n previousResult = record.result ?? record.error ?? 'No output.';\n\n if (i < taskList.length - 1) {\n onUpdate?.({\n content: [\n {\n type: 'text' as const,\n text: `Chain step ${i + 1}/${taskList.length}: ${t.agent} completed. Moving to next step.`,\n },\n ],\n });\n }\n }\n\n return {\n content: [{ type: 'text' as const, text: previousResult }],\n details: { subagentId: 'chain-completed' },\n };\n }\n\n // Should not reach here - all modes are handled above\n throw new Error('Unknown dispatch mode');\n } catch (err) {\n console.warn('[maestria] Subagent dispatch failed:', err);\n // Return handoff payload as structured text when dispatch fails\n const agentName = params.agent ?? params.tasks?.[0]?.agent ?? 'unknown';\n const taskDesc = params.task ?? params.tasks?.map((t) => t.task).join('; ') ?? 'unknown';\n const handoffInfo = [\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\n return {\n content: [{ type: 'text' as const, text: handoffInfo }],\n };\n }\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any); // TypeBox inferred types don't match ToolDefinition exactly\n\n // Subscribe to subagent lifecycle events for accurate state tracking.\n // These subscriptions are set up once at extension init, not on every tool call.\n // pi.events is the shared EventBus - distinct from pi.on() lifecycle hooks.\n if (pi.events) {\n const unsubStarted = pi.events.on(SUBAGENT_EVENTS.STARTED, (data: unknown) => {\n const { id, type } = data as { id: string; type: string };\n state.subagentStatus[id] = { type, status: 'running', startedAt: Date.now() };\n persistState(pi, state);\n pi.events?.emit(MAESTRIA_EVENTS.SUBAGENT_STARTED, {\n id,\n type,\n timestamp: Date.now(),\n });\n });\n\n const unsubCompleted = pi.events.on(SUBAGENT_EVENTS.COMPLETED, (data: unknown) => {\n const { id } = data as { id: string };\n const existing = state.subagentStatus[id];\n if (existing) {\n existing.status = 'completed';\n existing.completedAt = Date.now();\n }\n persistState(pi, state);\n pi.events?.emit(MAESTRIA_EVENTS.SUBAGENT_COMPLETED, {\n id,\n type: existing?.type,\n timestamp: Date.now(),\n });\n });\n\n const unsubFailed = pi.events.on(SUBAGENT_EVENTS.FAILED, (data: unknown) => {\n const { id, status } = data as { id: string; status: string };\n const existing = state.subagentStatus[id];\n if (existing) {\n existing.status = status ?? 'error';\n existing.completedAt = Date.now();\n }\n persistState(pi, state);\n pi.events?.emit(MAESTRIA_EVENTS.SUBAGENT_FAILED, {\n id,\n type: existing?.type,\n timestamp: Date.now(),\n });\n });\n\n const unsubSteered = pi.events.on(SUBAGENT_EVENTS.STEERED, (data: unknown) => {\n // Steering is informational - no status transition, but ensure\n // the agent is tracked as running if it wasn't already observed.\n const { id } = data as { id: string };\n if (!state.subagentStatus[id]) {\n state.subagentStatus[id] = { type: 'unknown', status: 'running', startedAt: Date.now() };\n }\n persistState(pi, state);\n });\n\n if (cleanups) {\n cleanups.push(unsubStarted, unsubCompleted, unsubFailed, unsubSteered);\n }\n }\n}\n","import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport {\n cycleToReviewModel,\n persistState,\n renderMaestriaSummary,\n restoreOriginalState,\n} from '@/state.js';\nimport { MAESTRIA_EVENTS } from '@maestria/shared-pi/subagent-utils';\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\nexport function installCommands(pi: ExtensionAPI, state: MaestriaState): void {\n pi.registerCommand('maestria-status', {\n description: 'Show current maestria session state including handoff history',\n handler: async (_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 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\n // 1. Save current model and tools for later restoration\n const currentModelId = ctx.model?.id ?? null;\n const currentTools = pi.getActiveTools();\n\n // 2. Update state: mark review mode, store originals\n const updatedState: MaestriaState = {\n ...state,\n reviewMode: true,\n originalModel: currentModelId,\n originalTools: currentTools,\n };\n Object.assign(state, updatedState);\n persistState(pi, state);\n\n // 3. Switch to review model if configured\n if (state.reviewModel) {\n const switched = await cycleToReviewModel(pi, ctx, state);\n if (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\n // 4. Restrict to read-only tools\n pi.setActiveTools(READ_ONLY_TOOLS);\n\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 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 pi.registerCommand('handoff', {\n description: 'Generate a structured handoff prompt for a new task context',\n handler: async (args: string, ctx) => {\n if (!args.trim()) {\n ctx.ui.notify('Usage: /handoff <goal> - describe the task context for handoff');\n return;\n }\n\n // Build a structured handoff document with 7 fields\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 '- Recent handoffs: ' + (state.handoffHistory?.length ?? 0) + ' entries',\n '- Files modified: ' +\n ((state.filesModified?.length ?? 0) > 0 ? state.filesModified.join(', ') : 'none'),\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\n // Record in state\n state.handoffHistory = [\n { from: 'current', to: 'next', task: goal, timestamp: Date.now() },\n ...(state.handoffHistory ?? []),\n ].slice(0, 5);\n\n // Persist state\n persistState(pi, state);\n\n // Send as user message with steer delivery\n pi.sendUserMessage(handoffPrompt, { deliverAs: 'steer' });\n },\n });\n\n pi.registerCommand('review-model', {\n description: 'Set which model to use when entering review mode',\n handler: async (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","/**\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\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+\\//,\n /dd\\s+if=/,\n />\\s*\\/dev\\/sd/,\n /chmod\\s+-R\\s+777\\s+\\//,\n /mkfs\\.\\w+/,\n /:(){ :\\|:& };:/,\n />\\s*\\/etc\\/(passwd|shadow|sudoers)/,\n /\\beval\\b/,\n /wget\\s+-O\\s*-\\s*\\|\\s*(bash|sh)/,\n /curl\\s+.*\\|\\s*(bash|sh)/,\n /crontab\\s+-r/,\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 /^(ls|cat|head|tail|git status|git diff|git log|git branch|find|grep|rg|pnpm test|npm test|pwd|which)\\b/;\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 function isReadOnlyBashCommand(rawCommand: string): boolean {\n const command = rawCommand.trim();\n if (command.includes('$(') || command.includes('`')) return false;\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.replace(/\\d?>&[12]/g, '');\n if (withoutFdRedirects.includes('>')) return false;\n return withoutFdRedirects\n .split(/[\\n;&|]+/)\n .every((segment) => READ_ONLY_BASH_PREFIX.test(segment.trim()));\n}\n","import {\n isToolCallEventType,\n type ExtensionAPI,\n type ToolCallEvent,\n type ExtensionContext,\n} from '@earendil-works/pi-coding-agent';\nimport type { MaestriaState } from '@/state.js';\nimport { DANGEROUS_PATTERNS, isReadOnlyBashCommand } from '@maestria/shared-pi/tools-core';\nimport { persistState, recordFileModified, recordFileRead } from '@/state.js';\n\nexport function installToolInterceptors(pi: ExtensionAPI, state: MaestriaState): void {\n pi.on('tool_call', async (event: ToolCallEvent, ctx: ExtensionContext) => {\n if (!event || !event.toolName) return;\n\n // ── Orchestrator routing enforcement ──\n // When a maestria workflow mode is active, restrict the root session\n // (orchestrator) to read-only recon + delegation. The orchestrator may\n // read, search, and inspect to route and verify, but mutations (edit,\n // write, mutation-capable bash) belong to specialists. Subagent sessions\n // are detected by the absence of the pi-subagents 'subagent' tool\n // (stripped by applyRecursionGuard in child sessions).\n if (state.mode !== null && pi.getActiveTools().includes('subagent')) {\n const isMutation =\n isToolCallEventType('edit', event) ||\n isToolCallEventType('write', event) ||\n isToolCallEventType('patch', event) ||\n event.toolName === 'bash';\n if (isMutation) {\n // Read-only bash (ls, git status, git diff, tests) is allowed so the\n // orchestrator can verify state; mutation-capable commands still\n // belong to specialists.\n if (event.toolName === 'bash') {\n const input = event.input as { command?: unknown } | 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:\n `Tool '${event.toolName}' is blocked for the orchestrator. ` +\n `Use 'maestria_subagent' to delegate mutations to specialists.`,\n };\n }\n }\n\n // Block destructive tools in review mode\n if (state.reviewMode) {\n if (\n isToolCallEventType('edit', event) ||\n isToolCallEventType('write', event) ||\n isToolCallEventType('bash', event)\n ) {\n return {\n block: true,\n reason: 'Review mode is active. Report findings, do not edit.',\n };\n }\n }\n\n // Block dangerous bash patterns regardless of mode\n if (isToolCallEventType('bash', event)) {\n if (!event.input || typeof event.input !== 'object') return undefined;\n const command = event.input.command;\n if (command) {\n for (const pattern of DANGEROUS_PATTERNS) {\n if (pattern.test(command)) {\n if (ctx.hasUI) {\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) return undefined;\n }\n return {\n block: true,\n reason: `Command matches dangerous pattern: ${pattern}`,\n };\n }\n }\n }\n }\n\n // Record file access for session state (ADR-PI-002: tool_call maintains file tracking).\n // Only record when the call is allowed to proceed.\n let tracked = false;\n if (isToolCallEventType('read', event)) {\n const path = event.input?.path;\n if (typeof path === 'string' && path) {\n Object.assign(state, recordFileRead(state, path));\n tracked = true;\n }\n } else if (isToolCallEventType('edit', event) || isToolCallEventType('write', event)) {\n const path = event.input?.path;\n if (typeof path === 'string' && path) {\n Object.assign(state, recordFileModified(state, path));\n tracked = true;\n }\n }\n if (tracked) {\n persistState(pi, state);\n }\n\n return undefined; // allow\n });\n}\n","import type {\n ExtensionAPI,\n ExtensionContext,\n SessionStartEvent,\n SessionTreeEvent,\n} from '@earendil-works/pi-coding-agent';\nimport { createInitialState } from '@/state.js';\nimport type { MaestriaState } from '@/state.js';\nimport { deploySpecialistAgents } from '@/agents.js';\nimport { installModeCommands, installModeAutoDetect } from '@/modes.js';\nimport { createModePromptHandler } from '@/rules.js';\nimport { installCompactionHandlers } from '@/compaction.js';\nimport { installSubagentTool } from '@/subagent.js';\nimport { installCommands } from '@/commands.js';\nimport { installToolInterceptors } from '@/tools.js';\n\ninterface PersistedStateEntry {\n type: string;\n customType?: string;\n data?: unknown;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction 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') return null;\n\n const branch = sessionManager.getBranch();\n return Array.isArray(branch) ? (branch as PersistedStateEntry[]) : null;\n}\n\nfunction restoreStateFromSession(state: MaestriaState, ctx: ExtensionContext): void {\n const next = createInitialState();\n const entries = currentSessionEntries(ctx);\n\n if (!entries) {\n const mutableState = state as unknown as Record<string, unknown>;\n for (const key of Object.keys(mutableState)) delete mutableState[key];\n Object.assign(state, next);\n return;\n }\n\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i];\n if (entry.type === 'custom' && entry.customType === 'maestria_state') {\n if (isRecord(entry.data)) Object.assign(next, entry.data);\n break;\n }\n }\n\n const mutableState = state as unknown as Record<string, unknown>;\n for (const key of Object.keys(mutableState)) delete mutableState[key];\n Object.assign(state, next);\n}\n\nexport default function (pi: ExtensionAPI): void {\n const state = createInitialState();\n const cleanups: Array<() => void> = [];\n\n // Install mode commands: /fein, /sonar, /blitz\n installModeCommands(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) => {\n return handleModePrompt(event, ctx);\n });\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(pi, state);\n\n // Install orchestration hooks: subagent tool and commands\n installSubagentTool(pi, state, cleanups);\n installCommands(pi, state);\n\n // Cleanup subscriptions on shutdown\n pi.on('session_shutdown', () => {\n for (const cleanup of cleanups) cleanup();\n cleanups.length = 0;\n });\n\n // Install tool call interceptors for review mode and dangerous patterns\n installToolInterceptors(pi, state);\n}\n"],"mappings":"6XA6DA,SAAgB,GAAoC,CAClD,MAAO,CACL,KAAM,KACN,WAAY,GACZ,kBAAmB,GACnB,qBAAsB,CAAC,EACvB,SAAU,CAAC,EACX,cAAe,CAAC,EAChB,UAAW,CAAC,EACZ,eAAgB,CAAC,EACjB,WAAY,GACZ,cAAe,KACf,cAAe,KACf,eAAgB,CAAC,EACjB,YAAa,KACb,WAAY,IACd,CACF,CAEA,SAAS,EAAe,EAAiB,EAAc,EAAuB,CAE5E,MAAO,CAAC,EAAM,GADG,EAAM,OAAQ,GAAM,IAAM,CACnB,CAAC,CAAC,CAAC,MAAM,EAAG,CAAG,CACzC,CAEA,SAAgB,EACd,EACA,EACA,EACA,EACe,CAEf,IAAM,EAAU,CAAC,CADa,OAAM,KAAI,OAAM,UAAW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CAAK,EAEtD,EAAG,GAAG,sBAAuB,EAAO,IAC3B,EAAiB,EAAO,CAAG,CACnC,EAGD,EAAG,GAAG,iBAAkB,EAA2B,IAAQ,CACzD,GAAuB,CAAG,EAG1B,EAAwB,EAAO,CAAG,CACpC,CAAC,EAGD,EAAG,GAAG,gBAAiB,EAA0B,IAAQ,CACvD,EAAwB,EAAO,CAAG,CACpC,CAAC,EAGD,EAA0B,EAAI,CAAK,EAGnC,EAAoB,EAAI,EAAO,CAAQ,EACvC,GAAgB,EAAI,CAAK,EAGzB,EAAG,GAAG,uBAA0B,CAC9B,IAAK,IAAM,KAAW,EAAU,EAAQ,EACxC,EAAS,OAAS,CACpB,CAAC,EAGD,EAAwB,EAAI,CAAK,CACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maestria/pi",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.5",
|
|
4
4
|
"description": "Maestria extension for the Pi coding agent",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-orchestration",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"build": "vp pack",
|
|
54
54
|
"test": "vp test",
|
|
55
55
|
"lint": "vp check",
|
|
56
|
-
"sync": "
|
|
56
|
+
"sync": "pnpm exec tsx ../core/scripts/sync.ts --config sync.config.ts",
|
|
57
57
|
"validate-skills": "node --experimental-strip-types scripts/validate-skills.ts",
|
|
58
58
|
"validate": "npm run validate-skills"
|
|
59
59
|
}
|
|
@@ -12,98 +12,69 @@ description: >-
|
|
|
12
12
|
|
|
13
13
|
# Global Agent Rules
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
This is the cross-platform behavior contract. It defines outcomes, evidence, safety, delegation, review, and bounded repair. The host runtime defines tool authority and lifecycle; specialists own their role methodology.
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
## Universal Floors
|
|
18
18
|
|
|
19
|
-
`!!!`
|
|
19
|
+
`!!!` marks a non-negotiable default-path rule. Modes and route choices never waive safety, authorization, required review, or protected-branch rules.
|
|
20
20
|
|
|
21
|
-
- **!!!
|
|
22
|
-
- **!!!
|
|
23
|
-
-
|
|
24
|
-
-
|
|
25
|
-
- **!!!
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
- **!!! 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.
|
|
29
|
-
- **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.
|
|
30
|
-
- **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.
|
|
31
|
-
- **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 once per session when needed and reuses the context; rules are propagated to routed agents via delegation prompts. See the orchestrator prompt for details.
|
|
21
|
+
- **!!! Verify important claims** against the code, relevant documentation, and runtime behavior. Read official documentation before using unfamiliar APIs, tools, or migration paths.
|
|
22
|
+
- **!!! Optimize for the user outcome and observable evidence.** Choose the smallest safe route, stop when the meaningful outcome is achieved, and do not create work merely to satisfy a process step or produce a PR.
|
|
23
|
+
- Do not avoid useful analysis or investigation by anthropomorphizing machine effort; choose approaches by technical trade-offs and evidence.
|
|
24
|
+
- Audit and ship affected documentation and required changesets with code when project policy requires them.
|
|
25
|
+
- **!!! Exhaust available evidence before asking.** Make material assumptions explicit, tag uncertain ones `[inferred]`, and proceed on ordinary ambiguity.
|
|
26
|
+
- **!!! Keep public output self-contained and professional.** Do not leak internal context, and understand existing systems before adapting or deleting them.
|
|
27
|
+
- State what the host guarantees versus what is only advisory. Never claim tool isolation, context isolation, lifecycle control, or maker/checker enforcement that the runtime does not provide.
|
|
32
28
|
|
|
33
|
-
|
|
29
|
+
## Precedence and Project Rules
|
|
34
30
|
|
|
35
|
-
-
|
|
36
|
-
-
|
|
37
|
-
-
|
|
38
|
-
- **Local files - read directly** with file reading tools (read, glob, grep, or code-intelligence tools). Never fetch local files via URL.
|
|
39
|
-
- **CLI references - local first.** Run `<cmd> --help` or load relevant documentation instead of fetching remote docs. Local tools are faster and more reliable.
|
|
31
|
+
- Safety and authorization override user intent, methodology, and brevity.
|
|
32
|
+
- When relevant, load `.maestria/workflow.md` and `.maestria/rules.md` once per session. Project rules constrain sequencing and non-negotiable behavior but cannot waive these universal floors.
|
|
33
|
+
- Modes are per-turn when the host supports them: `fein` requests the full route with review, `sonar` is research-only, and `blitz` skips optional ceremony only. Persisted modes must expose a clear/reset path.
|
|
40
34
|
|
|
41
|
-
##
|
|
35
|
+
## Outcome and Scope
|
|
42
36
|
|
|
43
|
-
-
|
|
44
|
-
-
|
|
45
|
-
-
|
|
46
|
-
-
|
|
37
|
+
- Define the primary user outcome, acceptance evidence, and meaningful non-goals before implementation or delegation when the task needs them.
|
|
38
|
+
- Compare progress with the outcome and acceptance evidence, not activity or process completion.
|
|
39
|
+
- Keep file, package, and runtime scope explicit. Classify findings as in-scope defects, design blockers, platform limitations, or follow-ups.
|
|
40
|
+
- Adjacent findings do not expand the current task automatically. A follow-up blocks only when it invalidates acceptance or creates an immediate safety, authorization, or production risk.
|
|
41
|
+
- Security, authentication, authorization, and permission findings are mandatory stops. Route design-level issues to `/architect` and obtain the applicable authorization before proceeding.
|
|
47
42
|
|
|
48
|
-
##
|
|
43
|
+
## Delegation and Context
|
|
49
44
|
|
|
50
|
-
|
|
45
|
+
Supported specialists are `adventurer`, `architect`, `builder`, `diagnose`, `planner`, `reviewer`, and `writer`.
|
|
51
46
|
|
|
52
|
-
-
|
|
53
|
-
-
|
|
54
|
-
-
|
|
55
|
-
-
|
|
56
|
-
-
|
|
57
|
-
-
|
|
58
|
-
- **Before reporting done:** verify termination condition met (cite evidence), assumptions tagged `[verified]`/`[inferred]`, escalation format used if blocked.
|
|
47
|
+
- Delegate only when another context, expertise, independent check, or parallel workstream materially improves the outcome. A delegation owns one coherent outcome.
|
|
48
|
+
- A useful handoff contains only the material needed to act: outcome, relevant context and constraints, acceptance or expected evidence, material assumptions or known problems, and the next step or blocker.
|
|
49
|
+
- A specialist reports what it produced, changed files or artifacts, evidence of validation, blockers or follow-ups, and the next step. Empty, malformed, unavailable, or blocked output is not success.
|
|
50
|
+
- When delegation fails, preserve useful state and make one justified recovery attempt when the cause is identifiable or transport can be retried. User or intentional platform cancellation is terminal. If recovery fails, stop dependent work, report the delta, and never mutate directly as a fallback.
|
|
51
|
+
- Parallelize only independent work with non-overlapping writers. Integrate results before reviewing the combined change.
|
|
52
|
+
- Before handoff or compaction, preserve the outcome, decisions, assumptions and evidence, changed files, validation, blockers, and next step.
|
|
59
53
|
|
|
60
|
-
##
|
|
54
|
+
## Acceptance and Blind Review
|
|
61
55
|
|
|
62
|
-
|
|
56
|
+
- **!!! Maker/checker split:** the implementer must not approve its own work.
|
|
57
|
+
- The checker independently inspects the requirements, acceptance criteria, relevant diff, and available validation or behavior evidence; maker claims and maker-authored narrative are not approval.
|
|
58
|
+
- Review against acceptance, correctness, safety, and the diff. Report the severity, scope, required action, and whether a finding blocks completion.
|
|
59
|
+
- In-scope defects may be repaired autonomously. Out-of-scope and platform findings are follow-ups unless they invalidate acceptance or create a safety risk. Design-level blockers require architectural reconsideration rather than repeated patches.
|
|
60
|
+
- Completion requires observable evidence for the acceptance criteria. Never claim an unverified result.
|
|
63
61
|
|
|
64
|
-
|
|
65
|
-
| --- | --- | --- |
|
|
66
|
-
| `/adventurer` | Codebase reconnaissance, deep code understanding | Understanding unfamiliar code, tracing dependencies, gathering context before implementation |
|
|
67
|
-
| `/architect` | Architecture decisions, trade-off analysis, ADRs | Choosing between approaches, technology evaluation |
|
|
68
|
-
| `/builder` | Focused implementation, single-task execution | Feature work, bug fixes, test writing, refactors |
|
|
69
|
-
| `/diagnose` | Systematic bug tracing, root cause analysis | Debugging regressions, production incidents, cryptic errors |
|
|
70
|
-
| `/planner` | Implementation plans with phased milestones | Complex features requiring structured execution |
|
|
71
|
-
| `/reviewer` | Code review with quality gates | Pre-merge review, security audit, post-implementation QA |
|
|
72
|
-
| `/writer` | Documentation following structured patterns | READMEs, API docs, changelogs, ADR transcription |
|
|
62
|
+
## Bounded Repair and Fail-Loud Behavior
|
|
73
63
|
|
|
74
|
-
|
|
64
|
+
- Ordinary in-scope repair may continue without routine user approval while it is making observable progress and remains within scope.
|
|
65
|
+
- Set a practical repair bound, normally three rounds. Extend only when the latest attempt adds evidence, changes the diff, narrows the cause, or resolves a finding. Never silently reset the bound.
|
|
66
|
+
- Repeated causes, repeated findings, restored diffs, or no new evidence are non-progress. Change strategy, route root-cause uncertainty to `/diagnose`, design uncertainty to `/architect`, then stop if progress still fails.
|
|
67
|
+
- Do not loop silently. Report: `Tried X, Y, Z. Blocked by [cause]. Need [input] to proceed.` Preserve the last diff and finding provenance.
|
|
75
68
|
|
|
76
|
-
|
|
77
|
-
- **State checkpointing** - periodically summarize what's done, what's in progress, what's next.
|
|
78
|
-
- **Context pruning** - remove irrelevant context when no longer needed.
|
|
79
|
-
- **Completion promises** - define success criteria before starting work. "This task is complete when [verifiable conditions]."
|
|
69
|
+
## Authorization, Lifecycle, and Branches
|
|
80
70
|
|
|
81
|
-
|
|
71
|
+
- Stop and obtain applicable authorization before security-boundary changes, authentication or permissions work, data migration or possible loss, production-impacting changes, or irreversible operations. Ordinary ambiguity is not an authorization checkpoint.
|
|
72
|
+
- Before completion, stop background processes started for the task unless they are intentionally part of the requested result. Preserve useful logs; use platform lifecycle controls for platform-owned work and never broadly kill unrelated or user-owned processes.
|
|
73
|
+
- Validated, independently reviewed work may be committed by the authorized executor on a recognized feature branch after inspecting and staging only the intended diff.
|
|
74
|
+
- Never commit or push protected branches. Commit, push, PR, merge, and release are separate gates. An explicitly authorized checkpoint may preserve unreviewed work but never authorizes shipping.
|
|
82
75
|
|
|
83
|
-
|
|
76
|
+
## Canonical Source Invariant
|
|
84
77
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
| `/reviewer` | Different PRs/changes | Same PR (sequential after `/builder`) |
|
|
89
|
-
| `/adventurer` | Different modules/areas | Same module (overlapping reports) |
|
|
90
|
-
| `/architect` | Different decisions | Same decision (ADR is single-writer) |
|
|
91
|
-
| `/planner` | Different features | Same feature (plan is single-writer) |
|
|
92
|
-
| `/writer` | Different documents | Same document (doc is single-writer) |
|
|
93
|
-
| `/diagnose` | Different bugs | Same bug or root-cause cluster |
|
|
94
|
-
|
|
95
|
-
## Commit Policy
|
|
96
|
-
|
|
97
|
-
- **Only the orchestrator authorizes commits.** Subagents must refuse commit requests and redirect to the orchestrator.
|
|
98
|
-
- **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.
|
|
99
|
-
- **Plans must not include implicit commit steps.** Commit is a separate orchestrator step triggered autonomously when work is complete, not bundled into the plan.
|
|
100
|
-
|
|
101
|
-
## Pipeline Patterns
|
|
102
|
-
|
|
103
|
-
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.
|
|
104
|
-
|
|
105
|
-
## Branch Discipline
|
|
106
|
-
|
|
107
|
-
- **!!! Never commit or push to main.** Always work on a feature branch. If you land on main, checkout a new branch first.
|
|
108
|
-
- **If on a worktree:** Proceed directly - worktrees are isolated by design. No branch check needed.
|
|
109
|
-
- **Pull latest before branching:** Before creating a new feature branch from main, run `git pull origin main` first.
|
|
78
|
+
- Author agent directives only under `packages/core/agent-directives/`.
|
|
79
|
+
- Generate platform projections with `scripts/sync-all`; never hand-edit them.
|
|
80
|
+
- Pass the sync check before handing off a canonical directive change.
|