iosm-cli 0.2.10 → 0.2.11

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.
Files changed (75) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +11 -2
  3. package/dist/core/agent-session.d.ts +4 -0
  4. package/dist/core/agent-session.d.ts.map +1 -1
  5. package/dist/core/agent-session.js +123 -49
  6. package/dist/core/agent-session.js.map +1 -1
  7. package/dist/core/background-processes.d.ts +31 -0
  8. package/dist/core/background-processes.d.ts.map +1 -0
  9. package/dist/core/background-processes.js +241 -0
  10. package/dist/core/background-processes.js.map +1 -0
  11. package/dist/core/bash-executor.d.ts +6 -0
  12. package/dist/core/bash-executor.d.ts.map +1 -1
  13. package/dist/core/bash-executor.js.map +1 -1
  14. package/dist/core/extensions/types.d.ts +3 -0
  15. package/dist/core/extensions/types.d.ts.map +1 -1
  16. package/dist/core/extensions/types.js.map +1 -1
  17. package/dist/core/extensions/wrapper.d.ts +19 -2
  18. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  19. package/dist/core/extensions/wrapper.js +23 -4
  20. package/dist/core/extensions/wrapper.js.map +1 -1
  21. package/dist/core/mcp/runtime.d.ts.map +1 -1
  22. package/dist/core/mcp/runtime.js +2 -0
  23. package/dist/core/mcp/runtime.js.map +1 -1
  24. package/dist/core/messages.d.ts +1 -1
  25. package/dist/core/messages.d.ts.map +1 -1
  26. package/dist/core/messages.js +2 -1
  27. package/dist/core/messages.js.map +1 -1
  28. package/dist/core/sdk.d.ts.map +1 -1
  29. package/dist/core/sdk.js +30 -2
  30. package/dist/core/sdk.js.map +1 -1
  31. package/dist/core/settings-manager.d.ts +17 -0
  32. package/dist/core/settings-manager.d.ts.map +1 -1
  33. package/dist/core/settings-manager.js +29 -0
  34. package/dist/core/settings-manager.js.map +1 -1
  35. package/dist/core/slash-commands.d.ts.map +1 -1
  36. package/dist/core/slash-commands.js +4 -0
  37. package/dist/core/slash-commands.js.map +1 -1
  38. package/dist/core/subagents.d.ts +10 -2
  39. package/dist/core/subagents.d.ts.map +1 -1
  40. package/dist/core/subagents.js +66 -17
  41. package/dist/core/subagents.js.map +1 -1
  42. package/dist/core/system-prompt.d.ts +25 -0
  43. package/dist/core/system-prompt.d.ts.map +1 -1
  44. package/dist/core/system-prompt.js +146 -14
  45. package/dist/core/system-prompt.js.map +1 -1
  46. package/dist/core/tools/bash.d.ts +5 -0
  47. package/dist/core/tools/bash.d.ts.map +1 -1
  48. package/dist/core/tools/bash.js +28 -2
  49. package/dist/core/tools/bash.js.map +1 -1
  50. package/dist/core/tools/index.d.ts +2 -1
  51. package/dist/core/tools/index.d.ts.map +1 -1
  52. package/dist/core/tools/index.js.map +1 -1
  53. package/dist/core/tools/permissions.d.ts +3 -0
  54. package/dist/core/tools/permissions.d.ts.map +1 -1
  55. package/dist/core/tools/permissions.js.map +1 -1
  56. package/dist/core/tools/task.d.ts +3 -1
  57. package/dist/core/tools/task.d.ts.map +1 -1
  58. package/dist/core/tools/task.js +48 -23
  59. package/dist/core/tools/task.js.map +1 -1
  60. package/dist/main.d.ts.map +1 -1
  61. package/dist/main.js +93 -1
  62. package/dist/main.js.map +1 -1
  63. package/dist/modes/interactive/interactive-mode.d.ts +5 -0
  64. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  65. package/dist/modes/interactive/interactive-mode.js +252 -24
  66. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  67. package/docs/cli-reference.md +5 -0
  68. package/docs/configuration.md +57 -1
  69. package/docs/development-and-testing.md +3 -2
  70. package/docs/extensions-packages-themes.md +27 -0
  71. package/docs/interactive-mode.md +3 -0
  72. package/docs/orchestration-and-subagents.md +16 -0
  73. package/docs/rpc-json-sdk.md +14 -0
  74. package/docs/sessions-traces-export.md +7 -0
  75. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"subagents.js","sourceRoot":"","sources":["../../src/core/subagents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,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CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxD,IAAI,WAAW,KAAK,CAAC;YAAE,OAAO,WAAW,CAAC;QAC1C,OAAO,KAAK,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IACnD,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport { isValidProfileName, type AgentProfileName } from \"./agent-profiles.js\";\n\nexport type CustomSubagentSourceScope = \"builtin\" | \"global\" | \"project\";\n\nexport interface CustomSubagentDefinition {\n\tname: string;\n\tdescription: string;\n\tsourcePath: string;\n\tprofile?: AgentProfileName;\n\ttools?: string[];\n\tdisallowedTools?: string[];\n\tsystemPrompt?: string;\n\tinstructions: string;\n\tcwd?: string;\n\tmodel?: string;\n\tbackground?: boolean;\n}\n\nexport interface CustomSubagentEntry extends CustomSubagentDefinition {\n\tsourceScope: CustomSubagentSourceScope;\n\tsourcePriority: number;\n\teffective: boolean;\n\toverriddenByPath?: string;\n}\n\nexport interface SubagentOverrideInfo {\n\tname: string;\n\twinnerPath: string;\n\twinnerScope: CustomSubagentSourceScope;\n\toverriddenPath: string;\n\toverriddenScope: CustomSubagentSourceScope;\n}\n\nexport interface SubagentDiagnostic {\n\tpath: string;\n\tmessage: string;\n}\n\nexport interface LoadCustomSubagentsResult {\n\tagents: CustomSubagentEntry[];\n\tallAgents: CustomSubagentEntry[];\n\toverrides: SubagentOverrideInfo[];\n\tdiagnostics: SubagentDiagnostic[];\n}\n\nconst BUILTIN_SUBAGENT_PRIORITY = -1;\n\nconst BUILTIN_SUBAGENTS: CustomSubagentDefinition[] = [\n\t{\n\t\tname: \"codebase_auditor\",\n\t\tdescription: \"Structured codebase audit for architecture, reliability, security, and test gaps.\",\n\t\tsourcePath: \"builtin://codebase_auditor.md\",\n\t\tprofile: \"explore\",\n\t\tinstructions: [\n\t\t\t\"You are a codebase auditor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Produce an evidence-based audit of architecture, defect risks, and maintainability hotspots.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read-only operation. Never edit files.\",\n\t\t\t\"- Make claims only with direct repository evidence.\",\n\t\t\t\"- Prioritize by user impact and likelihood (P0..P3).\",\n\t\t\t\"- If the assigned audit still spans multiple independent subsystems and delegation protocol is available, split it with nested delegates instead of producing one monolithic audit.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Findings (ordered by severity)\",\n\t\t\t\"2) Open questions/unknowns\",\n\t\t\t\"3) Recommended next actions\",\n\t\t\t\"\",\n\t\t\t\"For each finding include:\",\n\t\t\t\"- file path + line reference (when available)\",\n\t\t\t\"- risk/impact\",\n\t\t\t\"- concrete fix direction\",\n\t\t\t\"\",\n\t\t\t\"If no issues are found, explicitly state 'No findings' and list residual risks/testing gaps.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"system_error_analyst\",\n\t\tdescription: \"Diagnoses system/runtime failures and produces root-cause + fix plan.\",\n\t\tsourcePath: \"builtin://system_error_analyst.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a system error analyst.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Triage failures, identify probable root cause, and propose a minimal, testable fix plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Do not modify files.\",\n\t\t\t\"- Use deterministic evidence (logs, stack traces, tests, configs).\",\n\t\t\t\"- Distinguish facts vs hypotheses explicitly.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Incident summary\",\n\t\t\t\"2) Root-cause analysis (ranked hypotheses with evidence)\",\n\t\t\t\"3) Minimal patch plan\",\n\t\t\t\"4) Verification plan (commands + expected signals)\",\n\t\t\t\"5) Regression risks\",\n\t\t\t\"\",\n\t\t\t\"Escalation guidance:\",\n\t\t\t\"- If data is insufficient, request the minimum missing evidence instead of guessing.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_change_executor\",\n\t\tdescription: \"Implements repository changes under IOSM methodology and keeps artifacts aligned.\",\n\t\tsourcePath: \"builtin://iosm_change_executor.md\",\n\t\tprofile: \"iosm\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM change executor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze, implement, and verify changes while preserving IOSM methodology and artifact consistency.\",\n\t\t\t\"\",\n\t\t\t\"Execution policy:\",\n\t\t\t\"- Inspect relevant code and .iosm artifacts before edits.\",\n\t\t\t\"- Make minimal, targeted changes with clear rationale.\",\n\t\t\t\"- Run focused verification after each meaningful change.\",\n\t\t\t\"- Keep IOSM artifacts in sync when behavior/metrics assumptions change.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) What changed and why\",\n\t\t\t\"2) Files changed\",\n\t\t\t\"3) Verification executed and results\",\n\t\t\t\"4) Remaining risks/assumptions\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Do not introduce speculative changes.\",\n\t\t\t\"- If requirements are ambiguous, ask a concise clarification before risky edits.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_postchange_verifier\",\n\t\tdescription: \"Post-change IOSM verifier for metric/artifact integrity and regression checks.\",\n\t\tsourcePath: \"builtin://iosm_postchange_verifier.md\",\n\t\tprofile: \"iosm_verifier\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM post-change verifier.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Validate that implemented changes are correctly reflected in IOSM metrics/artifacts.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Restrict edits to .iosm artifacts unless explicitly instructed otherwise.\",\n\t\t\t\"- Prefer deterministic checks and reproducible commands.\",\n\t\t\t\"- Report mismatches and exact remediation steps.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Checks performed\",\n\t\t\t\"2) Pass/fail per check\",\n\t\t\t\"3) Artifact updates applied (if any)\",\n\t\t\t\"4) Remaining discrepancies and follow-ups\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"qa_test_engineer\",\n\t\tdescription: \"Writes tests, runs verification, and fixes regressions with evidence-driven workflow.\",\n\t\tsourcePath: \"builtin://qa_test_engineer.md\",\n\t\tprofile: \"full\",\n\t\tinstructions: [\n\t\t\t\"You are a QA test engineer and regression fixer.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Increase confidence by adding/updating tests, reproducing failures, and fixing root causes.\",\n\t\t\t\"\",\n\t\t\t\"Workflow:\",\n\t\t\t\"1) Reproduce failure (or define expected behavior if bug is not reproducible yet).\",\n\t\t\t\"2) Add/update focused tests that capture expected behavior.\",\n\t\t\t\"3) Run targeted tests first, then broader suite if needed.\",\n\t\t\t\"4) Implement minimal fix in production code.\",\n\t\t\t\"5) Re-run tests and report outcomes.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Never hide failures by removing assertions or disabling tests unless explicitly requested.\",\n\t\t\t\"- Prefer deterministic tests; avoid flaky timing assumptions.\",\n\t\t\t\"- Keep patch size minimal and localized.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Root cause summary\",\n\t\t\t\"2) Tests added/updated\",\n\t\t\t\"3) Code fixes applied\",\n\t\t\t\"4) Commands executed + pass/fail results\",\n\t\t\t\"5) Residual risk\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"test_failure_triager\",\n\t\tdescription: \"Analyzes failing/flaky tests and proposes a ranked remediation plan.\",\n\t\tsourcePath: \"builtin://test_failure_triager.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a test-failure triage specialist.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze failures quickly and produce a ranked, actionable remediation plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read/analyze only; do not edit files.\",\n\t\t\t\"- Separate infra/environment issues from product-code defects.\",\n\t\t\t\"- Label confidence for each hypothesis.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Failure classification (deterministic, flaky, environment, unknown)\",\n\t\t\t\"2) Ranked hypotheses with evidence\",\n\t\t\t\"3) Minimal next steps to verify each hypothesis\",\n\t\t\t\"4) Recommended owner/agent to execute fixes\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"meta_orchestrator\",\n\t\tdescription: \"Autonomous orchestration lead: audits, plans, and delegates parallel specialists safely.\",\n\t\tsourcePath: \"builtin://meta_orchestrator.md\",\n\t\tprofile: \"meta\",\n\t\t\tinstructions: [\n\t\t\t\t\"You are the main orchestration agent for complex engineering tasks.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Goal:\",\n\t\t\t\t\"- Drive tasks end-to-end with dynamic delegation: audit -> plan -> execution -> verification.\",\n\t\t\t\t\"- Act as the lead orchestrator, not as a substitute for the parent session runtime.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Required operating phases:\",\n\t\t\t\t\"1) Recon: do bounded read-only inspection to identify repository context, constraints, and relevant files.\",\n\t\t\t\t\"2) Plan: split work into an explicit execution graph of tasks/delegates, including dependencies and lock domains where needed.\",\n\t\t\t\t\"3) Execute adaptively: trivial tasks may stay single-agent; medium/complex tasks should maximize safe parallelism via <delegate_task> and multiple focused workstreams.\",\n\t\t\t\t\"4) Verify: for any code or test changes, add/update tests and run targeted verification before closure.\",\n\t\t\t\t\"5) Synthesize: provide integrated results, unresolved risks, and next actions only after all launched delegates are resolved.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Delegation policy:\",\n\t\t\t\t\"- Main emphasis in META orchestration is parallelism: use as many focused agents and delegates as the task can support safely, rather than defaulting to one broad worker.\",\n\t\t\t\t\"- Recon is only preparation; once you can name the workstreams, stop exploring and delegate.\",\n\t\t\t\t\"- For non-trivial work, assume multi-agent parallel fan-out is required unless you can justify why it is not useful.\",\n\t\t\t\t\"- Decide number of delegates based on task complexity (usually 1-10), and prefer higher fan-out when the work naturally splits.\",\n\t\t\t\t\"- For medium/complex work, target aggressive safe parallel fan-out (commonly >=3 delegates) when independent slices exist.\",\n\t\t\t\t\"- If the user asked for N parallel agents, match that fan-out when feasible or explain the exact blocker.\",\n\t\t\t\t\"- If a delegate owns a task that still contains multiple independent slices, that delegate should split again with nested delegates instead of executing everything alone.\",\n\t\t\t\t\"- Run independent read-heavy work in parallel by emitting multiple delegate blocks.\",\n\t\t\t\t\"- For write-capable delegates touching overlapping areas, provide lock_key to avoid edit collisions.\",\n\t\t\t\t\"- Use depends_on to enforce ordering for dependent steps (for example verification after implementation).\",\n\t\t\t\t\"- Use clear description values and focused prompts per delegate.\",\n\t\t\t\t\"- Do not keep doing direct implementation in the orchestrator after recon for non-trivial work; delegate first.\",\n\t\t\t\t\"- Do not collapse the whole implementation into one specialist delegate when multiple independent workstreams exist.\",\n\t\t\t\t\"- If you keep any non-trivial work single-agent or undelegated, include one line: DELEGATION_IMPOSSIBLE: <reason>.\",\n\t\t\t\"\",\n\t\t\t\"Suggested specialist mapping:\",\n\t\t\t\"- architecture/recon -> profile=explore or plan\",\n\t\t\t\"- implementation -> profile=meta or full or iosm\",\n\t\t\t\"- iosm artifact validation -> profile=iosm_verifier\",\n\t\t\t\"- test creation/fixes -> profile=full (or qa_test_engineer when referenced)\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Avoid broad overlapping writes without lock separation.\",\n\t\t\t\"- If requirements are ambiguous and risky, ask for minimal clarification before destructive changes.\",\n\t\t\t\"- Keep all delegated prompts concrete and scoped to specific files/behaviors.\",\n\t\t\t\"- Do not claim completion while any launched delegate remains pending/running.\",\n\t\t\t\"- If no code changed and tests were skipped, include an explicit safety justification.\",\n\t\t\t\"\",\n\t\t\t\"Output requirements:\",\n\t\t\t\"- concise execution summary\",\n\t\t\t\"- delegated work breakdown\",\n\t\t\t\"- verification status\",\n\t\t\t\"- residual risks/assumptions\",\n\t\t].join(\"\\n\"),\n\t},\n];\n\nfunction trimWrappingChars(value: string): string {\n\tlet next = value.trim();\n\tnext = next.replace(/^@+/, \"\");\n\tnext = next.replace(/^[`\"'“”‘’]+/, \"\");\n\tnext = next.replace(/[`\"'“”‘’]+$/, \"\");\n\tnext = next.replace(/[),;:!?]+$/, \"\");\n\treturn next.trim();\n}\n\nfunction pushCandidate(set: Set<string>, value: string): void {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return;\n\tset.add(trimmed);\n}\n\nexport function getSubagentLookupCandidates(reference: string): string[] {\n\tconst cleaned = trimWrappingChars(reference);\n\tif (!cleaned) return [];\n\tconst normalized = cleaned.replace(/\\\\/g, \"/\");\n\tconst lowerNormalized = normalized.toLowerCase();\n\tconst candidates = new Set<string>();\n\n\tpushCandidate(candidates, cleaned);\n\tpushCandidate(candidates, cleaned.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, normalized);\n\tpushCandidate(candidates, normalized.replace(/\\.md$/i, \"\"));\n\n\tconst pathMarkers = [\"/.iosm/agents/\", \".iosm/agents/\", \"/agents/\", \"agents/\"];\n\tfor (const marker of pathMarkers) {\n\t\tconst markerIndex = lowerNormalized.lastIndexOf(marker.toLowerCase());\n\t\tif (markerIndex === -1) continue;\n\t\tconst suffix = normalized.slice(markerIndex + marker.length);\n\t\tpushCandidate(candidates, suffix);\n\t\tpushCandidate(candidates, suffix.replace(/\\.md$/i, \"\"));\n\t}\n\n\tconst baseFromNormalized = normalized.split(\"/\").filter(Boolean).pop() ?? \"\";\n\tconst baseFromPath = basename(cleaned);\n\tpushCandidate(candidates, baseFromNormalized);\n\tpushCandidate(candidates, baseFromNormalized.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, baseFromPath);\n\tpushCandidate(candidates, baseFromPath.replace(/\\.md$/i, \"\"));\n\n\treturn Array.from(candidates);\n}\n\nexport function resolveCustomSubagentReference(\n\treference: string,\n\tagents: ReadonlyArray<Pick<CustomSubagentDefinition, \"name\" | \"sourcePath\">>,\n): string | undefined {\n\tif (agents.length === 0) return undefined;\n\tconst byName = new Map<string, string>();\n\tconst byNameLower = new Map<string, string>();\n\tconst bySourceBaseLower = new Map<string, string>();\n\n\tfor (const agent of agents) {\n\t\tbyName.set(agent.name, agent.name);\n\t\tbyNameLower.set(agent.name.toLowerCase(), agent.name);\n\n\t\tconst sourceBase = basename(agent.sourcePath);\n\t\tif (sourceBase) {\n\t\t\tconst sourceBaseLower = sourceBase.toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseLower, agent.name);\n\t\t\t}\n\t\t\tconst sourceBaseNoMdLower = sourceBase.replace(/\\.md$/i, \"\").toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseNoMdLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseNoMdLower, agent.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const candidate of getSubagentLookupCandidates(reference)) {\n\t\tconst exact = byName.get(candidate);\n\t\tif (exact) return exact;\n\n\t\tconst lower = candidate.toLowerCase();\n\t\tconst byLower = byNameLower.get(lower);\n\t\tif (byLower) return byLower;\n\t\tconst withoutMd = lower.replace(/\\.md$/i, \"\");\n\t\tconst byWithoutMd = byNameLower.get(withoutMd);\n\t\tif (byWithoutMd) return byWithoutMd;\n\n\t\tconst byBase = bySourceBaseLower.get(lower) ?? bySourceBaseLower.get(withoutMd);\n\t\tif (byBase) return byBase;\n\t}\n\n\treturn undefined;\n}\n\ntype ParsedFrontmatter = {\n\tname?: unknown;\n\tdescription?: unknown;\n\tprofile?: unknown;\n\ttools?: unknown;\n\tdisallowed_tools?: unknown;\n\tsystem_prompt?: unknown;\n\tcwd?: unknown;\n\tmodel?: unknown;\n\tbackground?: unknown;\n};\n\nfunction readMarkdownFilesRecursive(root: string): string[] {\n\tif (!existsSync(root)) return [];\n\tconst files: string[] = [];\n\tconst walk = (dir: string): void => {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true }).sort((left, right) =>\n\t\t\tleft.name.localeCompare(right.name),\n\t\t);\n\t\tfor (const entry of entries) {\n\t\t\tconst full = join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\twalk(full);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.isFile() && entry.name.toLowerCase().endsWith(\".md\")) {\n\t\t\t\tfiles.push(full);\n\t\t\t}\n\t\t}\n\t};\n\twalk(root);\n\treturn files;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (Array.isArray(value)) {\n\t\tconst normalized = value.map((item) => String(item).trim()).filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value\n\t\t\t.split(\",\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\treturn undefined;\n}\n\nfunction parseSubagentFile(filePath: string, cwd: string): { agent?: CustomSubagentDefinition; diagnostic?: SubagentDiagnostic } {\n\tlet content: string;\n\ttry {\n\t\tcontent = readFileSync(filePath, \"utf8\");\n\t} catch (error) {\n\t\treturn {\n\t\t\tdiagnostic: { path: filePath, message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}` },\n\t\t};\n\t}\n\n\tconst { frontmatter, body } = parseFrontmatter<ParsedFrontmatter>(content);\n\tconst nameRaw = typeof frontmatter.name === \"string\" ? frontmatter.name.trim() : \"\";\n\tconst defaultName = filePath.split(\"/\").pop()?.replace(/\\.md$/i, \"\") ?? \"subagent\";\n\tconst name = (nameRaw || defaultName).trim();\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tconst profileRaw = typeof frontmatter.profile === \"string\" ? frontmatter.profile.trim() : \"\";\n\tif (profileRaw.length > 0 && !isValidProfileName(profileRaw.toLowerCase())) {\n\t\treturn {\n\t\t\tdiagnostic: {\n\t\t\t\tpath: filePath,\n\t\t\t\tmessage: `Invalid profile \"${profileRaw}\". Valid profiles: explore, plan, iosm, iosm_analyst, iosm_verifier, cycle_planner, meta, full.`,\n\t\t\t},\n\t\t};\n\t}\n\tconst profile =\n\t\tprofileRaw.length > 0 ? (profileRaw.toLowerCase() as AgentProfileName) : undefined;\n\tconst tools = asStringArray(frontmatter.tools);\n\tconst disallowedTools = asStringArray(frontmatter.disallowed_tools);\n\tconst systemPrompt =\n\t\ttypeof frontmatter.system_prompt === \"string\" && frontmatter.system_prompt.trim().length > 0\n\t\t\t? frontmatter.system_prompt.trim()\n\t\t\t: undefined;\n\tconst configuredCwd =\n\t\ttypeof frontmatter.cwd === \"string\" && frontmatter.cwd.trim().length > 0\n\t\t\t? resolve(cwd, frontmatter.cwd.trim())\n\t\t\t: undefined;\n\n\tif (configuredCwd) {\n\t\ttry {\n\t\t\tif (!existsSync(configuredCwd) || !statSync(configuredCwd).isDirectory()) {\n\t\t\t\treturn { diagnostic: { path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` } };\n\t\t\t}\n\t\t} catch {\n\t\t\treturn { diagnostic: { path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` } };\n\t\t}\n\t}\n\n\tconst instructions = body.trim();\n\tif (!instructions) {\n\t\treturn { diagnostic: { path: filePath, message: \"Subagent instructions are empty.\" } };\n\t}\n\n\treturn {\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription: description || `Custom subagent ${name}`,\n\t\t\tsourcePath: filePath,\n\t\t\tprofile,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tsystemPrompt,\n\t\t\tinstructions,\n\t\t\tcwd: configuredCwd,\n\t\t\tmodel: typeof frontmatter.model === \"string\" ? frontmatter.model.trim() : undefined,\n\t\t\tbackground: frontmatter.background === true,\n\t\t},\n\t};\n}\n\nexport function loadCustomSubagents(options: { cwd: string; agentDir: string }): LoadCustomSubagentsResult {\n\tconst roots: Array<{ path: string; scope: CustomSubagentSourceScope; priority: number }> = [\n\t\t{ path: join(options.agentDir, \"agents\"), scope: \"global\", priority: 0 },\n\t\t{ path: join(options.cwd, \".iosm\", \"agents\"), scope: \"project\", priority: 1 },\n\t];\n\tconst diagnostics: SubagentDiagnostic[] = [];\n\tconst overrides: SubagentOverrideInfo[] = [];\n\tconst allAgents: CustomSubagentEntry[] = [];\n\tconst byName = new Map<string, CustomSubagentEntry>();\n\n\tconst registerEntry = (entry: CustomSubagentEntry): void => {\n\t\tconst existing = byName.get(entry.name);\n\t\tif (!existing) {\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\tallAgents.push(entry);\n\t\t\treturn;\n\t\t}\n\n\t\tconst shouldReplace =\n\t\t\tentry.sourcePriority > existing.sourcePriority ||\n\t\t\t(entry.sourcePriority === existing.sourcePriority &&\n\t\t\t\tentry.sourcePath.localeCompare(existing.sourcePath) > 0);\n\n\t\tif (entry.sourcePriority === existing.sourcePriority) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: entry.sourcePath,\n\t\t\t\tmessage: `Duplicate agent \"${entry.name}\" in ${entry.sourceScope} scope; ${\n\t\t\t\t\tshouldReplace ? \"this file takes precedence\" : \"existing file keeps precedence\"\n\t\t\t\t}.`,\n\t\t\t});\n\t\t}\n\n\t\tif (shouldReplace) {\n\t\t\texisting.effective = false;\n\t\t\texisting.overriddenByPath = entry.sourcePath;\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: entry.sourcePath,\n\t\t\t\twinnerScope: entry.sourceScope,\n\t\t\t\toverriddenPath: existing.sourcePath,\n\t\t\t\toverriddenScope: existing.sourceScope,\n\t\t\t});\n\t\t} else {\n\t\t\tentry.overriddenByPath = existing.sourcePath;\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: existing.sourcePath,\n\t\t\t\twinnerScope: existing.sourceScope,\n\t\t\t\toverriddenPath: entry.sourcePath,\n\t\t\t\toverriddenScope: entry.sourceScope,\n\t\t\t});\n\t\t}\n\n\t\tallAgents.push(entry);\n\t};\n\n\tfor (const builtin of BUILTIN_SUBAGENTS) {\n\t\tregisterEntry({\n\t\t\t...builtin,\n\t\t\tsourceScope: \"builtin\",\n\t\t\tsourcePriority: BUILTIN_SUBAGENT_PRIORITY,\n\t\t\teffective: false,\n\t\t});\n\t}\n\n\tfor (const root of roots) {\n\t\tfor (const file of readMarkdownFilesRecursive(root.path)) {\n\t\t\tconst parsed = parseSubagentFile(file, options.cwd);\n\t\t\tif (parsed.diagnostic) {\n\t\t\t\tdiagnostics.push(parsed.diagnostic);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!parsed.agent) continue;\n\t\t\tconst entry: CustomSubagentEntry = {\n\t\t\t\t...parsed.agent,\n\t\t\t\tsourceScope: root.scope,\n\t\t\t\tsourcePriority: root.priority,\n\t\t\t\teffective: false,\n\t\t\t};\n\t\t\tregisterEntry(entry);\n\t\t}\n\t}\n\n\tconst agents = Array.from(byName.values()).sort((left, right) => left.name.localeCompare(right.name));\n\tallAgents.sort((left, right) => {\n\t\tconst nameCompare = left.name.localeCompare(right.name);\n\t\tif (nameCompare !== 0) return nameCompare;\n\t\treturn right.sourcePriority - left.sourcePriority;\n\t});\n\treturn { agents, allAgents, overrides, diagnostics };\n}\n"]}
1
+ {"version":3,"file":"subagents.js","sourceRoot":"","sources":["../../src/core/subagents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,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,KAAK;aAChB,CAAC;YACF,aAAa,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACF,CAAC;IAED,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IACtG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QAC9B,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxD,IAAI,WAAW,KAAK,CAAC;YAAE,OAAO,WAAW,CAAC;QAC1C,OAAO,KAAK,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IACnD,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport { AGENT_PROFILES, isValidProfileName, type AgentProfileName } from \"./agent-profiles.js\";\n\nexport type CustomSubagentSourceScope = \"builtin\" | \"global\" | \"project\";\n\nexport interface CustomSubagentDefinition {\n\tname: string;\n\tdescription: string;\n\tsourcePath: string;\n\tprofile?: AgentProfileName;\n\ttools?: string[];\n\tdisallowedTools?: string[];\n\tsystemPrompt?: string;\n\tinstructions: string;\n\tcwd?: string;\n\tmodel?: string;\n\tbackground?: boolean;\n}\n\nexport interface CustomSubagentEntry extends CustomSubagentDefinition {\n\tsourceScope: CustomSubagentSourceScope;\n\tsourcePriority: number;\n\teffective: boolean;\n\toverriddenByPath?: string;\n}\n\nexport interface SubagentOverrideInfo {\n\tname: string;\n\twinnerPath: string;\n\twinnerScope: CustomSubagentSourceScope;\n\toverriddenPath: string;\n\toverriddenScope: CustomSubagentSourceScope;\n}\n\nexport interface SubagentDiagnostic {\n\tpath: string;\n\tmessage: string;\n}\n\nexport interface LoadCustomSubagentsResult {\n\tagents: CustomSubagentEntry[];\n\tallAgents: CustomSubagentEntry[];\n\toverrides: SubagentOverrideInfo[];\n\tdiagnostics: SubagentDiagnostic[];\n}\n\nconst BUILTIN_SUBAGENT_PRIORITY = -1;\n\nconst BUILTIN_SUBAGENTS: CustomSubagentDefinition[] = [\n\t{\n\t\tname: \"codebase_auditor\",\n\t\tdescription: \"Structured codebase audit for architecture, reliability, security, and test gaps.\",\n\t\tsourcePath: \"builtin://codebase_auditor.md\",\n\t\tprofile: \"explore\",\n\t\tinstructions: [\n\t\t\t\"You are a codebase auditor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Produce an evidence-based audit of architecture, defect risks, and maintainability hotspots.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read-only operation. Never edit files.\",\n\t\t\t\"- Make claims only with direct repository evidence.\",\n\t\t\t\"- Prioritize by user impact and likelihood (P0..P3).\",\n\t\t\t\"- If the assigned audit still spans multiple independent subsystems and delegation protocol is available, split it with nested delegates instead of producing one monolithic audit.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Findings (ordered by severity)\",\n\t\t\t\"2) Open questions/unknowns\",\n\t\t\t\"3) Recommended next actions\",\n\t\t\t\"\",\n\t\t\t\"For each finding include:\",\n\t\t\t\"- file path + line reference (when available)\",\n\t\t\t\"- risk/impact\",\n\t\t\t\"- concrete fix direction\",\n\t\t\t\"\",\n\t\t\t\"If no issues are found, explicitly state 'No findings' and list residual risks/testing gaps.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"system_error_analyst\",\n\t\tdescription: \"Diagnoses system/runtime failures and produces root-cause + fix plan.\",\n\t\tsourcePath: \"builtin://system_error_analyst.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a system error analyst.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Triage failures, identify probable root cause, and propose a minimal, testable fix plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Do not modify files.\",\n\t\t\t\"- Use deterministic evidence (logs, stack traces, tests, configs).\",\n\t\t\t\"- Distinguish facts vs hypotheses explicitly.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Incident summary\",\n\t\t\t\"2) Root-cause analysis (ranked hypotheses with evidence)\",\n\t\t\t\"3) Minimal patch plan\",\n\t\t\t\"4) Verification plan (commands + expected signals)\",\n\t\t\t\"5) Regression risks\",\n\t\t\t\"\",\n\t\t\t\"Escalation guidance:\",\n\t\t\t\"- If data is insufficient, request the minimum missing evidence instead of guessing.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_change_executor\",\n\t\tdescription: \"Implements repository changes under IOSM methodology and keeps artifacts aligned.\",\n\t\tsourcePath: \"builtin://iosm_change_executor.md\",\n\t\tprofile: \"iosm\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM change executor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze, implement, and verify changes while preserving IOSM methodology and artifact consistency.\",\n\t\t\t\"\",\n\t\t\t\"Execution policy:\",\n\t\t\t\"- Inspect relevant code and .iosm artifacts before edits.\",\n\t\t\t\"- Make minimal, targeted changes with clear rationale.\",\n\t\t\t\"- Run focused verification after each meaningful change.\",\n\t\t\t\"- Keep IOSM artifacts in sync when behavior/metrics assumptions change.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) What changed and why\",\n\t\t\t\"2) Files changed\",\n\t\t\t\"3) Verification executed and results\",\n\t\t\t\"4) Remaining risks/assumptions\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Do not introduce speculative changes.\",\n\t\t\t\"- If requirements are ambiguous, ask a concise clarification before risky edits.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_postchange_verifier\",\n\t\tdescription: \"Post-change IOSM verifier for metric/artifact integrity and regression checks.\",\n\t\tsourcePath: \"builtin://iosm_postchange_verifier.md\",\n\t\tprofile: \"iosm_verifier\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM post-change verifier.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Validate that implemented changes are correctly reflected in IOSM metrics/artifacts.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Restrict edits to .iosm artifacts unless explicitly instructed otherwise.\",\n\t\t\t\"- Prefer deterministic checks and reproducible commands.\",\n\t\t\t\"- Report mismatches and exact remediation steps.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Checks performed\",\n\t\t\t\"2) Pass/fail per check\",\n\t\t\t\"3) Artifact updates applied (if any)\",\n\t\t\t\"4) Remaining discrepancies and follow-ups\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"qa_test_engineer\",\n\t\tdescription: \"Writes tests, runs verification, and fixes regressions with evidence-driven workflow.\",\n\t\tsourcePath: \"builtin://qa_test_engineer.md\",\n\t\tprofile: \"full\",\n\t\tinstructions: [\n\t\t\t\"You are a QA test engineer and regression fixer.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Increase confidence by adding/updating tests, reproducing failures, and fixing root causes.\",\n\t\t\t\"\",\n\t\t\t\"Workflow:\",\n\t\t\t\"1) Reproduce failure (or define expected behavior if bug is not reproducible yet).\",\n\t\t\t\"2) Add/update focused tests that capture expected behavior.\",\n\t\t\t\"3) Run targeted tests first, then broader suite if needed.\",\n\t\t\t\"4) Implement minimal fix in production code.\",\n\t\t\t\"5) Re-run tests and report outcomes.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Never hide failures by removing assertions or disabling tests unless explicitly requested.\",\n\t\t\t\"- Prefer deterministic tests; avoid flaky timing assumptions.\",\n\t\t\t\"- Keep patch size minimal and localized.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Root cause summary\",\n\t\t\t\"2) Tests added/updated\",\n\t\t\t\"3) Code fixes applied\",\n\t\t\t\"4) Commands executed + pass/fail results\",\n\t\t\t\"5) Residual risk\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"test_failure_triager\",\n\t\tdescription: \"Analyzes failing/flaky tests and proposes a ranked remediation plan.\",\n\t\tsourcePath: \"builtin://test_failure_triager.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a test-failure triage specialist.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze failures quickly and produce a ranked, actionable remediation plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read/analyze only; do not edit files.\",\n\t\t\t\"- Separate infra/environment issues from product-code defects.\",\n\t\t\t\"- Label confidence for each hypothesis.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Failure classification (deterministic, flaky, environment, unknown)\",\n\t\t\t\"2) Ranked hypotheses with evidence\",\n\t\t\t\"3) Minimal next steps to verify each hypothesis\",\n\t\t\t\"4) Recommended owner/agent to execute fixes\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"meta_orchestrator\",\n\t\tdescription: \"Autonomous orchestration lead: audits, plans, and delegates parallel specialists safely.\",\n\t\tsourcePath: \"builtin://meta_orchestrator.md\",\n\t\tprofile: \"meta\",\n\t\t\tinstructions: [\n\t\t\t\t\"You are the main orchestration agent for complex engineering tasks.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Goal:\",\n\t\t\t\t\"- Drive tasks end-to-end with dynamic delegation: audit -> plan -> execution -> verification.\",\n\t\t\t\t\"- Act as the lead orchestrator, not as a substitute for the parent session runtime.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Required operating phases:\",\n\t\t\t\t\"1) Recon: do bounded read-only inspection to identify repository context, constraints, and relevant files.\",\n\t\t\t\t\"2) Plan: split work into an explicit execution graph of tasks/delegates, including dependencies and lock domains where needed.\",\n\t\t\t\t\"3) Execute adaptively: trivial tasks may stay single-agent; medium/complex tasks should maximize safe parallelism via <delegate_task> and multiple focused workstreams.\",\n\t\t\t\t\"4) Verify: for any code or test changes, add/update tests and run targeted verification before closure.\",\n\t\t\t\t\"5) Synthesize: provide integrated results, unresolved risks, and next actions only after all launched delegates are resolved.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Delegation policy:\",\n\t\t\t\t\"- Main emphasis in META orchestration is parallelism: use as many focused agents and delegates as the task can support safely, rather than defaulting to one broad worker.\",\n\t\t\t\t\"- Recon is only preparation; once you can name the workstreams, stop exploring and delegate.\",\n\t\t\t\t\"- For non-trivial work, assume multi-agent parallel fan-out is required unless you can justify why it is not useful.\",\n\t\t\t\t\"- Decide number of delegates based on task complexity (usually 1-10), and prefer higher fan-out when the work naturally splits.\",\n\t\t\t\t\"- For medium/complex work, target aggressive safe parallel fan-out (commonly >=3 delegates) when independent slices exist.\",\n\t\t\t\t\"- If the user asked for N parallel agents, match that fan-out when feasible or explain the exact blocker.\",\n\t\t\t\t\"- If a delegate owns a task that still contains multiple independent slices, that delegate should split again with nested delegates instead of executing everything alone.\",\n\t\t\t\t\"- Run independent read-heavy work in parallel by emitting multiple delegate blocks.\",\n\t\t\t\t\"- For write-capable delegates touching overlapping areas, provide lock_key to avoid edit collisions.\",\n\t\t\t\t\"- Use depends_on to enforce ordering for dependent steps (for example verification after implementation).\",\n\t\t\t\t\"- Use clear description values and focused prompts per delegate.\",\n\t\t\t\t\"- Do not keep doing direct implementation in the orchestrator after recon for non-trivial work; delegate first.\",\n\t\t\t\t\"- Do not collapse the whole implementation into one specialist delegate when multiple independent workstreams exist.\",\n\t\t\t\t\"- If you keep any non-trivial work single-agent or undelegated, include one line: DELEGATION_IMPOSSIBLE: <reason>.\",\n\t\t\t\"\",\n\t\t\t\"Suggested specialist mapping:\",\n\t\t\t\"- architecture/recon -> profile=explore or plan\",\n\t\t\t\"- implementation -> profile=meta or full or iosm\",\n\t\t\t\"- iosm artifact validation -> profile=iosm_verifier\",\n\t\t\t\"- test creation/fixes -> profile=full (or qa_test_engineer when referenced)\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Avoid broad overlapping writes without lock separation.\",\n\t\t\t\"- If requirements are ambiguous and risky, ask for minimal clarification before destructive changes.\",\n\t\t\t\"- Keep all delegated prompts concrete and scoped to specific files/behaviors.\",\n\t\t\t\"- Do not claim completion while any launched delegate remains pending/running.\",\n\t\t\t\"- If no code changed and tests were skipped, include an explicit safety justification.\",\n\t\t\t\"\",\n\t\t\t\"Output requirements:\",\n\t\t\t\"- concise execution summary\",\n\t\t\t\"- delegated work breakdown\",\n\t\t\t\"- verification status\",\n\t\t\t\"- residual risks/assumptions\",\n\t\t].join(\"\\n\"),\n\t},\n];\n\nconst EXTRA_KNOWN_TOOLS = [\"task\", \"todo_write\", \"todo_read\", \"ask_user\", \"git_read\"];\n\nexport function normalizeToolName(value: string): string {\n\treturn value.trim().toLowerCase().replace(/-/g, \"_\");\n}\n\nexport function getDefaultKnownToolNames(): string[] {\n\tconst fromProfiles = Object.values(AGENT_PROFILES).flatMap((profile) => profile.tools);\n\treturn Array.from(\n\t\tnew Set([...fromProfiles, ...EXTRA_KNOWN_TOOLS].map((name) => normalizeToolName(name)).filter(Boolean)),\n\t).sort((left, right) => left.localeCompare(right));\n}\n\nexport function normalizeAndFilterToolNames(\n\tvalues: readonly string[] | undefined,\n\tknownToolNames?: ReadonlySet<string>,\n): { normalized: string[]; unknown: string[] } {\n\tif (!values || values.length === 0) {\n\t\treturn { normalized: [], unknown: [] };\n\t}\n\n\tconst seen = new Set<string>();\n\tconst normalized: string[] = [];\n\tconst unknown: string[] = [];\n\tfor (const value of values) {\n\t\tconst next = normalizeToolName(value);\n\t\tif (!next || seen.has(next)) continue;\n\t\tseen.add(next);\n\t\tif (knownToolNames && knownToolNames.size > 0 && !knownToolNames.has(next)) {\n\t\t\tunknown.push(next);\n\t\t\tcontinue;\n\t\t}\n\t\tnormalized.push(next);\n\t}\n\treturn { normalized, unknown };\n}\n\nfunction trimWrappingChars(value: string): string {\n\tlet next = value.trim();\n\tnext = next.replace(/^@+/, \"\");\n\tnext = next.replace(/^[`\"'“”‘’]+/, \"\");\n\tnext = next.replace(/[`\"'“”‘’]+$/, \"\");\n\tnext = next.replace(/[),;:!?]+$/, \"\");\n\treturn next.trim();\n}\n\nfunction pushCandidate(set: Set<string>, value: string): void {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return;\n\tset.add(trimmed);\n}\n\nexport function getSubagentLookupCandidates(reference: string): string[] {\n\tconst cleaned = trimWrappingChars(reference);\n\tif (!cleaned) return [];\n\tconst normalized = cleaned.replace(/\\\\/g, \"/\");\n\tconst lowerNormalized = normalized.toLowerCase();\n\tconst candidates = new Set<string>();\n\n\tpushCandidate(candidates, cleaned);\n\tpushCandidate(candidates, cleaned.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, normalized);\n\tpushCandidate(candidates, normalized.replace(/\\.md$/i, \"\"));\n\n\tconst pathMarkers = [\"/.iosm/agents/\", \".iosm/agents/\", \"/agents/\", \"agents/\"];\n\tfor (const marker of pathMarkers) {\n\t\tconst markerIndex = lowerNormalized.lastIndexOf(marker.toLowerCase());\n\t\tif (markerIndex === -1) continue;\n\t\tconst suffix = normalized.slice(markerIndex + marker.length);\n\t\tpushCandidate(candidates, suffix);\n\t\tpushCandidate(candidates, suffix.replace(/\\.md$/i, \"\"));\n\t}\n\n\tconst baseFromNormalized = normalized.split(\"/\").filter(Boolean).pop() ?? \"\";\n\tconst baseFromPath = basename(cleaned);\n\tpushCandidate(candidates, baseFromNormalized);\n\tpushCandidate(candidates, baseFromNormalized.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, baseFromPath);\n\tpushCandidate(candidates, baseFromPath.replace(/\\.md$/i, \"\"));\n\n\treturn Array.from(candidates);\n}\n\nexport function resolveCustomSubagentReference(\n\treference: string,\n\tagents: ReadonlyArray<Pick<CustomSubagentDefinition, \"name\" | \"sourcePath\">>,\n): string | undefined {\n\tif (agents.length === 0) return undefined;\n\tconst byName = new Map<string, string>();\n\tconst byNameLower = new Map<string, string>();\n\tconst bySourceBaseLower = new Map<string, string>();\n\n\tfor (const agent of agents) {\n\t\tbyName.set(agent.name, agent.name);\n\t\tbyNameLower.set(agent.name.toLowerCase(), agent.name);\n\n\t\tconst sourceBase = basename(agent.sourcePath);\n\t\tif (sourceBase) {\n\t\t\tconst sourceBaseLower = sourceBase.toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseLower, agent.name);\n\t\t\t}\n\t\t\tconst sourceBaseNoMdLower = sourceBase.replace(/\\.md$/i, \"\").toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseNoMdLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseNoMdLower, agent.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const candidate of getSubagentLookupCandidates(reference)) {\n\t\tconst exact = byName.get(candidate);\n\t\tif (exact) return exact;\n\n\t\tconst lower = candidate.toLowerCase();\n\t\tconst byLower = byNameLower.get(lower);\n\t\tif (byLower) return byLower;\n\t\tconst withoutMd = lower.replace(/\\.md$/i, \"\");\n\t\tconst byWithoutMd = byNameLower.get(withoutMd);\n\t\tif (byWithoutMd) return byWithoutMd;\n\n\t\tconst byBase = bySourceBaseLower.get(lower) ?? bySourceBaseLower.get(withoutMd);\n\t\tif (byBase) return byBase;\n\t}\n\n\treturn undefined;\n}\n\ntype ParsedFrontmatter = {\n\tname?: unknown;\n\tdescription?: unknown;\n\tprofile?: unknown;\n\ttools?: unknown;\n\tdisallowed_tools?: unknown;\n\tsystem_prompt?: unknown;\n\tcwd?: unknown;\n\tmodel?: unknown;\n\tbackground?: unknown;\n};\n\nfunction readMarkdownFilesRecursive(root: string): string[] {\n\tif (!existsSync(root)) return [];\n\tconst files: string[] = [];\n\tconst walk = (dir: string): void => {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true }).sort((left, right) =>\n\t\t\tleft.name.localeCompare(right.name),\n\t\t);\n\t\tfor (const entry of entries) {\n\t\t\tconst full = join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\twalk(full);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.isFile() && entry.name.toLowerCase().endsWith(\".md\")) {\n\t\t\t\tfiles.push(full);\n\t\t\t}\n\t\t}\n\t};\n\twalk(root);\n\treturn files;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (Array.isArray(value)) {\n\t\tconst normalized = value.map((item) => String(item).trim()).filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value\n\t\t\t.split(\",\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\treturn undefined;\n}\n\nfunction parseSubagentFile(\n\tfilePath: string,\n\tcwd: string,\n\tknownToolNames: ReadonlySet<string>,\n): { agent?: CustomSubagentDefinition; diagnostics: SubagentDiagnostic[] } {\n\tconst diagnostics: SubagentDiagnostic[] = [];\n\tlet content: string;\n\ttry {\n\t\tcontent = readFileSync(filePath, \"utf8\");\n\t} catch (error) {\n\t\treturn {\n\t\t\tdiagnostics: [\n\t\t\t\t{ path: filePath, message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}` },\n\t\t\t],\n\t\t};\n\t}\n\n\tconst { frontmatter, body } = parseFrontmatter<ParsedFrontmatter>(content);\n\tconst nameRaw = typeof frontmatter.name === \"string\" ? frontmatter.name.trim() : \"\";\n\tconst defaultName = filePath.split(\"/\").pop()?.replace(/\\.md$/i, \"\") ?? \"subagent\";\n\tconst name = (nameRaw || defaultName).trim();\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tconst profileRaw = typeof frontmatter.profile === \"string\" ? frontmatter.profile.trim() : \"\";\n\tif (profileRaw.length > 0 && !isValidProfileName(profileRaw.toLowerCase())) {\n\t\treturn {\n\t\t\tdiagnostics: [\n\t\t\t\t{\n\t\t\t\t\tpath: filePath,\n\t\t\t\t\tmessage: `Invalid profile \"${profileRaw}\". Valid profiles: explore, plan, iosm, iosm_analyst, iosm_verifier, cycle_planner, meta, full.`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst profile =\n\t\tprofileRaw.length > 0 ? (profileRaw.toLowerCase() as AgentProfileName) : undefined;\n\tconst parsedTools = normalizeAndFilterToolNames(asStringArray(frontmatter.tools), knownToolNames);\n\tconst parsedDisallowedTools = normalizeAndFilterToolNames(asStringArray(frontmatter.disallowed_tools), knownToolNames);\n\tif (parsedTools.unknown.length > 0) {\n\t\tdiagnostics.push({\n\t\t\tpath: filePath,\n\t\t\tmessage: `Unknown tools were removed from \"tools\": ${parsedTools.unknown.join(\", \")}.`,\n\t\t});\n\t}\n\tif (parsedDisallowedTools.unknown.length > 0) {\n\t\tdiagnostics.push({\n\t\t\tpath: filePath,\n\t\t\tmessage: `Unknown tools were removed from \"disallowed_tools\": ${parsedDisallowedTools.unknown.join(\", \")}.`,\n\t\t});\n\t}\n\tconst tools = parsedTools.normalized.length > 0 ? parsedTools.normalized : undefined;\n\tconst disallowedTools = parsedDisallowedTools.normalized.length > 0 ? parsedDisallowedTools.normalized : undefined;\n\tconst systemPrompt =\n\t\ttypeof frontmatter.system_prompt === \"string\" && frontmatter.system_prompt.trim().length > 0\n\t\t\t? frontmatter.system_prompt.trim()\n\t\t\t: undefined;\n\tconst configuredCwd =\n\t\ttypeof frontmatter.cwd === \"string\" && frontmatter.cwd.trim().length > 0\n\t\t\t? resolve(cwd, frontmatter.cwd.trim())\n\t\t\t: undefined;\n\n\tif (configuredCwd) {\n\t\ttry {\n\t\t\tif (!existsSync(configuredCwd) || !statSync(configuredCwd).isDirectory()) {\n\t\t\t\treturn { diagnostics: [{ path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` }] };\n\t\t\t}\n\t\t} catch {\n\t\t\treturn { diagnostics: [{ path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` }] };\n\t\t}\n\t}\n\n\tconst instructions = body.trim();\n\tif (!instructions) {\n\t\treturn { diagnostics: [{ path: filePath, message: \"Subagent instructions are empty.\" }] };\n\t}\n\n\treturn {\n\t\tdiagnostics,\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription: description || `Custom subagent ${name}`,\n\t\t\tsourcePath: filePath,\n\t\t\tprofile,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tsystemPrompt,\n\t\t\tinstructions,\n\t\t\tcwd: configuredCwd,\n\t\t\tmodel: typeof frontmatter.model === \"string\" ? frontmatter.model.trim() : undefined,\n\t\t\tbackground: frontmatter.background === true,\n\t\t},\n\t};\n}\n\nexport interface LoadCustomSubagentsOptions {\n\tcwd: string;\n\tagentDir: string;\n\tknownToolNames?: string[];\n}\n\nexport function loadCustomSubagents(options: LoadCustomSubagentsOptions): LoadCustomSubagentsResult {\n\tconst roots: Array<{ path: string; scope: CustomSubagentSourceScope; priority: number }> = [\n\t\t{ path: join(options.agentDir, \"agents\"), scope: \"global\", priority: 0 },\n\t\t{ path: join(options.cwd, \".iosm\", \"agents\"), scope: \"project\", priority: 1 },\n\t];\n\tconst normalizedKnownToolNames = new Set(\n\t\t(options.knownToolNames && options.knownToolNames.length > 0 ? options.knownToolNames : getDefaultKnownToolNames())\n\t\t\t.map((name) => normalizeToolName(name))\n\t\t\t.filter(Boolean),\n\t);\n\tconst diagnostics: SubagentDiagnostic[] = [];\n\tconst overrides: SubagentOverrideInfo[] = [];\n\tconst allAgents: CustomSubagentEntry[] = [];\n\tconst byName = new Map<string, CustomSubagentEntry>();\n\n\tconst registerEntry = (entry: CustomSubagentEntry): void => {\n\t\tconst existing = byName.get(entry.name);\n\t\tif (!existing) {\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\tallAgents.push(entry);\n\t\t\treturn;\n\t\t}\n\n\t\tconst shouldReplace =\n\t\t\tentry.sourcePriority > existing.sourcePriority ||\n\t\t\t(entry.sourcePriority === existing.sourcePriority &&\n\t\t\t\tentry.sourcePath.localeCompare(existing.sourcePath) > 0);\n\n\t\tif (entry.sourcePriority === existing.sourcePriority) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: entry.sourcePath,\n\t\t\t\tmessage: `Duplicate agent \"${entry.name}\" in ${entry.sourceScope} scope; ${\n\t\t\t\t\tshouldReplace ? \"this file takes precedence\" : \"existing file keeps precedence\"\n\t\t\t\t}.`,\n\t\t\t});\n\t\t}\n\n\t\tif (shouldReplace) {\n\t\t\texisting.effective = false;\n\t\t\texisting.overriddenByPath = entry.sourcePath;\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: entry.sourcePath,\n\t\t\t\twinnerScope: entry.sourceScope,\n\t\t\t\toverriddenPath: existing.sourcePath,\n\t\t\t\toverriddenScope: existing.sourceScope,\n\t\t\t});\n\t\t} else {\n\t\t\tentry.overriddenByPath = existing.sourcePath;\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: existing.sourcePath,\n\t\t\t\twinnerScope: existing.sourceScope,\n\t\t\t\toverriddenPath: entry.sourcePath,\n\t\t\t\toverriddenScope: entry.sourceScope,\n\t\t\t});\n\t\t}\n\n\t\tallAgents.push(entry);\n\t};\n\n\tfor (const builtin of BUILTIN_SUBAGENTS) {\n\t\tregisterEntry({\n\t\t\t...builtin,\n\t\t\tsourceScope: \"builtin\",\n\t\t\tsourcePriority: BUILTIN_SUBAGENT_PRIORITY,\n\t\t\teffective: false,\n\t\t});\n\t}\n\n\tfor (const root of roots) {\n\t\tfor (const file of readMarkdownFilesRecursive(root.path)) {\n\t\t\tconst parsed = parseSubagentFile(file, options.cwd, normalizedKnownToolNames);\n\t\t\tif (parsed.diagnostics.length > 0) diagnostics.push(...parsed.diagnostics);\n\t\t\tif (!parsed.agent) continue;\n\t\t\tconst entry: CustomSubagentEntry = {\n\t\t\t\t...parsed.agent,\n\t\t\t\tsourceScope: root.scope,\n\t\t\t\tsourcePriority: root.priority,\n\t\t\t\teffective: false,\n\t\t\t};\n\t\t\tregisterEntry(entry);\n\t\t}\n\t}\n\n\tconst agents = Array.from(byName.values()).sort((left, right) => left.name.localeCompare(right.name));\n\tallAgents.sort((left, right) => {\n\t\tconst nameCompare = left.name.localeCompare(right.name);\n\t\tif (nameCompare !== 0) return nameCompare;\n\t\treturn right.sourcePriority - left.sourcePriority;\n\t});\n\treturn { agents, allAgents, overrides, diagnostics };\n}\n"]}
@@ -2,6 +2,22 @@
2
2
  * System prompt construction and project context loading
3
3
  */
4
4
  import { type Skill } from "./skills.js";
5
+ export interface PromptContextProcessingOptions {
6
+ enableContextDedupe?: boolean;
7
+ maxContextCharsPerFile?: number;
8
+ maxTotalContextChars?: number;
9
+ enableGitSnapshotContext?: boolean;
10
+ }
11
+ export interface PromptContextStats {
12
+ contextBeforeChars: number;
13
+ contextAfterChars: number;
14
+ dedupeHits: number;
15
+ truncatedFiles: string[];
16
+ droppedFiles: number;
17
+ totalFiles: number;
18
+ includedFiles: number;
19
+ gitSnapshotIncluded: boolean;
20
+ }
5
21
  export interface BuildSystemPromptOptions {
6
22
  /** Custom system prompt (replaces default). */
7
23
  customPrompt?: string;
@@ -20,6 +36,15 @@ export interface BuildSystemPromptOptions {
20
36
  path: string;
21
37
  content: string;
22
38
  }>;
39
+ /** Optional git snapshot context block (plumbing; included only when enabled via contextProcessing). */
40
+ gitSnapshotContext?: {
41
+ path?: string;
42
+ content: string;
43
+ };
44
+ /** Context processing controls (dedupe + budgets). */
45
+ contextProcessing?: PromptContextProcessingOptions;
46
+ /** Optional callback for context processing diagnostics/tracing. */
47
+ onContextProcessed?: (stats: PromptContextStats) => void;
23
48
  /** Pre-loaded skills. */
24
49
  skills?: Skill[];
25
50
  }
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AA2ChE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;CACjB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAsahF"}
1
+ {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAKhE,MAAM,WAAW,8BAA8B;IAC9C,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9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;CACjB;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAwahF"}
@@ -1,12 +1,147 @@
1
1
  /**
2
2
  * System prompt construction and project context loading
3
3
  */
4
+ import { createHash } from "node:crypto";
4
5
  import { getDocsPath, getExamplesPath, getReadmePath } from "../config.js";
5
6
  import { formatSkillsForPrompt } from "./skills.js";
7
+ const DEFAULT_CONTEXT_MAX_CHARS_PER_FILE = 4000;
8
+ const DEFAULT_CONTEXT_MAX_TOTAL_CHARS = 12000;
9
+ function normalizeContextContent(content) {
10
+ return content.replace(/\r\n?/g, "\n").trim();
11
+ }
12
+ function normalizeContextPath(pathValue) {
13
+ return pathValue.replace(/\\/g, "/").trim();
14
+ }
15
+ function normalizePositiveLimit(value, fallback) {
16
+ if (typeof value !== "number" || !Number.isFinite(value))
17
+ return fallback;
18
+ const integer = Math.floor(value);
19
+ return integer > 0 ? integer : fallback;
20
+ }
21
+ function resolveContextOptions(options) {
22
+ return {
23
+ enableContextDedupe: options?.enableContextDedupe !== false,
24
+ maxContextCharsPerFile: normalizePositiveLimit(options?.maxContextCharsPerFile, DEFAULT_CONTEXT_MAX_CHARS_PER_FILE),
25
+ maxTotalContextChars: normalizePositiveLimit(options?.maxTotalContextChars, DEFAULT_CONTEXT_MAX_TOTAL_CHARS),
26
+ enableGitSnapshotContext: options?.enableGitSnapshotContext === true,
27
+ };
28
+ }
29
+ function hashContextForDedupe(content) {
30
+ return createHash("sha256").update(content).digest("hex");
31
+ }
32
+ function buildContextSection(contextFiles, options, gitSnapshotContext) {
33
+ const resolved = resolveContextOptions(options);
34
+ const entries = contextFiles.map((entry) => ({
35
+ path: normalizeContextPath(entry.path),
36
+ content: normalizeContextContent(entry.content),
37
+ }));
38
+ let gitSnapshotIncluded = false;
39
+ if (resolved.enableGitSnapshotContext &&
40
+ typeof gitSnapshotContext?.content === "string" &&
41
+ gitSnapshotContext.content.trim().length > 0) {
42
+ gitSnapshotIncluded = true;
43
+ entries.push({
44
+ path: normalizeContextPath(gitSnapshotContext.path ?? "[git-snapshot]"),
45
+ content: normalizeContextContent(gitSnapshotContext.content),
46
+ });
47
+ }
48
+ const stats = {
49
+ contextBeforeChars: entries.reduce((sum, entry) => sum + entry.content.length, 0),
50
+ contextAfterChars: 0,
51
+ dedupeHits: 0,
52
+ truncatedFiles: [],
53
+ droppedFiles: 0,
54
+ totalFiles: entries.length,
55
+ includedFiles: 0,
56
+ gitSnapshotIncluded,
57
+ };
58
+ if (entries.length === 0) {
59
+ return { section: "", stats };
60
+ }
61
+ const seenHashes = new Set();
62
+ const truncated = new Set();
63
+ const deduped = [];
64
+ for (const entry of entries) {
65
+ if (!entry.content) {
66
+ continue;
67
+ }
68
+ if (resolved.enableContextDedupe) {
69
+ const hash = hashContextForDedupe(entry.content);
70
+ if (seenHashes.has(hash)) {
71
+ stats.dedupeHits += 1;
72
+ continue;
73
+ }
74
+ seenHashes.add(hash);
75
+ }
76
+ deduped.push(entry);
77
+ }
78
+ let remainingTotalChars = resolved.maxTotalContextChars;
79
+ const processed = [];
80
+ for (const entry of deduped) {
81
+ let content = entry.content;
82
+ if (content.length > resolved.maxContextCharsPerFile) {
83
+ content = content.slice(0, resolved.maxContextCharsPerFile).trimEnd();
84
+ truncated.add(entry.path);
85
+ }
86
+ if (remainingTotalChars <= 0) {
87
+ stats.droppedFiles += 1;
88
+ truncated.add(entry.path);
89
+ continue;
90
+ }
91
+ if (content.length > remainingTotalChars) {
92
+ content = content.slice(0, remainingTotalChars).trimEnd();
93
+ truncated.add(entry.path);
94
+ }
95
+ if (content.length === 0) {
96
+ stats.droppedFiles += 1;
97
+ continue;
98
+ }
99
+ processed.push({ path: entry.path, content });
100
+ remainingTotalChars = Math.max(0, remainingTotalChars - content.length);
101
+ }
102
+ stats.contextAfterChars = processed.reduce((sum, entry) => sum + entry.content.length, 0);
103
+ stats.includedFiles = processed.length;
104
+ stats.truncatedFiles = Array.from(truncated.values());
105
+ if (processed.length === 0) {
106
+ const metadata = [];
107
+ if (stats.dedupeHits > 0)
108
+ metadata.push(`- dedupe_hits: ${stats.dedupeHits}`);
109
+ if (stats.truncatedFiles.length > 0)
110
+ metadata.push(`- truncated_files: ${stats.truncatedFiles.length}`);
111
+ if (stats.droppedFiles > 0)
112
+ metadata.push(`- dropped_files: ${stats.droppedFiles}`);
113
+ const metadataBlock = metadata.length > 0 ? `${metadata.join("\n")}\n\n` : "";
114
+ return {
115
+ section: `\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n${metadataBlock}(context omitted after preprocessing budget)\n\n`,
116
+ stats,
117
+ };
118
+ }
119
+ const metadataLines = [];
120
+ if (stats.dedupeHits > 0)
121
+ metadataLines.push(`- dedupe_hits: ${stats.dedupeHits}`);
122
+ if (stats.truncatedFiles.length > 0) {
123
+ const preview = stats.truncatedFiles.slice(0, 8).join(", ");
124
+ const suffix = stats.truncatedFiles.length > 8 ? ` (+${stats.truncatedFiles.length - 8} more)` : "";
125
+ metadataLines.push(`- truncated_files: ${stats.truncatedFiles.length} (${preview}${suffix})`);
126
+ }
127
+ if (stats.droppedFiles > 0)
128
+ metadataLines.push(`- dropped_files: ${stats.droppedFiles}`);
129
+ if (stats.gitSnapshotIncluded)
130
+ metadataLines.push("- git_snapshot_context: enabled");
131
+ let section = "\n\n# Project Context\n\n";
132
+ section += "Project-specific instructions and guidelines:\n\n";
133
+ if (metadataLines.length > 0) {
134
+ section += `${metadataLines.join("\n")}\n\n`;
135
+ }
136
+ for (const entry of processed) {
137
+ section += `## ${entry.path}\n\n${entry.content}\n\n`;
138
+ }
139
+ return { section, stats };
140
+ }
6
141
  /** Tool descriptions for system prompt */
7
142
  const toolDescriptions = {
8
143
  read: "Read file contents",
9
- bash: "Execute bash commands (ls, grep, find, etc.)",
144
+ bash: "Execute bash commands (ls, grep, find, etc.); supports detached mode via run_in_background",
10
145
  edit: "Make surgical edits to files (find exact text and replace)",
11
146
  write: "Create or overwrite files",
12
147
  grep: "Search file contents for patterns (respects .gitignore)",
@@ -36,7 +171,7 @@ const toolDescriptions = {
36
171
  };
37
172
  /** Build the system prompt with tools, guidelines, and context */
38
173
  export function buildSystemPrompt(options = {}) {
39
- const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, } = options;
174
+ const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, gitSnapshotContext, contextProcessing, onContextProcessed, skills: providedSkills, } = options;
40
175
  const resolvedCwd = cwd ?? process.cwd();
41
176
  const now = new Date();
42
177
  const dateTime = now.toLocaleString("en-US", {
@@ -52,18 +187,16 @@ export function buildSystemPrompt(options = {}) {
52
187
  const appendSection = appendSystemPrompt ? `\n\n${appendSystemPrompt}` : "";
53
188
  const contextFiles = providedContextFiles ?? [];
54
189
  const skills = providedSkills ?? [];
190
+ const contextSectionResult = buildContextSection(contextFiles, contextProcessing, gitSnapshotContext);
191
+ onContextProcessed?.(contextSectionResult.stats);
55
192
  if (customPrompt) {
56
193
  let prompt = customPrompt;
57
194
  if (appendSection) {
58
195
  prompt += appendSection;
59
196
  }
60
197
  // Append project context files
61
- if (contextFiles.length > 0) {
62
- prompt += "\n\n# Project Context\n\n";
63
- prompt += "Project-specific instructions and guidelines:\n\n";
64
- for (const { path: filePath, content } of contextFiles) {
65
- prompt += `## ${filePath}\n\n${content}\n\n`;
66
- }
198
+ if (contextSectionResult.section) {
199
+ prompt += contextSectionResult.section;
67
200
  }
68
201
  // Append skills section (only if read tool is available)
69
202
  const customPromptHasRead = !selectedTools || selectedTools.includes("read");
@@ -135,6 +268,9 @@ export function buildSystemPrompt(options = {}) {
135
268
  else if (hasBash && (hasGrep || hasFind || hasLs || hasRg || hasFd)) {
136
269
  addGuideline("Prefer grep/find/ls/rg/fd tools over bash for codebase exploration (faster and less noisy)");
137
270
  }
271
+ if (hasBash) {
272
+ addGuideline("For long-running shell work that should not block the turn, use bash with run_in_background=true and report the returned backgroundTaskId; keep foreground mode for commands whose output is needed immediately");
273
+ }
138
274
  if (hasBash && hasGitRead) {
139
275
  addGuideline("Prefer git_read over bash for git status/diff/log/blame analysis in read-only workflows");
140
276
  }
@@ -348,12 +484,8 @@ iosm-cli reference docs (use when needed):
348
484
  prompt += appendSection;
349
485
  }
350
486
  // Append project context files
351
- if (contextFiles.length > 0) {
352
- prompt += "\n\n# Project Context\n\n";
353
- prompt += "Project-specific instructions and guidelines:\n\n";
354
- for (const { path: filePath, content } of contextFiles) {
355
- prompt += `## ${filePath}\n\n${content}\n\n`;
356
- }
487
+ if (contextSectionResult.section) {
488
+ prompt += contextSectionResult.section;
357
489
  }
358
490
  // Append skills section (only if read tool is available)
359
491
  if (hasRead && skills.length > 0) {