issue-flow 0.19.1 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -0
- package/dist/{agent-EWKA7357.js → agent-4DHRKZ2Z.js} +11 -11
- package/dist/{analyze-Z7ODC27F.js → analyze-UEJ2R3H5.js} +19 -19
- package/dist/{apply-VNSWQS6O.js → apply-QDYNQMUX.js} +11 -11
- package/dist/{bench-ZJEIACUK.js → bench-RNRXVEFK.js} +16 -16
- package/dist/{chunk-2EZW4X57.js → chunk-37O2FMAN.js} +8 -8
- package/dist/{chunk-IMB6FA2F.js → chunk-44RF3VFG.js} +48 -4
- package/dist/chunk-44RF3VFG.js.map +1 -0
- package/dist/{chunk-WPHC6JBR.js → chunk-7WBUEBD5.js} +4 -4
- package/dist/{chunk-KDQRNVBZ.js → chunk-ADH6RJNX.js} +3 -3
- package/dist/{chunk-HHXWAWU6.js → chunk-AKL5UPR6.js} +11 -11
- package/dist/{chunk-XKR3VD2Z.js → chunk-BTBJ5UOO.js} +3 -3
- package/dist/{chunk-UDRAD7MF.js → chunk-CLZ6RRZL.js} +7 -7
- package/dist/{chunk-J6VJ5M2U.js → chunk-DBLXLKGU.js} +7 -7
- package/dist/{chunk-3JD25HHJ.js → chunk-DZ3DZ3EN.js} +5 -5
- package/dist/{chunk-P7ZYOC23.js → chunk-EORDSKWZ.js} +7 -7
- package/dist/chunk-EORDSKWZ.js.map +1 -0
- package/dist/{chunk-XQLNZW7I.js → chunk-EYKPWHT7.js} +9 -9
- package/dist/{chunk-2YYP7AE6.js → chunk-FU2FQ4JE.js} +10 -10
- package/dist/{chunk-RGFMQFX7.js → chunk-G442RDFX.js} +5 -5
- package/dist/{chunk-7CMVL4X6.js → chunk-I64N6RL6.js} +2 -2
- package/dist/{chunk-XHCP6ZNO.js → chunk-JBYXJOJJ.js} +11 -11
- package/dist/{chunk-GD7JZMSJ.js → chunk-JCR5C5A7.js} +2 -2
- package/dist/{chunk-UPAAZU4W.js → chunk-K5NM26NV.js} +2 -2
- package/dist/{chunk-TJVX42KY.js → chunk-KUA6KBBD.js} +2 -2
- package/dist/{chunk-WB2FVIUS.js → chunk-KUL64XUF.js} +5 -5
- package/dist/{chunk-DXH4TQRB.js → chunk-MML2G7IC.js} +2 -2
- package/dist/{chunk-IQYXXFRC.js → chunk-PM5YWJYO.js} +5 -5
- package/dist/chunk-PM5YWJYO.js.map +1 -0
- package/dist/{chunk-HWWB22HC.js → chunk-PXPTIXJF.js} +9 -8
- package/dist/chunk-PXPTIXJF.js.map +1 -0
- package/dist/{chunk-MHA7Q3KU.js → chunk-QJHZ3HYJ.js} +24 -24
- package/dist/{chunk-LYC57OXF.js → chunk-RDPK7LYK.js} +4 -4
- package/dist/{chunk-46S7APLQ.js → chunk-RMIBLFG3.js} +9 -9
- package/dist/{chunk-ZAYATXJD.js → chunk-T736DSZI.js} +5 -5
- package/dist/{chunk-MQTVMB7W.js → chunk-UDUUUFQF.js} +35 -12
- package/dist/chunk-UDUUUFQF.js.map +1 -0
- package/dist/{chunk-PHPAK2L6.js → chunk-V7GETODQ.js} +18 -12
- package/dist/{chunk-PHPAK2L6.js.map → chunk-V7GETODQ.js.map} +1 -1
- package/dist/{chunk-PRGPSNGA.js → chunk-VHQMMY2D.js} +2 -2
- package/dist/{chunk-F2NFJ27Z.js → chunk-VJ3PF6B7.js} +50 -16
- package/dist/chunk-VJ3PF6B7.js.map +1 -0
- package/dist/{chunk-HEHHQU4G.js → chunk-WB4FA2EH.js} +6 -6
- package/dist/{chunk-2Q6PG3MT.js → chunk-WQSGL5LX.js} +11 -5
- package/dist/chunk-WQSGL5LX.js.map +1 -0
- package/dist/{chunk-LRWIP7QS.js → chunk-Y2KOWABB.js} +3 -3
- package/dist/{chunk-UHDXXLYH.js → chunk-YC24E66P.js} +538 -40
- package/dist/chunk-YC24E66P.js.map +1 -0
- package/dist/{chunk-NYDAHE3Y.js → chunk-Z6RCKCVB.js} +8 -8
- package/dist/{chunk-ERAG5IQB.js → chunk-ZPGNVBWY.js} +3 -3
- package/dist/cli.js +55 -53
- package/dist/cli.js.map +1 -1
- package/dist/{compat-YPDZB34U.js → compat-OJG76J4I.js} +5 -5
- package/dist/{config-56B4OHZE.js → config-6YTWPDBK.js} +10 -10
- package/dist/{conventions-DW2CM5I3.js → conventions-5UPOTU42.js} +13 -13
- package/dist/{db-5NU77PJA.js → db-QAZG4LQD.js} +9 -9
- package/dist/{diagnostics-UCTS2VUF.js → diagnostics-YEFB42E5.js} +6 -6
- package/dist/execute-QCT64D37.js +38 -0
- package/dist/{generate-O7GUXLN4.js → generate-QATMDKOK.js} +17 -17
- package/dist/{git-LCG45YXD.js → git-XGOECXWG.js} +2 -2
- package/dist/{history-6GSURU3H.js → history-NBPUZVGQ.js} +9 -9
- package/dist/{init-DD6DBRC5.js → init-4LB2YKWP.js} +11 -11
- package/dist/{operations-HU5ZFEBA.js → operations-RUQP2Y2F.js} +11 -11
- package/dist/{permissions-NNNSRC4P.js → permissions-QZPUUBSO.js} +3 -3
- package/dist/plan-2NMSHTMD.js +38 -0
- package/dist/{policy-RFJOJQL6.js → policy-RKKFF5A2.js} +11 -11
- package/dist/pr-QKFO5HI3.js +42 -0
- package/dist/pr-review-H2BFD6F2.js +33 -0
- package/dist/prd-ET6XKYRS.js +37 -0
- package/dist/{ps-AKRHGPSR.js → ps-UIKSOUAQ.js} +10 -10
- package/dist/{recorder-T7426CKV.js → recorder-LOU3PTIE.js} +6 -6
- package/dist/{registry-DWRKD65A.js → registry-HV7M6MAH.js} +4 -4
- package/dist/{repository-TABBRW2C.js → repository-RCRR6RDE.js} +2 -2
- package/dist/{resume-GDXKK5XP.js → resume-BWJZGBLZ.js} +36 -36
- package/dist/review-2MTZLNSS.js +38 -0
- package/dist/{routing-FPNUVE7T.js → routing-RM5ABHHD.js} +12 -12
- package/dist/run-XMACQBRJ.js +61 -0
- package/dist/{state-manager-IGNTD4AB.js → state-manager-SRN4VJSX.js} +4 -4
- package/dist/{usage-XW27AL5K.js → usage-JOODVE5O.js} +9 -9
- package/dist/{web-NCDBVZ5Y.js → web-TLMWJ2BM.js} +15 -15
- package/package.json +3 -2
- package/web/public/app.js +2 -2
- package/dist/chunk-2Q6PG3MT.js.map +0 -1
- package/dist/chunk-F2NFJ27Z.js.map +0 -1
- package/dist/chunk-HWWB22HC.js.map +0 -1
- package/dist/chunk-IMB6FA2F.js.map +0 -1
- package/dist/chunk-IQYXXFRC.js.map +0 -1
- package/dist/chunk-MQTVMB7W.js.map +0 -1
- package/dist/chunk-P7ZYOC23.js.map +0 -1
- package/dist/chunk-UHDXXLYH.js.map +0 -1
- package/dist/execute-R7AVOLNG.js +0 -38
- package/dist/plan-XR6B7EM3.js +0 -38
- package/dist/pr-OSCNJCOO.js +0 -42
- package/dist/pr-review-IKIYHFBO.js +0 -33
- package/dist/prd-HFDZJJQR.js +0 -37
- package/dist/review-JJHMQA2O.js +0 -38
- package/dist/run-RLCURLLL.js +0 -61
- /package/dist/{agent-EWKA7357.js.map → agent-4DHRKZ2Z.js.map} +0 -0
- /package/dist/{analyze-Z7ODC27F.js.map → analyze-UEJ2R3H5.js.map} +0 -0
- /package/dist/{apply-VNSWQS6O.js.map → apply-QDYNQMUX.js.map} +0 -0
- /package/dist/{bench-ZJEIACUK.js.map → bench-RNRXVEFK.js.map} +0 -0
- /package/dist/{chunk-2EZW4X57.js.map → chunk-37O2FMAN.js.map} +0 -0
- /package/dist/{chunk-WPHC6JBR.js.map → chunk-7WBUEBD5.js.map} +0 -0
- /package/dist/{chunk-KDQRNVBZ.js.map → chunk-ADH6RJNX.js.map} +0 -0
- /package/dist/{chunk-HHXWAWU6.js.map → chunk-AKL5UPR6.js.map} +0 -0
- /package/dist/{chunk-XKR3VD2Z.js.map → chunk-BTBJ5UOO.js.map} +0 -0
- /package/dist/{chunk-UDRAD7MF.js.map → chunk-CLZ6RRZL.js.map} +0 -0
- /package/dist/{chunk-J6VJ5M2U.js.map → chunk-DBLXLKGU.js.map} +0 -0
- /package/dist/{chunk-3JD25HHJ.js.map → chunk-DZ3DZ3EN.js.map} +0 -0
- /package/dist/{chunk-XQLNZW7I.js.map → chunk-EYKPWHT7.js.map} +0 -0
- /package/dist/{chunk-2YYP7AE6.js.map → chunk-FU2FQ4JE.js.map} +0 -0
- /package/dist/{chunk-RGFMQFX7.js.map → chunk-G442RDFX.js.map} +0 -0
- /package/dist/{chunk-7CMVL4X6.js.map → chunk-I64N6RL6.js.map} +0 -0
- /package/dist/{chunk-XHCP6ZNO.js.map → chunk-JBYXJOJJ.js.map} +0 -0
- /package/dist/{chunk-GD7JZMSJ.js.map → chunk-JCR5C5A7.js.map} +0 -0
- /package/dist/{chunk-UPAAZU4W.js.map → chunk-K5NM26NV.js.map} +0 -0
- /package/dist/{chunk-TJVX42KY.js.map → chunk-KUA6KBBD.js.map} +0 -0
- /package/dist/{chunk-WB2FVIUS.js.map → chunk-KUL64XUF.js.map} +0 -0
- /package/dist/{chunk-DXH4TQRB.js.map → chunk-MML2G7IC.js.map} +0 -0
- /package/dist/{chunk-MHA7Q3KU.js.map → chunk-QJHZ3HYJ.js.map} +0 -0
- /package/dist/{chunk-LYC57OXF.js.map → chunk-RDPK7LYK.js.map} +0 -0
- /package/dist/{chunk-46S7APLQ.js.map → chunk-RMIBLFG3.js.map} +0 -0
- /package/dist/{chunk-ZAYATXJD.js.map → chunk-T736DSZI.js.map} +0 -0
- /package/dist/{chunk-PRGPSNGA.js.map → chunk-VHQMMY2D.js.map} +0 -0
- /package/dist/{chunk-HEHHQU4G.js.map → chunk-WB4FA2EH.js.map} +0 -0
- /package/dist/{chunk-LRWIP7QS.js.map → chunk-Y2KOWABB.js.map} +0 -0
- /package/dist/{chunk-NYDAHE3Y.js.map → chunk-Z6RCKCVB.js.map} +0 -0
- /package/dist/{chunk-ERAG5IQB.js.map → chunk-ZPGNVBWY.js.map} +0 -0
- /package/dist/{compat-YPDZB34U.js.map → compat-OJG76J4I.js.map} +0 -0
- /package/dist/{config-56B4OHZE.js.map → config-6YTWPDBK.js.map} +0 -0
- /package/dist/{conventions-DW2CM5I3.js.map → conventions-5UPOTU42.js.map} +0 -0
- /package/dist/{db-5NU77PJA.js.map → db-QAZG4LQD.js.map} +0 -0
- /package/dist/{diagnostics-UCTS2VUF.js.map → diagnostics-YEFB42E5.js.map} +0 -0
- /package/dist/{execute-R7AVOLNG.js.map → execute-QCT64D37.js.map} +0 -0
- /package/dist/{generate-O7GUXLN4.js.map → generate-QATMDKOK.js.map} +0 -0
- /package/dist/{git-LCG45YXD.js.map → git-XGOECXWG.js.map} +0 -0
- /package/dist/{history-6GSURU3H.js.map → history-NBPUZVGQ.js.map} +0 -0
- /package/dist/{init-DD6DBRC5.js.map → init-4LB2YKWP.js.map} +0 -0
- /package/dist/{operations-HU5ZFEBA.js.map → operations-RUQP2Y2F.js.map} +0 -0
- /package/dist/{permissions-NNNSRC4P.js.map → permissions-QZPUUBSO.js.map} +0 -0
- /package/dist/{plan-XR6B7EM3.js.map → plan-2NMSHTMD.js.map} +0 -0
- /package/dist/{policy-RFJOJQL6.js.map → policy-RKKFF5A2.js.map} +0 -0
- /package/dist/{pr-OSCNJCOO.js.map → pr-QKFO5HI3.js.map} +0 -0
- /package/dist/{pr-review-IKIYHFBO.js.map → pr-review-H2BFD6F2.js.map} +0 -0
- /package/dist/{prd-HFDZJJQR.js.map → prd-ET6XKYRS.js.map} +0 -0
- /package/dist/{ps-AKRHGPSR.js.map → ps-UIKSOUAQ.js.map} +0 -0
- /package/dist/{recorder-T7426CKV.js.map → recorder-LOU3PTIE.js.map} +0 -0
- /package/dist/{registry-DWRKD65A.js.map → registry-HV7M6MAH.js.map} +0 -0
- /package/dist/{repository-TABBRW2C.js.map → repository-RCRR6RDE.js.map} +0 -0
- /package/dist/{resume-GDXKK5XP.js.map → resume-BWJZGBLZ.js.map} +0 -0
- /package/dist/{review-JJHMQA2O.js.map → review-2MTZLNSS.js.map} +0 -0
- /package/dist/{routing-FPNUVE7T.js.map → routing-RM5ABHHD.js.map} +0 -0
- /package/dist/{run-RLCURLLL.js.map → run-XMACQBRJ.js.map} +0 -0
- /package/dist/{state-manager-IGNTD4AB.js.map → state-manager-SRN4VJSX.js.map} +0 -0
- /package/dist/{usage-XW27AL5K.js.map → usage-JOODVE5O.js.map} +0 -0
- /package/dist/{web-NCDBVZ5Y.js.map → web-TLMWJ2BM.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agents/types.ts","../src/storage/schemas.ts","../src/agents/schemas.ts","../src/storage/lock.ts"],"sourcesContent":["/**\n * The agent layer: a swappable runner inside `runHeadless` / `executeClaude`.\n *\n * The pipeline still talks to those two facades. What changes is the binary\n * they spawn and how its stream is read. Defaults stay Claude, and an\n * unconfigured invocation produces the same argv the project has always used.\n */\n\nimport type { ClaudeUsage } from '../core/metrics.js';\n\n/** Providers the pipeline can invoke. A fifth would add a file, not a refactor. */\nexport type AgentProviderId = 'claude' | 'codex' | 'cursor' | 'antigravity';\n\n/** The eight invocations that actually call an agent. `init` is not one of them. */\nexport type AgentPhase =\n | 'analyze'\n | 'generate'\n | 'prd'\n | 'plan'\n | 'execute'\n | 'review'\n | 'pr'\n | 'pr-review';\n\nexport const AGENT_PHASES: readonly AgentPhase[] = [\n 'analyze',\n 'generate',\n 'prd',\n 'plan',\n 'execute',\n 'review',\n 'pr',\n 'pr-review',\n] as const;\n\nexport function isAgentPhase(value: string): value is AgentPhase {\n return (AGENT_PHASES as readonly string[]).includes(value);\n}\n\nexport function isAgentProviderId(value: string): value is AgentProviderId {\n return value === 'claude' || value === 'codex' || value === 'cursor' || value === 'antigravity';\n}\n\n/**\n * Semantic permission of an invocation, translated by each runner.\n *\n * read-only — phases that only inspect (analyze, review, pr-review)\n * workspace — phases that write artifacts (generate, prd, plan, pr)\n * autonomous — the execute loop\n */\nexport type AgentPermission = 'read-only' | 'workspace' | 'autonomous';\n\n/** Default permission of each phase. Analyze writes `analysis.md` via a\n * fallback when the agent cannot write, so it stays in the issue's read-only\n * set: the agent is asked not to mutate the project, and the command writes\n * the artifact itself when needed. */\nexport const DEFAULT_PHASE_PERMISSION: Record<AgentPhase, AgentPermission> = {\n analyze: 'read-only',\n generate: 'workspace',\n prd: 'workspace',\n plan: 'workspace',\n execute: 'autonomous',\n review: 'read-only',\n pr: 'workspace',\n 'pr-review': 'read-only',\n};\n\n/** Token/cost metrics. Alias of the existing Claude shape so no import breaks. */\nexport type AgentUsage = ClaudeUsage;\n\nexport type AgentEvent =\n | { kind: 'text'; text: string }\n | { kind: 'tool'; name: string; detail?: string };\n\n/**\n * What a runner needs to execute one invocation.\n *\n * `onLine` is the watchdog heartbeat: a process writing anything is a process\n * that is alive, including a malformed line. `onEvent` is the normalised\n * stream the UI already consumes.\n */\nexport interface AgentInvocation {\n prompt: string;\n phase: AgentPhase;\n workingDirectory?: string;\n addDirs?: string[];\n /** ms; 0 = no limit (the execute loop). */\n timeout: number;\n permission: AgentPermission;\n maxTurns?: number;\n allowedTools?: string[];\n onEvent?: (event: AgentEvent) => void;\n onLine?: (line: string) => void;\n /**\n * Silence tolerated before the agent is considered stuck. Absent or `0`\n * disables the watchdog — verbose headless never had one.\n */\n inactivityTimeoutMs?: number;\n /** Pin this invocation to a provider (L2 reviewer). Skips failover. */\n forceProvider?: AgentProviderId;\n /** Telemetry purpose when it is not the phase name (`verify`). */\n purpose?: 'verify';\n /** Observability context; it never changes provider behaviour or prompt contents. */\n iteration?: number;\n correctionCycle?: number;\n storyIds?: string[];\n}\n\nexport interface AgentRunResult {\n success: boolean;\n result: string;\n /** Combined raw output, for `isTransientFailure()` / `trimErrorMessage()`. */\n rawOutput: string;\n exitCode: number;\n usage: AgentUsage | null;\n error: string | null;\n /** Who actually ran — never inferred afterwards. */\n agent: { provider: AgentProviderId; model: string | null };\n sessionId?: string;\n /** Captured at invocation time and cached per process. */\n harnessVersion?: string | null;\n}\n\n/**\n * What a runner can do. Declared so a fourth provider adds a file, not a\n * refactor. The core asks \"does this invocation need extraDirectories?\",\n * never \"which provider is this?\".\n */\nexport interface AgentCapabilities {\n /** Extra directories beyond the workspace. `flag` is `--add-dir`. */\n extraDirectories: 'flag' | 'permission-file' | 'none';\n /** Convenience: `extraDirectories === 'flag'`. */\n addDirs: boolean;\n toolAllowlist: boolean;\n maxTurns: boolean;\n osSandbox: boolean;\n modelSelection: boolean;\n modelDiscovery: boolean;\n usage: 'tokens-and-cost' | 'tokens-only' | 'none';\n reportsUsage: boolean;\n reportsCost: boolean;\n sessionResume: boolean;\n /** How the auth probe is interpreted. Cursor's `status` exits 0 while logged out. */\n authProbe: 'exit-code' | 'text' | 'none';\n bareModelAliases: boolean;\n promptChannel: 'argv' | 'stdin' | 'both';\n nativeTimeout: boolean;\n contextFileName: string;\n contextFileMaxBytes: number | null;\n toolNameCase: 'CamelCase' | 'lowercase' | 'none';\n readOnlyMode: 'native' | 'sandbox' | 'tool-allowlist' | 'none';\n}\n\nexport type CodexSandbox = 'read-only' | 'workspace-write' | 'danger-full-access';\nexport type CodexReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';\n\nexport interface ClaudeSettings {\n ignoreUserConfig?: boolean;\n /** Companion of `ignoreUserConfig`. Escape: `false` keeps user MCP servers. */\n strictMcpConfig?: boolean;\n}\n\nexport interface CodexSettings {\n reasoningEffort?: CodexReasoningEffort;\n sandbox?: CodexSandbox;\n ignoreUserConfig?: boolean;\n skipGitRepoCheck?: boolean;\n configOverrides?: Record<string, string | number | boolean>;\n}\n\nexport type CursorSandbox = 'enabled' | 'disabled';\nexport type CursorPermissionsFile = 'global' | 'project' | 'none';\n\nexport interface CursorSettings {\n sandbox?: CursorSandbox;\n approveMcps?: boolean;\n permissionsFile?: CursorPermissionsFile;\n minVersion?: string;\n}\n\nexport type AntigravityEffort = 'low' | 'medium' | 'high';\n\nexport interface AntigravitySettings {\n effort?: AntigravityEffort;\n sandbox?: boolean;\n /** Ceiling used when `timeout === 0`. `null` / `0` is \"no ceiling\" and is rejected. */\n executeTimeout?: number | string | null;\n maxPromptBytes?: number;\n minVersion?: string;\n}\n\n/** One layer of the agent block — default or a single phase. */\nexport interface AgentBlock {\n provider?: AgentProviderId;\n model?: string | null;\n claude?: ClaudeSettings;\n codex?: CodexSettings;\n cursor?: CursorSettings;\n antigravity?: AntigravitySettings;\n}\n\nexport interface AgentConfig {\n provider: AgentProviderId;\n model: string | null;\n claude: ClaudeSettings;\n codex: CodexSettings;\n cursor: CursorSettings;\n antigravity: AntigravitySettings;\n phases: Partial<Record<AgentPhase, AgentBlock>>;\n}\n\n/** Which rung of the ladder produced a resolved value. */\nexport type AgentOrigin = 'default' | 'global' | 'project' | 'env' | 'cli';\n\nexport interface ResolvedAgentSettings {\n provider: AgentProviderId;\n model: string | null;\n claude: ClaudeSettings;\n codex: CodexSettings;\n cursor: CursorSettings;\n antigravity: AntigravitySettings;\n origin: {\n provider: AgentOrigin;\n model: AgentOrigin;\n };\n}\n\nexport interface AgentRunner {\n readonly id: AgentProviderId;\n readonly capabilities: AgentCapabilities;\n versionCommand(): { command: string; args: string[] };\n authCommand?(): { command: string; args: string[] };\n run(invocation: AgentInvocation, settings: ResolvedAgentSettings): Promise<AgentRunResult>;\n}\n\nexport const CLAUDE_CAPABILITIES: AgentCapabilities = {\n extraDirectories: 'flag',\n addDirs: true,\n toolAllowlist: true,\n maxTurns: true,\n osSandbox: false,\n modelSelection: true,\n modelDiscovery: false,\n usage: 'tokens-and-cost',\n reportsUsage: true,\n reportsCost: true,\n sessionResume: false,\n authProbe: 'none',\n bareModelAliases: true,\n promptChannel: 'both',\n nativeTimeout: false,\n contextFileName: 'CLAUDE.md',\n contextFileMaxBytes: null,\n toolNameCase: 'CamelCase',\n readOnlyMode: 'native',\n};\n\nexport const CODEX_CAPABILITIES: AgentCapabilities = {\n extraDirectories: 'flag',\n addDirs: true,\n toolAllowlist: false,\n maxTurns: false,\n osSandbox: true,\n modelSelection: true,\n modelDiscovery: false,\n usage: 'tokens-only',\n reportsUsage: true,\n reportsCost: false,\n sessionResume: true,\n authProbe: 'exit-code',\n bareModelAliases: false,\n promptChannel: 'both',\n nativeTimeout: false,\n contextFileName: 'AGENTS.md',\n contextFileMaxBytes: 32 * 1024,\n toolNameCase: 'none',\n readOnlyMode: 'sandbox',\n};\n\nexport const CURSOR_CAPABILITIES: AgentCapabilities = {\n extraDirectories: 'permission-file',\n addDirs: false,\n toolAllowlist: false,\n maxTurns: false,\n osSandbox: true,\n modelSelection: true,\n modelDiscovery: true,\n usage: 'none',\n reportsUsage: false,\n reportsCost: false,\n sessionResume: true,\n authProbe: 'text',\n bareModelAliases: false,\n promptChannel: 'argv',\n nativeTimeout: false,\n contextFileName: 'AGENTS.md',\n contextFileMaxBytes: null,\n toolNameCase: 'lowercase',\n readOnlyMode: 'native',\n};\n\nexport const ANTIGRAVITY_CAPABILITIES: AgentCapabilities = {\n extraDirectories: 'flag',\n addDirs: true,\n toolAllowlist: false,\n maxTurns: false,\n osSandbox: true,\n modelSelection: true,\n modelDiscovery: true,\n usage: 'tokens-only',\n reportsUsage: true,\n reportsCost: false,\n sessionResume: true,\n authProbe: 'none',\n bareModelAliases: false,\n promptChannel: 'argv',\n nativeTimeout: true,\n contextFileName: 'AGENTS.md',\n contextFileMaxBytes: null,\n toolNameCase: 'CamelCase',\n readOnlyMode: 'native',\n};\n\nexport const AGENT_SCHEMA_VERSION = 1;\n\n/**\n * CLI overrides captured by `setAgentCliOverrides`.\n *\n * `forceProvider` / `forceModel` are the emergency buttons (`--agent` /\n * `--agent-model`): they overwrite every phase after the ladder has run.\n */\nexport interface AgentCliOverrides {\n provider?: AgentProviderId;\n model?: string | null;\n forceProvider?: AgentProviderId;\n forceModel?: string;\n claude?: ClaudeSettings;\n codex?: CodexSettings;\n cursor?: CursorSettings;\n antigravity?: AntigravitySettings;\n phases?: Partial<Record<AgentPhase, AgentBlock>>;\n}\n","import { z } from 'zod';\nimport { agentConfigInputSchema } from '../agents/schemas.js';\nimport type { ExecutionPlan } from '../execution/types.js';\nimport type {\n ExhaustedAction,\n FailoverMode,\n PolicyConfig as ResiliencePolicyConfig,\n ResilienceProfile,\n RetryConfigKey,\n RetryPolicy,\n} from '../resilience/policy.js';\nimport { pullRequestRefSchema, routingConfigInputSchema, webConfigSchema } from '../schemas.js';\n\n/**\n * Zod schemas for the files written under the global storage tree\n * (`~/.issue-flow`): the per-project `metadata.json` and the global\n * `config.json`.\n *\n * They live here rather than in `src/schemas.ts` so that file stays focused on\n * the pipeline domain (task plans, Issue metadata, session snapshots) and the\n * storage layer keeps owning its own formats.\n */\n\n/** Version stamped on files written by this release of the storage layer. */\nexport const STORAGE_SCHEMA_VERSION = 1;\n\n/**\n * Where a `plan` run's `US-NNN` numbering came from (issue #36):\n *\n * - `history`: recovered from the highest number already used anywhere in the\n * project's `tasks.json` files, automatically or via `--continue`.\n * - `start-us`: forced by the user via `--start-us <n>`, ignoring history.\n * - `none`: no history found (the project's first `plan` run) — starts at\n * `US-001`.\n */\nexport const userStoryNumberingSourceSchema = z.enum(['history', 'start-us', 'none']);\n\n/**\n * A single numbering decision, persisted for audit under\n * `metadata.json`'s `userStoryNumbering` (see below) — never used to resolve\n * the *next* decision, which always re-scans `tasks.json` from scratch.\n */\nexport const userStoryNumberingDecisionSchema = z.object({\n /** The `US-NNN` number the `plan` prompt was told to continue from. */\n nextNumber: z.number().int().positive(),\n source: userStoryNumberingSourceSchema,\n /** Issue the decision was made for. */\n issueNumber: z.string().min(1),\n decidedAt: z.string().min(1),\n /** Human-readable origin, e.g. the previous story id and issue it came from. */\n detail: z.string().optional(),\n});\n\n/**\n * `~/.issue-flow/projects/<project-id>/metadata.json`.\n *\n * Deliberately **not** `.strict()`: a newer release may add fields (dashboard\n * history, counters) and an older one must still be able to read the file\n * instead of rejecting it. Unknown keys are dropped on parse, never fatal.\n *\n * `root` is the last known local checkout — informative only. Identity lives in\n * `projectId` (see `getProjectId()` in `paths.ts`), so moving the folder of a\n * project that has a remote updates `root` without changing the id.\n */\nexport const projectMetadataSchema = z.object({\n schemaVersion: z.number().int().positive(),\n projectId: z.string().min(1),\n root: z.string().min(1),\n /** Normalized remote (`host/org/repo`), or null when the project has none. */\n remoteUrl: z.string().nullable(),\n createdAt: z.string().min(1),\n updatedAt: z.string().min(1),\n /** Null until the project is used by a pipeline run. */\n lastAttemptAt: z.string().nullable(),\n /**\n * Most recent User Story numbering decision made by `plan` (issue #36).\n * Absent on a project whose `plan` never ran through the numbering\n * resolver, or on a `metadata.json` written before the feature existed.\n */\n userStoryNumbering: userStoryNumberingDecisionSchema.optional(),\n});\n\n/**\n * Global counterpart of the `web` key of `.issue-flow.json`, restricted to the\n * settings that make sense machine-wide: `enabled` and `includeLogs` stay a\n * per-project decision.\n *\n * The validation of each field is reused from `webConfigSchema` through\n * `.unwrap()`, which strips the `.default()` and keeps the constraints. Picking\n * and calling `.partial()` would not be enough: in zod 4 an optional field\n * still materializes its default when the key is absent\n * (`z.object({ port: z.number().default(3737) }).partial().parse({})` yields\n * `{ port: 3737 }`), and a materialized default in this layer would override\n * the project layer during the merge.\n */\nconst webShape = webConfigSchema.shape;\nexport const globalWebConfigSchema = z\n .object({\n port: webShape.port.unwrap(),\n host: webShape.host.unwrap(),\n refreshSeconds: webShape.refreshSeconds.unwrap(),\n logLimit: webShape.logLimit.unwrap(),\n })\n .partial();\n\n/** Global retry preferences, mirroring `DEFAULTS` in `config.ts`. */\nexport const globalRetryConfigSchema = z\n .object({\n retryLimit: z.number().int().nonnegative(),\n retryForever: z.boolean(),\n backoffBaseSeconds: z.number().nonnegative(),\n backoffMaxSeconds: z.number().nonnegative(),\n })\n .partial();\n\n/* ── the `resilience` key ───────────────────────────────────────────────── */\n\n/**\n * The file format of the `resilience` key, shared by `.issue-flow.json` and\n * `~/.issue-flow/config.json` — the same object is accepted in both, because\n * they are two rungs of one ladder rather than two formats.\n *\n * **Every field is optional and none carries a `.default()`**, for the reason\n * stated on `globalConfigSchema` below and in `AGENTS.md`: both files are\n * intermediate precedence layers, and a default materialized in one of them is\n * indistinguishable from a value the user wrote.\n *\n * The enums are pinned to the types of `resilience/policy.ts` with `satisfies`,\n * so a value the resolver understands and the file rejects (or the reverse) is\n * a compile error rather than a silent drop at parse time.\n */\nconst resilienceProfileSchema = z.enum([\n 'default',\n 'continuous',\n]) satisfies z.ZodType<ResilienceProfile>;\nconst jitterSchema = z.enum(['none', 'full']) satisfies z.ZodType<RetryPolicy['jitter']>;\nconst failoverModeSchema = z.enum([\n 'never',\n 'after_attempts',\n 'immediate',\n]) satisfies z.ZodType<FailoverMode>;\nconst exhaustedActionSchema = z.enum(['fail', 'block']) satisfies z.ZodType<ExhaustedAction>;\n\n/** One `resilience.retry.<kind>` entry — a partial `RetryPolicy`. */\nexport const retryPolicyOverrideSchema = z\n .object({\n maxAttempts: z.number().int().nonnegative(),\n initialDelayMs: z.number().nonnegative(),\n maxDelayMs: z.number().nonnegative(),\n backoffFactor: z.number().min(1),\n jitter: jitterSchema,\n retryForever: z.boolean(),\n failover: failoverModeSchema,\n failoverAfterAttempts: z.number().int().positive(),\n onExhausted: exhaustedActionSchema,\n })\n .partial();\n\n/**\n * `resilience.retry`, one optional entry per `FailureKind`.\n *\n * Built from a `Record<RetryConfigKey, …>` on purpose: adding a `FailureKind`\n * without giving it a configuration key stops compiling here.\n */\nconst retryOverridesByKind: Record<RetryConfigKey, typeof retryPolicyOverrideSchema> = {\n network: retryPolicyOverrideSchema,\n timeout: retryPolicyOverrideSchema,\n stalled: retryPolicyOverrideSchema,\n rateLimit: retryPolicyOverrideSchema,\n providerDown: retryPolicyOverrideSchema,\n providerCrash: retryPolicyOverrideSchema,\n authentication: retryPolicyOverrideSchema,\n configuration: retryPolicyOverrideSchema,\n repositoryState: retryPolicyOverrideSchema,\n taskExecution: retryPolicyOverrideSchema,\n internal: retryPolicyOverrideSchema,\n unknown: retryPolicyOverrideSchema,\n};\n\nexport const resilienceRetryConfigSchema = z.object(retryOverridesByKind).partial();\n\n/** `resilience.providers` — agent health and failover (US-024, US-025). */\nexport const resilienceProvidersConfigSchema = z\n .object({\n failover: z.boolean(),\n chain: z.array(z.string().min(1)),\n cooldownMs: z.number().nonnegative(),\n maxCooldownMs: z.number().nonnegative(),\n failureWindowMs: z.number().positive(),\n failuresToTrip: z.number().int().positive(),\n })\n .partial();\n\nexport const providerHealthStatusSchema = z.enum([\n 'healthy',\n 'degraded',\n 'unavailable',\n 'rate_limited',\n 'auth_failed',\n 'half_open',\n]);\n\nexport const providerHealthRecordSchema = z.object({\n status: providerHealthStatusSchema.default('healthy'),\n failures: z\n .array(\n z.object({\n at: z.string(),\n kind: z.enum([\n 'network',\n 'timeout',\n 'stalled',\n 'rate_limit',\n 'provider_down',\n 'provider_crash',\n 'authentication',\n 'configuration',\n 'repository_state',\n 'task_execution',\n 'internal',\n 'unknown',\n ]),\n }),\n )\n .default([]),\n consecutiveFailures: z.number().int().nonnegative().default(0),\n cooldownLevel: z.number().int().nonnegative().default(0),\n cooldownUntil: z.string().nullable().default(null),\n lastFailureKind: z\n .enum([\n 'network',\n 'timeout',\n 'stalled',\n 'rate_limit',\n 'provider_down',\n 'provider_crash',\n 'authentication',\n 'configuration',\n 'repository_state',\n 'task_execution',\n 'internal',\n 'unknown',\n ])\n .nullable()\n .default(null),\n lastFailureAt: z.string().nullable().default(null),\n lastSuccessAt: z.string().nullable().default(null),\n probeInFlight: z.boolean().default(false),\n probeStartedAt: z.string().nullable().default(null),\n});\n\nexport const providersHealthSchema = z.object({\n schemaVersion: z.literal(1).default(1),\n providers: z.record(z.string(), providerHealthRecordSchema).default({}),\n});\n\n/** `resilience.queue` — what a failing issue does to the rest of them (US-027). */\nexport const resilienceQueueConfigSchema = z\n .object({\n onIssueFailure: z.enum(['stop', 'skip', 'block']),\n maxIssueAttempts: z.number().int().positive(),\n })\n .partial();\n\n/** `resilience.watchdog` — inactivity detection over the event stream (US-026). */\nexport const resilienceWatchdogConfigSchema = z\n .object({\n inactivityTimeoutMs: z.number().int().nonnegative(),\n })\n .partial();\n\n/** `resilience.journal` — the append-only `events.jsonl` (US-015). */\nexport const resilienceJournalConfigSchema = z\n .object({\n enabled: z.boolean(),\n maxFileBytes: z.number().int().positive(),\n })\n .partial();\n\n/** `resilience.decompose` — the \"this issue is too large\" report (US-030). */\nexport const resilienceDecomposeConfigSchema = z\n .object({\n auto: z.boolean(),\n })\n .partial();\n\nexport const resilienceConfigSchema = z\n .object({\n profile: resilienceProfileSchema,\n /** Whether a credential failure may migrate to another provider. */\n failoverOnAuth: z.boolean(),\n retry: resilienceRetryConfigSchema,\n providers: resilienceProvidersConfigSchema,\n queue: resilienceQueueConfigSchema,\n watchdog: resilienceWatchdogConfigSchema,\n journal: resilienceJournalConfigSchema,\n decompose: resilienceDecomposeConfigSchema,\n })\n .partial();\n\n/**\n * Intermediate `telemetry` key. Every field optional, no `.default()` — this\n * file is a middle rung of the config ladder.\n */\nexport const telemetryPricingOverrideSchema = z\n .object({\n inputPerMillion: z.number(),\n outputPerMillion: z.number(),\n cacheReadPerMillion: z.number(),\n cacheWritePerMillion: z.number(),\n })\n .partial();\n\nexport const telemetryConfigInputSchema = z\n .object({\n enabled: z.boolean(),\n maxExecutions: z.number().int().positive(),\n pricing: z\n .object({\n estimate: z.boolean(),\n overrides: z.record(z.string(), telemetryPricingOverrideSchema),\n })\n .partial(),\n })\n .partial();\n\n/** Global commit preferences. `signoff` is consumed by `commitMessage()`. */\nexport const globalCommitConfigSchema = z\n .object({\n signoff: z.boolean(),\n conventional: z.boolean(),\n })\n .partial();\n\n/**\n * SQLite adoption controls. They deliberately live in a separate `storage`\n * object so choosing the compatibility driver cannot be confused with the\n * location of the global storage tree (`storageDir`).\n */\nexport const storageConfigInputSchema = z\n .object({\n /** Keep legacy JSON as the active driver, for recovery or a staged rollout. */\n driver: z.enum(['sqlite', 'json']),\n /** Number of pre-migration database snapshots to retain. */\n backupRetention: z.number().int().nonnegative(),\n /** Explicit row-retention policy. Omitted values mean retain history. */\n retention: z\n .object({\n executions: z.number().int().nonnegative(),\n events: z.number().int().nonnegative(),\n snapshots: z.number().int().nonnegative(),\n backups: z.number().int().nonnegative(),\n })\n .partial(),\n })\n .partial();\n\n/**\n * `~/.issue-flow/config.json`.\n *\n * **Every key is optional and no key carries a `.default()`.** This is a design\n * constraint, not an omission: the global file is an intermediate precedence\n * layer (CLI > env > `.issue-flow.json` > `config.json` > defaults), so a\n * default materialized here would be indistinguishable from a value the user\n * actually wrote and would silently override the project layer during the\n * merge. Same reason `readWebConfigFile()` parses with\n * `webConfigSchema.partial()`. Defaults belong to the final layer only.\n */\nexport const globalConfigSchema = z\n .object({\n schemaVersion: z.number().int().positive(),\n /** Override for the directory holding `projects/`. */\n storageDir: z.string().min(1),\n storage: storageConfigInputSchema,\n web: globalWebConfigSchema,\n retry: globalRetryConfigSchema,\n commit: globalCommitConfigSchema,\n resilience: resilienceConfigSchema,\n agent: agentConfigInputSchema,\n telemetry: telemetryConfigInputSchema,\n routing: routingConfigInputSchema,\n })\n .partial();\n\n/**\n * `~/.issue-flow/web.lock`.\n *\n * Marks the single web monitoring server active on this machine: `pid` and\n * `port` let a new invocation tell a live instance from a stale one before\n * attempting to bind its own (see `web/lock.ts`). Not `.strict()` for the same\n * reason as the schemas above — a newer release may add fields.\n */\nexport const webLockSchema = z.object({\n pid: z.number().int().positive(),\n port: z.number().int().positive(),\n host: z.string().min(1),\n startedAt: z.string().min(1),\n /** Added in a backward-compatible way: locks from older releases remain valid. */\n instanceId: z.string().min(1).optional(),\n});\n\n/**\n * `~/.issue-flow/projects/<project-id>/run.lock`.\n *\n * Ownership of a run, so a second invocation in the same project refuses\n * instead of fighting the first one over `tasks.json` and the branch. Same\n * shape of guard as `web.lock` — a pid, a host and a timestamp — plus the\n * heartbeat that tells a dead owner from a slow one.\n *\n * No field defaults: a lock is written whole by its owner, and a half-read one\n * degrades to \"no lock\" at the reader, exactly like `readWebLock`.\n */\nexport const runLockSchema = z.object({\n pid: z.number().int().positive(),\n /** `os.hostname()`. A pid only means something on the host that wrote it. */\n host: z.string().min(1),\n /** The issue (or queue) identifier the owner is running. */\n target: z.string().min(1),\n startedAt: z.string().min(1),\n lastHeartbeatAt: z.string().min(1),\n /** Absent on a foreground run written before this field existed. */\n detached: z.boolean().optional(),\n});\n\n/**\n * `~/.issue-flow/projects/<project-id>/queues/<queue-id>/execution-plan.json`.\n *\n * The coordination state of a multi-issue run: which Issues, in which order, on\n * which shared branch, and how far the queue got. Each Issue keeps its own\n * `tasks.json` — nothing of the task plan is duplicated here.\n *\n * Written only when a queue really has more than one Issue: a single-issue run\n * creates no queue directory at all, which is what keeps the storage layout of\n * every existing user unchanged.\n *\n * Not `.strict()`, like every other file schema here, and `satisfies` keeps it\n * in lockstep with the `ExecutionPlan` interface in `src/execution/types.ts`.\n */\nexport const executionPlanIssueSchema = z.object({\n id: z.string().min(1),\n number: z.number().int().positive().nullable(),\n title: z.string(),\n url: z.string().nullable(),\n source: z.string().min(1),\n position: z.number().int().positive(),\n // `blocked` and `skipped` are additive: no plan written before them can\n // carry one, and a reader that does not know them was never given one.\n status: z.enum(['pending', 'in_progress', 'completed', 'failed', 'blocked', 'skipped']),\n origin: z.enum(['requested', 'discovered']),\n role: z.enum(['executable', 'container']).default('executable'),\n externalDependencies: z.array(z.string()).default([]),\n dependsOn: z.array(z.string()).default([]),\n parent: z.string().nullable().default(null),\n priority: z.enum(['high', 'medium', 'low']).nullable().default(null),\n heuristic: z.boolean().default(false),\n failedPhase: z.string().nullable().default(null),\n lastError: z\n .object({ category: z.string(), message: z.string(), at: z.string() })\n .nullable()\n .default(null),\n startedAt: z.string().nullable().default(null),\n completedAt: z.string().nullable().default(null),\n // Both default, so an execution-plan.json written by an earlier release\n // parses unchanged and reads as \"never attempted, not blocked\".\n attempts: z.number().int().min(0).default(0),\n blockedReason: z.string().nullable().default(null),\n});\n\nexport const executionPlanSchema = z.object({\n closeIssue: z.boolean().optional(),\n closedIssueIds: z.array(z.string()).optional(),\n prReviewCompleted: z.boolean().optional(),\n schemaVersion: z.literal(1),\n id: z.string().min(1),\n project: z.string().min(1),\n requested: z.array(z.string().min(1)),\n branchName: z.string().nullable().default(null),\n noBranch: z.boolean().default(false),\n prReview: z.boolean().default(false),\n status: z.enum(['pending', 'in_progress', 'completed', 'failed']),\n createdAt: z.string().min(1),\n updatedAt: z.string().min(1),\n truncated: z.boolean().default(false),\n issues: z.array(executionPlanIssueSchema),\n excluded: z\n .array(\n z.object({\n id: z.string().min(1),\n number: z.number().int().positive().nullable(),\n title: z.string(),\n url: z.string().nullable(),\n reason: z.string(),\n }),\n )\n .default([]),\n pullRequest: pullRequestRefSchema.optional(),\n}) satisfies z.ZodType<ExecutionPlan>;\n\nexport type UserStoryNumberingSource = z.infer<typeof userStoryNumberingSourceSchema>;\nexport type UserStoryNumberingDecision = z.infer<typeof userStoryNumberingDecisionSchema>;\nexport type ProjectMetadata = z.infer<typeof projectMetadataSchema>;\nexport type ValidatedExecutionPlan = z.infer<typeof executionPlanSchema>;\nexport type GlobalWebConfig = z.infer<typeof globalWebConfigSchema>;\nexport type GlobalRetryConfig = z.infer<typeof globalRetryConfigSchema>;\nexport type GlobalCommitConfig = z.infer<typeof globalCommitConfigSchema>;\nexport type StorageConfigInput = z.infer<typeof storageConfigInputSchema>;\nexport type ResilienceRetryConfig = z.infer<typeof resilienceRetryConfigSchema>;\nexport type ResilienceProvidersConfig = z.infer<typeof resilienceProvidersConfigSchema>;\nexport type ProviderHealthStatus = z.infer<typeof providerHealthStatusSchema>;\nexport type ProviderHealthRecord = z.infer<typeof providerHealthRecordSchema>;\nexport type ProvidersHealth = z.infer<typeof providersHealthSchema>;\nexport type ResilienceQueueConfig = z.infer<typeof resilienceQueueConfigSchema>;\nexport type ResilienceWatchdogConfig = z.infer<typeof resilienceWatchdogConfigSchema>;\nexport type ResilienceJournalConfig = z.infer<typeof resilienceJournalConfigSchema>;\nexport type ResilienceDecomposeConfig = z.infer<typeof resilienceDecomposeConfigSchema>;\nexport type ResilienceConfig = z.infer<typeof resilienceConfigSchema>;\nexport type GlobalConfig = z.infer<typeof globalConfigSchema>;\nexport type TelemetryConfigInput = z.infer<typeof telemetryConfigInputSchema>;\n\n/**\n * The file format is a *superset* of what `resolvePolicy()` reads: it also\n * carries `providers`, `queue`, `watchdog`, `journal` and `decompose`, which\n * belong to later layers. This alias is the compile-time proof of the \"superset\"\n * half — a drift between the two shapes fails to build here rather than at the\n * first call site that passes one to the other.\n */\ntype Assert<T extends true> = T;\nexport type ResilienceConfigIsPolicyConfig = Assert<\n ResilienceConfig extends ResiliencePolicyConfig ? true : false\n>;\nexport type WebLock = z.infer<typeof webLockSchema>;\nexport type RunLock = z.infer<typeof runLockSchema>;\n","import { z } from 'zod';\nimport { AGENT_PHASES, type AgentPhase } from './types.js';\n\n/**\n * File-format schemas for the `agent` key.\n *\n * These are intermediate layers (global `config.json` and `.issue-flow.json`).\n * No field carries a `.default()`: a default materialized here would look\n * like a value the user wrote and would silently override the rung above.\n */\n\nexport const agentProviderIdSchema = z.enum(['claude', 'codex', 'cursor', 'antigravity']);\n\nexport const codexSandboxSchema = z.enum(['read-only', 'workspace-write', 'danger-full-access']);\n\nexport const codexReasoningEffortSchema = z.enum(['minimal', 'low', 'medium', 'high', 'xhigh']);\n\nexport const claudeSettingsSchema = z\n .object({\n ignoreUserConfig: z.boolean(),\n strictMcpConfig: z.boolean(),\n })\n .partial();\n\nexport const codexSettingsSchema = z\n .object({\n reasoningEffort: codexReasoningEffortSchema,\n sandbox: codexSandboxSchema,\n ignoreUserConfig: z.boolean(),\n skipGitRepoCheck: z.boolean(),\n configOverrides: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])),\n })\n .partial();\n\nexport const cursorSandboxSchema = z.enum(['enabled', 'disabled']);\n\nexport const cursorPermissionsFileSchema = z.enum(['global', 'project', 'none']);\n\nexport const cursorSettingsSchema = z\n .object({\n sandbox: cursorSandboxSchema,\n approveMcps: z.boolean(),\n permissionsFile: cursorPermissionsFileSchema,\n minVersion: z.string().min(1),\n force: z.boolean().refine((value) => value !== false, {\n message:\n 'agent.cursor.force cannot be false: without --force, Cursor finishes with exit 0 and writes nothing.',\n }),\n })\n .partial();\n\nexport const antigravityEffortSchema = z.enum(['low', 'medium', 'high']);\n\nexport const antigravitySettingsSchema = z\n .object({\n effort: antigravityEffortSchema,\n sandbox: z.boolean(),\n executeTimeout: z.union([z.number().int(), z.string().min(1), z.null()]),\n maxPromptBytes: z.number().int().positive(),\n minVersion: z.string().min(1),\n skipPermissions: z.boolean().refine((value) => value !== false, {\n message:\n 'agent.antigravity.skipPermissions cannot be false: without --dangerously-skip-permissions, Antigravity finishes SUCCESS and writes nothing.',\n }),\n })\n .partial();\n\nexport const agentBlockSchema = z\n .object({\n provider: agentProviderIdSchema,\n model: z.string().min(1).nullable(),\n claude: claudeSettingsSchema,\n codex: codexSettingsSchema,\n cursor: cursorSettingsSchema,\n antigravity: antigravitySettingsSchema,\n })\n .partial();\n\n/**\n * The `phases` map as written in a file. Unknown keys are dropped by the\n * loader (with a warning); this schema only accepts the eight real phases.\n */\nexport const agentPhasesSchema = z\n .object({\n analyze: agentBlockSchema,\n generate: agentBlockSchema,\n prd: agentBlockSchema,\n plan: agentBlockSchema,\n execute: agentBlockSchema,\n review: agentBlockSchema,\n pr: agentBlockSchema,\n 'pr-review': agentBlockSchema,\n })\n .partial();\n\n/** Input shape of the `agent` key — every field optional, no defaults. */\nexport const agentConfigInputSchema = z\n .object({\n provider: agentProviderIdSchema,\n model: z.string().min(1).nullable(),\n claude: claudeSettingsSchema,\n codex: codexSettingsSchema,\n cursor: cursorSettingsSchema,\n antigravity: antigravitySettingsSchema,\n phases: agentPhasesSchema,\n })\n .partial();\n\nexport type AgentConfigInput = z.infer<typeof agentConfigInputSchema>;\n\n/** Loose parse of a `phases` object so unknown keys can be reported. */\nexport function parsePhasesInput(\n value: unknown,\n warn: (message: string) => void,\n): Partial<Record<AgentPhase, z.infer<typeof agentBlockSchema>>> {\n if (value === undefined || value === null) return {};\n if (typeof value !== 'object' || Array.isArray(value)) {\n warn('Ignoring \"agent.phases\": expected an object.');\n return {};\n }\n\n const result: Partial<Record<AgentPhase, z.infer<typeof agentBlockSchema>>> = {};\n for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {\n if (!(AGENT_PHASES as readonly string[]).includes(key)) {\n warn(`Ignoring unknown agent phase \"${key}\".`);\n continue;\n }\n const parsed = agentBlockSchema.safeParse(raw);\n if (!parsed.success) {\n warn(`Ignoring agent.phases.${key}: ${parsed.error.issues[0]?.message ?? 'invalid value'}.`);\n continue;\n }\n result[key as AgentPhase] = parsed.data;\n }\n return result;\n}\n","import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { hostname } from 'node:os';\nimport { dirname } from 'node:path';\nimport { type RunLock, runLockSchema } from './schemas.js';\n\n/**\n * Run ownership: who is executing in this project right now.\n *\n * Generalised from `web/lock.ts`, which has guarded the monitoring server the\n * same way since it existed — atomic `wx` create, `process.kill(pid, 0)` for\n * liveness, and a read that degrades to \"no lock\" on anything malformed. What\n * this module adds is the piece a *long* run needs and a server does not: a\n * **heartbeat**. A web server proves it is alive by answering a health probe;\n * a pipeline has no port to probe, so it says so in the file instead.\n *\n * The two signals answer different questions and both are needed:\n *\n * - the **pid** catches the machine that rebooted or the process that was\n * `kill -9`ed — the lock outlives its owner, and nothing else would notice;\n * - the **heartbeat** catches the owner that is technically alive but no longer\n * running (a pid reused by an unrelated process is the same case), and it is\n * the only signal that survives being read from another host.\n *\n * Nothing here is destructive by inference: a lock is only taken over when it\n * is stale by both measures the policy states, and taking one over is reported\n * to the caller (`reclaimedFrom`) so the run can be recorded as interrupted\n * rather than silently restarted.\n */\n\n/** The lock is rewritten this often while a run holds it. */\nexport const RUN_LOCK_HEARTBEAT_MS = 10_000;\n\n/**\n * How many missed heartbeats make a lock stale.\n *\n * Three, not one: a machine under load, a suspended laptop or a slow\n * filesystem can miss a beat without the run being dead, and stealing a lock\n * from a live owner is the failure this module exists to prevent.\n */\nexport const RUN_LOCK_STALE_INTERVALS = 3;\n\n/** How many times a claim is retried after clearing a stale lock. */\nconst CLAIM_RETRIES = 3;\n\nexport interface RunLockHandle {\n readonly lock: RunLock;\n /**\n * The dead owner this lock was taken from, when it was taken from one.\n *\n * `null` on a clean acquisition. Non-null is the fact a caller records as an\n * *interrupted* run: something was executing here and never finished.\n */\n readonly reclaimedFrom: RunLock | null;\n /** Stop the heartbeat and remove the lock. Never rejects. */\n release(): Promise<void>;\n}\n\nexport type AcquireRunLockResult =\n | { ok: true; handle: RunLockHandle }\n | { ok: false; owner: RunLock };\n\nexport interface AcquireRunLockOptions {\n /** Issue (or queue) identifier this run works on. */\n target: string;\n /** Rewrite interval. Also the unit `staleIntervals` counts. */\n heartbeatMs?: number;\n staleIntervals?: number;\n /** Injectable identity, so a test can pretend to be another process. */\n pid?: number;\n host?: string;\n /** Injectable clock, so staleness is testable without waiting. */\n clock?: () => number;\n /** Called once, when a stale lock is taken over. Never throws through. */\n onTakeover?: (previous: RunLock) => void;\n /**\n * Start the rewriting timer. Default true; a test that drives the clock by\n * hand turns it off and calls `touchRunLock` itself.\n */\n heartbeat?: boolean;\n /** The owner is a process spawned by `--background`. */\n detached?: boolean;\n}\n\n/**\n * `process.kill(pid, 0)` throws `ESRCH` when the pid is gone and `EPERM` when\n * it is alive but owned by another user — **only `ESRCH` means \"not alive\"**.\n * Reading `EPERM` as death is how a lock gets stolen from a healthy run\n * started by another user.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/**\n * Read a lock, degrading anything unreadable to \"no lock\".\n *\n * A partial write, a file from an incompatible release, a truncated JSON: all\n * of them mean the same thing operationally, and none of them justifies\n * failing a run. Same behaviour as `readWebLock` and `loadGlobalConfig`.\n */\nexport async function readRunLock(lockFile: string): Promise<RunLock | null> {\n let raw: string;\n try {\n raw = await readFile(lockFile, 'utf-8');\n } catch {\n return null;\n }\n try {\n const result = runLockSchema.safeParse(JSON.parse(raw));\n return result.success ? result.data : null;\n } catch {\n return null;\n }\n}\n\n/** Remove a lock file. Best effort; never rejects. */\nexport async function removeRunLock(lockFile: string): Promise<void> {\n try {\n await rm(lockFile, { force: true });\n } catch {\n /* best-effort cleanup */\n }\n}\n\nexport interface StalenessOptions {\n heartbeatMs?: number;\n staleIntervals?: number;\n clock?: () => number;\n /** Treat this pid as our own, so a re-entrant claim is not \"stale\". */\n pid?: number;\n host?: string;\n}\n\n/**\n * Whether `lock` may be taken over.\n *\n * A lock written on another host cannot be judged by pid — `process.kill` there\n * says nothing about a process here — so on a foreign host only the heartbeat\n * decides. That is the case a shared filesystem creates, and reading it wrong\n * is how two machines end up on the same branch.\n */\nexport function isRunLockStale(lock: RunLock, options: StalenessOptions = {}): boolean {\n const heartbeatMs = options.heartbeatMs ?? RUN_LOCK_HEARTBEAT_MS;\n const staleIntervals = options.staleIntervals ?? RUN_LOCK_STALE_INTERVALS;\n const now = (options.clock ?? Date.now)();\n const host = options.host ?? hostname();\n\n const beat = Date.parse(lock.lastHeartbeatAt);\n const silent = Number.isNaN(beat) || now - beat > heartbeatMs * staleIntervals;\n\n if (lock.host !== host) return silent;\n return silent || !isProcessAlive(lock.pid);\n}\n\n/** Whether this very process already owns `lock`. */\nfunction isSelf(lock: RunLock, pid: number, host: string): boolean {\n return lock.pid === pid && lock.host === host;\n}\n\n/**\n * One line naming the owner, for the message a refused invocation prints.\n *\n * The pid alone is useless to a person; the pid *plus the host plus when it\n * last said anything* is what lets them decide between waiting and killing it.\n */\nexport function describeRunLockOwner(lock: RunLock): string {\n return `pid ${lock.pid} on ${lock.host} (issue ${lock.target}, started ${lock.startedAt}, last heartbeat ${lock.lastHeartbeatAt})`;\n}\n\n/** Rewrite the lock with a fresh heartbeat. Never rejects. */\nexport async function touchRunLock(lockFile: string, lock: RunLock, at: string): Promise<RunLock> {\n const next: RunLock = { ...lock, lastHeartbeatAt: at };\n try {\n await writeFile(lockFile, `${JSON.stringify(next, null, 2)}\\n`, 'utf-8');\n } catch {\n // A heartbeat that cannot be written is not worth failing a run over: the\n // worst case is that another invocation eventually judges us stale, which\n // is the same outcome as this process having died.\n }\n return next;\n}\n\n/**\n * Atomic exclusive create. `wx` fails with `EEXIST` when someone else won the\n * race, which is what lets two concurrent invocations agree on one winner\n * without a lock for the lock.\n */\nasync function claim(lockFile: string, lock: RunLock): Promise<boolean> {\n try {\n await mkdir(dirname(lockFile), { recursive: true });\n await writeFile(lockFile, `${JSON.stringify(lock, null, 2)}\\n`, {\n encoding: 'utf-8',\n flag: 'wx',\n });\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;\n throw err;\n }\n}\n\n/**\n * Take ownership of the run in this project, or report who already has it.\n *\n * Three outcomes, and only three:\n *\n * 1. **free** — the lock is claimed and a heartbeat starts;\n * 2. **held by a dead owner** — the stale lock is cleared, claimed, and the\n * previous owner comes back on `reclaimedFrom` so the caller can record the\n * interrupted run;\n * 3. **held by a live owner** — `{ ok: false, owner }`, and the caller refuses\n * with a message naming it. Nothing is deleted, nothing is retried into\n * submission.\n *\n * A lock this very process already holds is outcome 1 with a no-op release:\n * re-entering is not a conflict, and a nested acquisition must not remove the\n * file the outer one still owns.\n */\nexport async function acquireRunLock(\n lockFile: string,\n options: AcquireRunLockOptions,\n): Promise<AcquireRunLockResult> {\n const pid = options.pid ?? process.pid;\n const host = options.host ?? hostname();\n const heartbeatMs = options.heartbeatMs ?? RUN_LOCK_HEARTBEAT_MS;\n const clock = options.clock ?? Date.now;\n const staleness: StalenessOptions = {\n heartbeatMs,\n ...(options.staleIntervals === undefined ? {} : { staleIntervals: options.staleIntervals }),\n clock,\n pid,\n host,\n };\n\n let reclaimedFrom: RunLock | null = null;\n\n for (let attempt = 0; attempt <= CLAIM_RETRIES; attempt++) {\n const at = new Date(clock()).toISOString();\n const mine: RunLock = {\n pid,\n host,\n target: options.target,\n startedAt: at,\n lastHeartbeatAt: at,\n ...(options.detached === true ? { detached: true } : {}),\n };\n\n if (await claim(lockFile, mine)) {\n return { ok: true, handle: startHandle(lockFile, mine, reclaimedFrom, options) };\n }\n\n const existing = await readRunLock(lockFile);\n\n if (existing === null) {\n // Unreadable: a partial write, or a file from a shape we do not know.\n // Treated as absent, exactly as `readRunLock` documents.\n await removeRunLock(lockFile);\n continue;\n }\n\n if (isSelf(existing, pid, host)) {\n return { ok: true, handle: nestedHandle(existing) };\n }\n\n if (!isRunLockStale(existing, staleness)) {\n return { ok: false, owner: existing };\n }\n\n reclaimedFrom = existing;\n try {\n options.onTakeover?.(existing);\n } catch {\n // A caller's bookkeeping must not decide whether the run starts.\n }\n await removeRunLock(lockFile);\n }\n\n // Every attempt lost the race and every lock read was stale or unreadable:\n // something else is fighting for this file. Refusing is the safe answer.\n const owner = await readRunLock(lockFile);\n if (owner !== null) return { ok: false, owner };\n return {\n ok: false,\n owner: {\n pid: 0,\n host,\n target: options.target,\n startedAt: new Date(clock()).toISOString(),\n lastHeartbeatAt: new Date(clock()).toISOString(),\n },\n };\n}\n\nfunction startHandle(\n lockFile: string,\n lock: RunLock,\n reclaimedFrom: RunLock | null,\n options: AcquireRunLockOptions,\n): RunLockHandle {\n const heartbeatMs = options.heartbeatMs ?? RUN_LOCK_HEARTBEAT_MS;\n const clock = options.clock ?? Date.now;\n let current = lock;\n let timer: NodeJS.Timeout | null = null;\n\n if (options.heartbeat !== false) {\n timer = setInterval(() => {\n void touchRunLock(lockFile, current, new Date(clock()).toISOString()).then((next) => {\n current = next;\n });\n }, heartbeatMs);\n // The heartbeat must never be the reason a process stays alive.\n timer.unref();\n }\n\n return {\n lock,\n reclaimedFrom,\n release: async () => {\n if (timer !== null) {\n clearInterval(timer);\n timer = null;\n }\n await removeRunLock(lockFile);\n },\n };\n}\n\n/** A re-entrant acquisition: same owner, no timer of its own, no removal. */\nfunction nestedHandle(lock: RunLock): RunLockHandle {\n return { lock, reclaimedFrom: null, release: async () => {} };\n}\n"],"mappings":";;;;;;;;AAwBO,IAAM,eAAsC;AAAA,EACjD;AA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,QAAQ;AAAA,MAChB,WAAW,IAAI,KAAK,MAAM,CAAC,EAAE,YAAY;AAAA,MACzC,iBAAiB,IAAI,KAAK,MAAM,CAAC,EAAE,YAAY;AAAA,IACjD;AAAA,EACF;AACF;AAEA,SAAS,YACP,UACA,MACA,eACA,SACe;AACf,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,QAAQ,QAAQ,SAAS,KAAK;AACpC,MAAI,UAAU;AACd,MAAI,QAA+B;AAEnC,MAAI,QAAQ,cAAc,OAAO;AAC/B,YAAQ,YAAY,MAAM;AACxB,WAAK,aAAa,UAAU,SAAS,IAAI,KAAK,MAAM,CAAC,EAAE,YAAY,CAAC,EAAE,KAAK,CAAC,SAAS;AACnF,kBAAU;AAAA,MACZ,CAAC;AAAA,IACH,GAAG,WAAW;AAEd,UAAM,MAAM;AAAA,EACd;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,SAAS,YAAY;AACnB,UAAI,UAAU,MAAM;AAClB,sBAAc,KAAK;AACnB,gBAAQ;AAAA,MACV;AACA,YAAM,cAAc,QAAQ;AAAA,IAC9B;AAAA,EACF;AACF;AAGA,SAAS,aAAa,MAA8B;AAClD,SAAO,EAAE,MAAM,eAAe,MAAM,SAAS,YAAY;AAAA,EAAC,EAAE;AAC9D;","names":["z","z"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/verify/present.ts","../src/verify/gate.ts","../src/routing/escalation.ts"],"sourcesContent":["import type { VerdictStatus, VerificationLevel } from './types.js';\n\n/** One-line label. `unverified` is never phrased as a verified success. */\nexport function formatVerificationLine(\n verdict: VerdictStatus,\n level: VerificationLevel | string | null = null,\n): string {\n const suffix = level !== null && level !== '' ? ` (${level})` : '';\n if (verdict === 'passed') return `Acceptance contract passed${suffix}`;\n if (verdict === 'failed') return `Acceptance contract failed${suffix}`;\n return `Acceptance contract unverified${suffix} — nothing objective confirmed`;\n}\n","import { dirname } from 'node:path';\nimport { setLastError } from '../core/state-manager.js';\nimport { failureFingerprint, fatalFailedCount } from '../routing/escalation.js';\nimport { redactSecrets } from '../telemetry/redact.js';\nimport type { EngineConfig, ResolvedPaths, TaskPlan } from '../types.js';\nimport { printError, printSuccess, printWarning } from '../ui/logger.js';\nimport { formatVerificationLine } from './present.js';\nimport { formatReviewFindings } from './reviewer.js';\nimport { type AcceptanceOutcome, runAcceptance } from './run-issue.js';\nimport { frameCheckOutput } from './runner.js';\n\nconst contractHistory: { fingerprint: string; fatalFailed: number }[] = [];\n\n/** `prdFile` is `tasks.json` in the issue directory (global or standalone). */\nexport function resolveIssueDir(_config: EngineConfig, paths: ResolvedPaths): string {\n return dirname(paths.prdFile);\n}\n\nexport async function runAcceptanceGate(options: {\n issueDir: string;\n cwd?: string;\n addDirs?: string[];\n skipReviewer?: boolean;\n}): Promise<AcceptanceOutcome> {\n return runAcceptance({\n issueDir: options.issueDir,\n cwd: options.cwd,\n addDirs: options.addDirs,\n skipReviewer: options.skipReviewer,\n });\n}\n\nexport function applyAcceptanceToPlan(\n plan: TaskPlan,\n outcome: AcceptanceOutcome,\n): { plan: TaskPlan; failed: boolean } {\n const line = formatVerificationLine(outcome.verdict, outcome.level);\n if (outcome.verdict === 'failed') {\n printError(line);\n const results = outcome.contract.results;\n contractHistory.push({\n fingerprint: failureFingerprint(results),\n fatalFailed: fatalFailedCount(results),\n });\n return {\n plan: {\n ...setLastError(plan, 'task_execution', line),\n issueStatus: 'in_progress',\n completedAt: null,\n pipeline: { ...plan.pipeline, executionCompleted: false, reviewCompleted: false },\n lastReviewFindings:\n outcome.review?.status === 'failed'\n ? redactSecrets(formatReviewFindings(outcome.review.findings))\n : results\n .filter((result) => result.fatal && result.status !== 'passed')\n .map((result) =>\n redactSecrets(\n `${result.id}: ${result.command ?? 'expected files'} (${result.status})\\n${frameCheckOutput(result.output)}`,\n ),\n )\n .join('\\n') || plan.lastReviewFindings,\n },\n failed: true,\n };\n }\n if (outcome.verdict === 'unverified') {\n printWarning(line);\n return { plan, failed: false };\n }\n printSuccess(line);\n return { plan, failed: false };\n}\n","import type { AgentProviderId } from '../agents/types.js';\nimport type { FailureKind } from '../resilience/errors.js';\nimport type { CheckResult } from '../verify/types.js';\nimport type { ModelEntry, ModelTier } from './models.js';\n\nexport type FailureClass = 'availability' | 'non-convergence' | 'environment';\n\nexport type EscalationRung =\n | 'current'\n | 'effort'\n | 'model'\n | 'harness'\n | 'review'\n | 'decompose'\n | 'blocked';\n\nexport const LADDER: readonly EscalationRung[] = [\n 'current',\n 'effort',\n 'model',\n 'harness',\n 'review',\n 'decompose',\n 'blocked',\n] as const;\n\nexport interface EscalationConfig {\n enabled: boolean;\n minAttemptsBeforeEscalation: number;\n maxEscalations: number;\n maxRungs: EscalationRung[];\n}\n\nexport const DEFAULT_ESCALATION: EscalationConfig = {\n enabled: false,\n minAttemptsBeforeEscalation: 2,\n maxEscalations: 2,\n maxRungs: ['effort', 'model', 'harness'],\n};\n\nconst AVAILABILITY: ReadonlySet<FailureKind> = new Set([\n 'provider_down',\n 'provider_crash',\n 'rate_limit',\n 'network',\n]);\n\nconst ENVIRONMENT: ReadonlySet<FailureKind> = new Set([\n 'configuration',\n 'repository_state',\n 'authentication',\n]);\n\nexport interface AttemptSignals {\n results: readonly CheckResult[];\n failureKind?: FailureKind | null;\n fingerprint?: string;\n fatalFailed?: number;\n diffBytes?: number;\n}\n\n/**\n * Class A stays with #69. Class C stays with #64. This function never\n * recommends a model change for either.\n */\nexport function classifyAttempt(input: AttemptSignals): FailureClass {\n if (input.failureKind && AVAILABILITY.has(input.failureKind)) return 'availability';\n if (input.failureKind && ENVIRONMENT.has(input.failureKind)) return 'environment';\n if (input.results.some((result) => result.status === 'could-not-run')) return 'environment';\n if (input.results.some((result) => result.status === 'failed')) return 'non-convergence';\n return 'environment';\n}\n\n/** Hash of the failed-check *ids*, never of the error text. */\nexport function failureFingerprint(results: readonly CheckResult[]): string {\n return results\n .filter((result) => result.status === 'failed')\n .map((result) => result.id)\n .sort()\n .join('\\n');\n}\n\nexport function fatalFailedCount(results: readonly CheckResult[]): number {\n return results.filter((result) => result.fatal && result.status === 'failed').length;\n}\n\nexport interface ConvergenceHistoryEntry {\n fingerprint: string;\n fatalFailed: number;\n diffBytes?: number;\n}\n\nexport function detectNonConvergence(input: {\n history: readonly ConvergenceHistoryEntry[];\n minAttempts?: number;\n}): { nonConverged: boolean; reason: string } {\n const minAttempts = input.minAttempts ?? DEFAULT_ESCALATION.minAttemptsBeforeEscalation;\n if (input.history.length < minAttempts) {\n return { nonConverged: false, reason: 'below-min-attempts' };\n }\n\n const latest = input.history[input.history.length - 1];\n const previous = input.history[input.history.length - 2];\n if (latest === undefined || previous === undefined) {\n return { nonConverged: false, reason: 'below-min-attempts' };\n }\n\n const progressed =\n latest.fatalFailed < previous.fatalFailed ||\n (latest.diffBytes ?? 0) > (previous.diffBytes ?? 0);\n if (progressed) {\n return { nonConverged: false, reason: 'progress' };\n }\n\n const window = input.history.slice(-minAttempts);\n const samePrint = window.every((entry) => entry.fingerprint === latest.fingerprint);\n if (samePrint && latest.fingerprint !== '') {\n return { nonConverged: true, reason: 'repeated-fingerprint' };\n }\n if (!progressed) {\n return { nonConverged: true, reason: 'no-progress' };\n }\n return { nonConverged: false, reason: 'progress' };\n}\n\nexport interface NextRungInput {\n tried: readonly EscalationRung[];\n capabilities: {\n reasoningEffort: boolean;\n modelSelection: boolean;\n otherHarness: boolean;\n };\n maxRungs?: readonly EscalationRung[];\n maxEscalations?: number;\n escalationsUsed?: number;\n}\n\nexport interface NextRungResult {\n rung: EscalationRung;\n skipped: EscalationRung[];\n exhausted: boolean;\n}\n\nfunction hasCapability(rung: EscalationRung, capabilities: NextRungInput['capabilities']): boolean {\n if (rung === 'effort') return capabilities.reasoningEffort;\n if (rung === 'model') return capabilities.modelSelection;\n if (rung === 'harness') return capabilities.otherHarness;\n return true;\n}\n\n/**\n * The ladder only climbs. A rejected target is never a candidate again.\n * `claude → codex → claude` is impossible because `harness` is consumed once.\n */\nexport function nextRung(input: NextRungInput): NextRungResult {\n const allowed = input.maxRungs ?? DEFAULT_ESCALATION.maxRungs;\n const maxEscalations = input.maxEscalations ?? DEFAULT_ESCALATION.maxEscalations;\n const used = input.escalationsUsed ?? input.tried.filter((rung) => rung !== 'current').length;\n if (used >= maxEscalations) {\n return { rung: 'blocked', skipped: [], exhausted: true };\n }\n\n const skipped: EscalationRung[] = [];\n const tried = new Set(input.tried);\n for (const rung of LADDER) {\n if (rung === 'current') continue;\n if (tried.has(rung)) continue;\n if (rung !== 'blocked' && !allowed.includes(rung)) continue;\n if (!hasCapability(rung, input.capabilities)) {\n skipped.push(rung);\n continue;\n }\n return { rung, skipped, exhausted: rung === 'blocked' };\n }\n return { rung: 'blocked', skipped, exhausted: true };\n}\n\n/** A harness already used on this task cannot be selected again. */\nexport function unusedHarness(\n current: AgentProviderId,\n triedHarnesses: readonly AgentProviderId[],\n available: readonly AgentProviderId[],\n): AgentProviderId | null {\n const seen = new Set<AgentProviderId>([current, ...triedHarnesses]);\n return available.find((id) => !seen.has(id)) ?? null;\n}\n\nconst TIER_ORDER: readonly ModelTier[] = ['fast', 'mid', 'strong'];\n\n/** Return the next stronger concrete model, never a tier/model already attempted. */\nexport function nextModelTier(\n current: ModelTier,\n tried: readonly ModelTier[],\n catalog: readonly ModelEntry[],\n): ModelEntry | null {\n const seen = new Set<ModelTier>([current, ...tried]);\n const currentIndex = TIER_ORDER.indexOf(current);\n for (const tier of TIER_ORDER.slice(currentIndex + 1)) {\n if (seen.has(tier)) continue;\n const entry = catalog.find((model) => model.tier === tier);\n if (entry !== undefined) return entry;\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAGO,SAAS,uBACd,SACA,QAA2C,MACnC;AACR,QAAM,SAAS,UAAU,QAAQ,UAAU,KAAK,KAAK,KAAK,MAAM;AAChE,MAAI,YAAY,SAAU,QAAO,6BAA6B,MAAM;AACpE,MAAI,YAAY,SAAU,QAAO,6BAA6B,MAAM;AACpE,SAA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AE,KAAK,OAAO,WAAW,gBAAgB,KAAK,OAAO,MAAM;AAAA,EAAM,iBAAiB,OAAO,MAAM,CAAC;AAAA,UAC5G;AAAA,QACF,EACC,KAAK,IAAI,KAAK,KAAK;AAAA,MAC9B;AAAA,MACA,QAAQ;AAAA,IACV;AAAA,EACF;AACA,MAAI,QAAQ,YAAY,cAAc;AACpC,iBAAa,IAAI;AACjB,WAAO,EAAE,MAAM,QAAQ,MAAM;AAAA,EAC/B;AACA,eAAa,IAAI;AACjB,SAAO,EAAE,MAAM,QAAQ,MAAM;AAC/B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/headless.ts","../src/routing/budget.ts","../src/agents/health.ts","../src/agents/routing-application.ts","../src/agents/select.ts","../src/agents/invoke.ts","../src/core/decompose.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport chalk from 'chalk';\nimport { invokeSelectedAgent } from '../agents/invoke.js';\nimport { resolveAgentFor } from '../agents/resolve.js';\nimport type {\n AgentEvent,\n AgentInvocation,\n AgentPermission,\n AgentPhase,\n AgentProviderId,\n AgentRunResult,\n} from '../agents/types.js';\nimport { getActiveResilienceConfig } from '../config.js';\nimport { resolvePolicy } from '../resilience/policy.js';\nimport { withRetry } from '../resilience/retry.js';\nimport { writeDiagnostic } from '../storage/diagnostics.js';\nimport { createSpinner, ElapsedTimer, formatDuration, getIcons, useColor } from '../ui/logger.js';\nimport { DECOMPOSITION_THRESHOLDS, timeoutsByPhase } from './decompose.js';\nimport { type ClaudeUsage, sumUsage } from './metrics.js';\nimport { getSessionPublisher } from './session-publisher.js';\nimport { getShutdownSignal } from './shutdown.js';\nimport { isoNow } from './state-manager.js';\nimport {\n getActivityCallback,\n getInactivityTimeout,\n getOutputCallback,\n isVerbose,\n} from './verbose.js';\n\nexport interface HeadlessOptions {\n prompt: string;\n maxTurns?: number;\n timeout?: number;\n outputFormat?: 'json' | 'text' | 'stream-json';\n allowedTools?: string[];\n /**\n * Extra directories the headless session may read from and write to, passed\n * through as `--add-dir`. Required whenever a prompt points at a path outside\n * the working tree (e.g. the global issue storage under `~/.issue-flow`).\n */\n addDirs?: string[];\n /** Status message displayed as spinner (non-verbose) or header (verbose). */\n statusMessage?: string;\n /** Optional callback for routing verbose output (e.g., through listr2 task.output). */\n onOutput?: (line: string) => void;\n /** Journal-backed identity used to apply the one-time 2× timeout escalation. */\n timeoutHistory?: {\n phase: string;\n journalFiles: string[];\n };\n /** The invoking phase. Defaults to `analyze` only for resolution; argv is unchanged. */\n phase?: AgentPhase;\n /**\n * Semantic permission. Absent means `workspace`, which is the historical\n * `runHeadless` argv (no `--permission-mode`, no `--dangerously-skip-permissions`).\n */\n permission?: AgentPermission;\n /** Pin this invocation to a provider (L2 reviewer). */\n forceProvider?: AgentProviderId;\n /** Telemetry purpose when it is not the phase name (`verify`). */\n purpose?: 'verify';\n correctionCycle?: number;\n storyIds?: string[];\n}\n\nexport type HeadlessCost = ClaudeUsage;\n\nexport interface HeadlessResult {\n success: boolean;\n result: string;\n cost: HeadlessCost | null;\n error: string | null;\n agent?: { provider: AgentProviderId; model: string | null };\n /** The resilience budget was spent inside the facade; an outer artifact retry must not repeat it. */\n retryExhausted?: boolean;\n}\n\nexport const DEFAULT_HEADLESS_TIMEOUT_MS = 900_000;\n\nasync function escalatedTimeout(\n timeoutMs: number,\n history: HeadlessOptions['timeoutHistory'],\n): Promise<number> {\n if (timeoutMs === 0 || history === undefined) return timeoutMs;\n\n const journal = (\n await Promise.all(\n history.journalFiles.map(async (file) => {\n try {\n return await readFile(file, 'utf-8');\n } catch {\n return '';\n }\n }),\n )\n ).join('');\n const timeouts = timeoutsByPhase(journal).get(history.phase) ?? 0;\n if (timeouts < DECOMPOSITION_THRESHOLDS.timeoutsPerPhase) return timeoutMs;\n return Math.min(timeoutMs * 2, Number.MAX_SAFE_INTEGER);\n}\n\nfunction printAgentEvent(event: AgentEvent, onOutput?: (line: string) => void): void {\n const icons = getIcons();\n const colored = useColor();\n const emit = onOutput ?? ((msg: string) => process.stdout.write(`${msg}\\n`));\n\n if (event.kind === 'text') {\n const lines = event.text.split('\\n');\n for (const textLine of lines) {\n if (!textLine.trim()) continue;\n const prefix = colored ? chalk.dim(` ${icons.connector} `) : ` ${icons.connector} `;\n const text = colored ? chalk.dim(textLine) : textLine;\n emit(`${prefix}${text}`);\n }\n return;\n }\n\n getSessionPublisher().publish({\n type: 'activity',\n at: isoNow(),\n tool: event.name,\n detail: event.detail,\n });\n const toolName = event.name.padEnd(12);\n const prefix = colored ? chalk.dim(` ${icons.connector} `) : ` ${icons.connector} `;\n const toolIcon = colored ? chalk.cyan(icons.tool) : icons.tool;\n const toolLabel = colored ? chalk.cyan(toolName) : toolName;\n const contextText = event.detail ? (colored ? chalk.dim(event.detail) : event.detail) : '';\n emit(`${prefix}${toolIcon} ${toolLabel} ${contextText}`);\n}\n\nasync function invokeHeadlessAgent(\n invocation: AgentInvocation,\n): Promise<{ run: AgentRunResult; retryExhausted: boolean }> {\n const config = getActiveResilienceConfig();\n if (config.providers?.failover !== true) {\n return { run: (await invokeSelectedAgent(invocation)).run, retryExhausted: false };\n }\n\n let usage: ClaudeUsage | null = null;\n const outcome = await withRetry(() => invokeSelectedAgent(invocation), {\n policy: (failure) => resolvePolicy(failure.kind, config),\n signal: getShutdownSignal(),\n evaluate: (selected) => selected.failure,\n onAttempt: ({ value, failure, willRetry, delayMs, attempt }) => {\n if (value.run.usage !== null) usage = sumUsage(usage, value.run.usage);\n if (failure === null || !willRetry) return;\n getSessionPublisher().publish({\n type: 'retry',\n at: isoNow(),\n attempt,\n delaySeconds: delayMs / 1000,\n reason: failure.message,\n kind: failure.kind,\n });\n writeDiagnostic({\n level: 'warning',\n message: `Retrying ${invocation.phase} after ${failure.kind}`,\n context: { attempt, delayMs, reason: failure.message },\n fields: { phase: invocation.phase },\n });\n },\n });\n\n return {\n run: usage === null ? outcome.value.run : { ...outcome.value.run, usage },\n retryExhausted: outcome.exhausted,\n };\n}\n\n/**\n * Invoke the resolved agent in headless mode.\n *\n * Each invocation is an isolated session. UI (spinner, verbose header, activity)\n * stays here; argv and stream parsing belong to the runner.\n */\nexport async function runHeadless(options: HeadlessOptions): Promise<HeadlessResult> {\n const {\n prompt,\n maxTurns = 10,\n timeout: configuredTimeout = DEFAULT_HEADLESS_TIMEOUT_MS,\n outputFormat = 'json',\n allowedTools,\n addDirs,\n statusMessage,\n onOutput,\n phase = 'analyze',\n permission = 'workspace',\n forceProvider,\n purpose,\n correctionCycle,\n storyIds,\n } = options;\n const timeout = await escalatedTimeout(configuredTimeout, options.timeoutHistory);\n const settings = await resolveAgentFor(phase);\n\n const verbose = isVerbose();\n const effectiveOnOutput = onOutput ?? getOutputCallback();\n\n if (verbose) {\n const icons = getIcons();\n const colored = useColor();\n const emit = effectiveOnOutput ?? ((msg: string) => process.stdout.write(`${msg}\\n`));\n if (statusMessage) {\n const msg = colored\n ? chalk.blue(`${icons.start} ${statusMessage}`)\n : `${icons.start} ${statusMessage}`;\n emit(msg);\n }\n const connectorLine = colored ? chalk.dim(` ${icons.connector}`) : ` ${icons.connector}`;\n emit(connectorLine);\n\n const startTime = Date.now();\n const { run, retryExhausted } = await invokeHeadlessAgent({\n prompt,\n phase,\n addDirs,\n timeout,\n permission,\n maxTurns,\n allowedTools,\n ...(forceProvider === undefined ? {} : { forceProvider }),\n ...(purpose === undefined ? {} : { purpose }),\n ...(correctionCycle === undefined ? {} : { correctionCycle }),\n ...(storyIds === undefined ? {} : { storyIds }),\n onEvent: (event) => printAgentEvent(event, effectiveOnOutput),\n });\n\n const elapsedSec = Math.floor((Date.now() - startTime) / 1000);\n const durationStr = formatDuration(elapsedSec);\n const doneLine = colored\n ? chalk.dim(` ${icons.connector} ${chalk.italic(`Done in ${durationStr}`)}`)\n : ` ${icons.connector} Done in ${durationStr}`;\n emit(doneLine);\n emit(connectorLine);\n\n return mapHeadlessResult(run, outputFormat, retryExhausted);\n }\n\n const spinner = statusMessage ? createSpinner(statusMessage).start() : null;\n let timer: ElapsedTimer | null = null;\n if (spinner) {\n timer = new ElapsedTimer((elapsed) => {\n spinner.suffixText = useColor() ? chalk.dim(`(${elapsed})`) : `(${elapsed})`;\n }).start();\n }\n\n try {\n const { run, retryExhausted } = await invokeHeadlessAgent({\n prompt,\n phase,\n addDirs,\n timeout,\n permission,\n maxTurns,\n allowedTools,\n inactivityTimeoutMs: getInactivityTimeout(),\n ...(forceProvider === undefined ? {} : { forceProvider }),\n ...(purpose === undefined ? {} : { purpose }),\n ...(correctionCycle === undefined ? {} : { correctionCycle }),\n ...(storyIds === undefined ? {} : { storyIds }),\n onEvent: (event) => {\n if (event.kind === 'text') return;\n getSessionPublisher().publish({\n type: 'activity',\n at: isoNow(),\n tool: event.name,\n detail: event.detail,\n });\n getActivityCallback()?.({ tool: event.name, detail: event.detail });\n },\n });\n\n const elapsed = timer?.stop() ?? 0;\n const dur = useColor()\n ? chalk.dim(` (${formatDuration(elapsed)})`)\n : ` (${formatDuration(elapsed)})`;\n\n if (!run.success) {\n spinner?.fail(`${statusMessage}${dur}`);\n return mapHeadlessResult(run, outputFormat, retryExhausted);\n }\n\n spinner?.succeed(`${statusMessage}${dur}`);\n return mapHeadlessResult(run, outputFormat, retryExhausted);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const catchElapsed = timer?.stop() ?? 0;\n const catchDur = useColor()\n ? chalk.dim(` (${formatDuration(catchElapsed)})`)\n : ` (${formatDuration(catchElapsed)})`;\n spinner?.fail(`${statusMessage}${catchDur}`);\n return {\n success: false,\n result: '',\n cost: null,\n error: message,\n agent: { provider: settings.provider, model: settings.model },\n };\n }\n}\n\nfunction mapHeadlessResult(\n run: {\n success: boolean;\n result: string;\n rawOutput: string;\n usage: ClaudeUsage | null;\n error: string | null;\n agent: { provider: AgentProviderId; model: string | null };\n },\n outputFormat: 'json' | 'text' | 'stream-json',\n retryExhausted = false,\n): HeadlessResult {\n if (outputFormat === 'text') {\n return {\n success: run.success,\n result: run.success ? run.rawOutput || run.result : '',\n cost: null,\n error: run.error,\n agent: run.agent,\n ...(retryExhausted ? { retryExhausted: true } : {}),\n };\n }\n if (!run.success) {\n return {\n success: false,\n result: '',\n cost: null,\n error: run.error,\n agent: run.agent,\n ...(retryExhausted ? { retryExhausted: true } : {}),\n };\n }\n return {\n success: true,\n result: run.result,\n cost: run.usage,\n error: null,\n agent: run.agent,\n ...(retryExhausted ? { retryExhausted: true } : {}),\n };\n}\n","import type { CostRecord, StopReason } from '../telemetry/types.js';\n\nexport interface RoutingCeilings {\n maxCostUsdPerIssue: number | null;\n maxDurationMsPerIssue: number | null;\n maxExecutionsPerIssue: number | null;\n onCeiling: 'block';\n}\n\nexport const DEFAULT_CEILINGS: RoutingCeilings = {\n maxCostUsdPerIssue: null,\n maxDurationMsPerIssue: null,\n maxExecutionsPerIssue: null,\n onCeiling: 'block',\n};\n\nexport interface SpentSnapshot {\n /** Observed reported USD only. `unknown` / `estimated` do not fill this. */\n reportedUsd: number;\n costStatus: CostRecord['status'];\n durationMs: number;\n executions: number;\n}\n\nexport type CeilingBinding = 'cost' | 'duration' | 'executions';\n\nexport type CeilingVerdict =\n | { ok: true; binding: null }\n | {\n ok: false;\n stopReason: Extract<StopReason, 'max_cost' | 'max_duration' | 'max_attempts'>;\n binding: CeilingBinding;\n onCeiling: 'block';\n numbers: { spent: number; ceiling: number };\n /** Which ceiling is actually in force when cost is unknown. */\n enforced: CeilingBinding[];\n };\n\n/**\n * Single choke point. A harness flag is never a substitute: a runner that\n * ignores `--max-budget-usd` still stops here.\n */\nexport function evaluateCeilings(input: {\n ceilings?: Partial<RoutingCeilings> | undefined;\n spent: SpentSnapshot;\n}): CeilingVerdict {\n const ceilings = { ...DEFAULT_CEILINGS, ...input.ceilings };\n const enforced: CeilingBinding[] = [];\n if (ceilings.maxCostUsdPerIssue !== null && input.spent.costStatus === 'reported') {\n enforced.push('cost');\n }\n if (ceilings.maxDurationMsPerIssue !== null) enforced.push('duration');\n if (ceilings.maxExecutionsPerIssue !== null) enforced.push('executions');\n\n if (\n ceilings.maxCostUsdPerIssue !== null &&\n input.spent.costStatus === 'reported' &&\n input.spent.reportedUsd >= ceilings.maxCostUsdPerIssue\n ) {\n return {\n ok: false,\n stopReason: 'max_cost',\n binding: 'cost',\n onCeiling: 'block',\n numbers: { spent: input.spent.reportedUsd, ceiling: ceilings.maxCostUsdPerIssue },\n enforced,\n };\n }\n\n if (\n ceilings.maxDurationMsPerIssue !== null &&\n input.spent.durationMs >= ceilings.maxDurationMsPerIssue\n ) {\n return {\n ok: false,\n stopReason: 'max_duration',\n binding: 'duration',\n onCeiling: 'block',\n numbers: { spent: input.spent.durationMs, ceiling: ceilings.maxDurationMsPerIssue },\n enforced,\n };\n }\n\n if (\n ceilings.maxExecutionsPerIssue !== null &&\n input.spent.executions >= ceilings.maxExecutionsPerIssue\n ) {\n return {\n ok: false,\n stopReason: 'max_attempts',\n binding: 'executions',\n onCeiling: 'block',\n numbers: { spent: input.spent.executions, ceiling: ceilings.maxExecutionsPerIssue },\n enforced,\n };\n }\n\n return { ok: true, binding: null };\n}\n\nexport function spendFromCost(cost: CostRecord): Pick<SpentSnapshot, 'reportedUsd' | 'costStatus'> {\n if (cost.status === 'reported') {\n return { reportedUsd: cost.amount, costStatus: 'reported' };\n }\n return { reportedUsd: 0, costStatus: cost.status };\n}\n\n/** `blocked` is only left by a human — the machine never unblocks a ceiling. */\nexport function canLeaveBlocked(actor: string): boolean {\n return actor === 'human';\n}\n","import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport type { ClassifiedFailure, FailureKind } from '../resilience/errors.js';\nimport {\n getProviderHealthRepository,\n readStoredProvidersHealth,\n updateStoredProviderHealth,\n} from '../storage/db/repository.js';\nimport {\n type ProviderHealthRecord,\n type ProvidersHealth,\n providersHealthSchema,\n type ResilienceProvidersConfig,\n} from '../storage/schemas.js';\n\nexport const DEFAULT_PROVIDER_COOLDOWN_MS = 60_000;\nexport const DEFAULT_PROVIDER_MAX_COOLDOWN_MS = 30 * 60_000;\nexport const DEFAULT_PROVIDER_FAILURE_WINDOW_MS = 5 * 60_000;\nexport const DEFAULT_PROVIDER_FAILURES_TO_TRIP = 3;\n\nexport interface ProviderHealthOptions {\n now?: () => number;\n config?: ResilienceProvidersConfig;\n}\n\nexport interface ResolvedProviderHealthConfig {\n cooldownMs: number;\n maxCooldownMs: number;\n failureWindowMs: number;\n failuresToTrip: number;\n}\n\nexport function resolveProviderHealthConfig(\n config: ResilienceProvidersConfig = {},\n): ResolvedProviderHealthConfig {\n return {\n cooldownMs: Math.max(0, config.cooldownMs ?? DEFAULT_PROVIDER_COOLDOWN_MS),\n maxCooldownMs: Math.max(\n config.cooldownMs ?? DEFAULT_PROVIDER_COOLDOWN_MS,\n config.maxCooldownMs ?? DEFAULT_PROVIDER_MAX_COOLDOWN_MS,\n ),\n failureWindowMs: Math.max(1, config.failureWindowMs ?? DEFAULT_PROVIDER_FAILURE_WINDOW_MS),\n failuresToTrip: Math.max(\n 1,\n Math.trunc(config.failuresToTrip ?? DEFAULT_PROVIDER_FAILURES_TO_TRIP),\n ),\n };\n}\n\nfunction emptyHealth(): ProvidersHealth {\n return providersHealthSchema.parse({});\n}\n\nfunction emptyRecord(): ProviderHealthRecord {\n return providersHealthSchema.parse({ providers: { provider: {} } }).providers.provider;\n}\n\nexport async function readProvidersHealth(filePath: string): Promise<ProvidersHealth> {\n const repository = getProviderHealthRepository(filePath);\n if (repository !== undefined) return readStoredProvidersHealth(repository);\n try {\n return providersHealthSchema.parse(JSON.parse(await readFile(filePath, 'utf-8')));\n } catch {\n return emptyHealth();\n }\n}\n\nasync function writeProvidersHealth(filePath: string, value: ProvidersHealth): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n const tmp = `${filePath}.tmp-${process.pid}`;\n await writeFile(tmp, `${JSON.stringify(value, null, 2)}\\n`, 'utf-8');\n await rename(tmp, filePath);\n}\n\nasync function updateRecord(\n filePath: string,\n provider: string,\n update: (record: ProviderHealthRecord) => ProviderHealthRecord,\n): Promise<ProviderHealthRecord> {\n const repository = getProviderHealthRepository(filePath);\n if (repository !== undefined) {\n return updateStoredProviderHealth(repository, provider, update);\n }\n const health = await readProvidersHealth(filePath);\n const next = update(health.providers[provider] ?? emptyRecord());\n await writeProvidersHealth(filePath, {\n ...health,\n providers: { ...health.providers, [provider]: next },\n });\n return next;\n}\n\nfunction cooldownDelay(level: number, config: ResolvedProviderHealthConfig): number {\n return Math.min(config.maxCooldownMs, config.cooldownMs * 2 ** Math.max(0, level));\n}\n\nconst BREAKER_KINDS = new Set<FailureKind>([\n 'timeout',\n 'stalled',\n 'provider_down',\n 'provider_crash',\n]);\n\nexport async function recordProviderFailure(\n filePath: string,\n provider: string,\n failure: ClassifiedFailure,\n options: ProviderHealthOptions = {},\n): Promise<ProviderHealthRecord> {\n const nowMs = options.now?.() ?? Date.now();\n const at = new Date(nowMs).toISOString();\n const config = resolveProviderHealthConfig(options.config);\n\n return updateRecord(filePath, provider, (record) => {\n const failures = [\n ...record.failures.filter((entry) => {\n const timestamp = Date.parse(entry.at);\n return Number.isFinite(timestamp) && nowMs - timestamp <= config.failureWindowMs;\n }),\n { at, kind: failure.kind },\n ];\n const consecutiveFailures = record.consecutiveFailures + 1;\n\n if (failure.kind === 'authentication') {\n return {\n ...record,\n status: 'auth_failed',\n failures,\n consecutiveFailures,\n cooldownUntil: null,\n lastFailureKind: failure.kind,\n lastFailureAt: at,\n probeInFlight: false,\n probeStartedAt: null,\n };\n }\n\n if (failure.kind === 'rate_limit') {\n const delay = failure.retryAfterMs ?? cooldownDelay(record.cooldownLevel, config);\n return {\n ...record,\n status: 'rate_limited',\n failures,\n consecutiveFailures,\n cooldownLevel:\n failure.retryAfterMs === undefined ? record.cooldownLevel + 1 : record.cooldownLevel,\n cooldownUntil: new Date(nowMs + delay).toISOString(),\n lastFailureKind: failure.kind,\n lastFailureAt: at,\n probeInFlight: false,\n probeStartedAt: null,\n };\n }\n\n if (BREAKER_KINDS.has(failure.kind)) {\n const recentProviderFailures = failures.filter((entry) =>\n BREAKER_KINDS.has(entry.kind),\n ).length;\n const unavailable =\n record.status === 'half_open' || recentProviderFailures >= config.failuresToTrip;\n const delay = unavailable ? cooldownDelay(record.cooldownLevel, config) : 0;\n return {\n ...record,\n status: unavailable ? 'unavailable' : 'degraded',\n failures,\n consecutiveFailures,\n cooldownLevel: unavailable ? record.cooldownLevel + 1 : record.cooldownLevel,\n cooldownUntil: unavailable ? new Date(nowMs + delay).toISOString() : null,\n lastFailureKind: failure.kind,\n lastFailureAt: at,\n probeInFlight: false,\n probeStartedAt: null,\n };\n }\n\n // Network and task/repository/configuration failures do not describe the\n // provider's health. Keep the breaker state, but retain the diagnosis for\n // audit and dashboard surfaces.\n return {\n ...record,\n lastFailureKind: failure.kind,\n lastFailureAt: at,\n probeInFlight: false,\n probeStartedAt: null,\n };\n });\n}\n\nexport async function recordProviderSuccess(\n filePath: string,\n provider: string,\n options: Pick<ProviderHealthOptions, 'now'> = {},\n): Promise<ProviderHealthRecord> {\n const at = new Date(options.now?.() ?? Date.now()).toISOString();\n return updateRecord(filePath, provider, (record) => ({\n ...record,\n status: 'healthy',\n failures: [],\n consecutiveFailures: 0,\n cooldownLevel: 0,\n cooldownUntil: null,\n lastFailureKind: null,\n lastSuccessAt: at,\n probeInFlight: false,\n probeStartedAt: null,\n }));\n}\n\n/** Open the circuit when retry policy asks for failover before the trip count. */\nexport async function openProviderCircuit(\n filePath: string,\n provider: string,\n options: ProviderHealthOptions = {},\n): Promise<ProviderHealthRecord> {\n const nowMs = options.now?.() ?? Date.now();\n const config = resolveProviderHealthConfig(options.config);\n return updateRecord(filePath, provider, (record) => {\n if (record.status === 'unavailable' || record.status === 'rate_limited') return record;\n const delay = cooldownDelay(record.cooldownLevel, config);\n return {\n ...record,\n status: 'unavailable',\n cooldownLevel: record.cooldownLevel + 1,\n cooldownUntil: new Date(nowMs + delay).toISOString(),\n probeInFlight: false,\n probeStartedAt: null,\n };\n });\n}\n\nexport interface HalfOpenResult {\n acquired: boolean;\n record: ProviderHealthRecord;\n}\n\n/** Atomically enough for the project-level single-run lock: one half-open probe per provider. */\nexport async function acquireHalfOpenProbe(\n filePath: string,\n provider: string,\n options: ProviderHealthOptions = {},\n): Promise<HalfOpenResult> {\n const nowMs = options.now?.() ?? Date.now();\n const at = new Date(nowMs).toISOString();\n const config = resolveProviderHealthConfig(options.config);\n let acquired = false;\n const record = await updateRecord(filePath, provider, (current) => {\n const cooldownUntil = current.cooldownUntil === null ? 0 : Date.parse(current.cooldownUntil);\n if (Number.isFinite(cooldownUntil) && cooldownUntil > nowMs) return current;\n\n const probeStarted = current.probeStartedAt === null ? 0 : Date.parse(current.probeStartedAt);\n const probeIsFresh =\n current.probeInFlight &&\n Number.isFinite(probeStarted) &&\n nowMs - probeStarted < config.cooldownMs;\n if (probeIsFresh) return current;\n\n acquired = true;\n return {\n ...current,\n status: 'half_open',\n cooldownUntil: null,\n probeInFlight: true,\n probeStartedAt: at,\n };\n });\n return { acquired, record };\n}\n","import type { RoutingDecision } from '../routing/types.js';\nimport type { AgentAvailability } from './availability.js';\nimport { probeAgent } from './availability.js';\nimport { runnerFor } from './registry.js';\nimport type { AgentSelection } from './select.js';\nimport type { AgentPhase, AgentProviderId } from './types.js';\nimport { isAgentProviderId } from './types.js';\n\nexport interface RoutingApplicationResult {\n selection: AgentSelection;\n applied: boolean;\n warning: string | null;\n /** Candidates tried before the applied (or final failed) target. */\n fallbackFrom: Array<{ provider: string; model: string | null; reason: string }>;\n}\n\nexport function routingRecommendationLine(\n decision: RoutingDecision | null,\n phase: AgentPhase,\n): string | null {\n if (\n decision === null ||\n decision.mode !== 'recommend' ||\n decision.reasonCodes.includes('EXPLICIT_CONFIG')\n ) {\n return null;\n }\n const tier = decision.selected.tier ? ` (${decision.selected.tier})` : '';\n return `Routing suggests ${decision.selected.provider}:${decision.selected.model ?? 'default'}${tier} for ${phase} (${decision.reasonCodes.join(', ')}) · apply with routing.mode active`;\n}\n\nfunction isAttemptable(availability: AgentAvailability): boolean {\n return (\n availability.installed &&\n availability.authentication !== 'failed' &&\n availability.state !== 'unavailable'\n );\n}\n\n/**\n * Apply an active decision without changing invocation permission. Walks the\n * ranked eligible list when the top target is unavailable; explicit config is\n * never overridden. Fail-open to the original selection when nothing works.\n */\nexport async function applyRoutingDecision(\n original: AgentSelection,\n decision: RoutingDecision | null,\n phase: AgentPhase,\n options: { probe?: (provider: AgentProviderId) => Promise<AgentAvailability> } = {},\n): Promise<RoutingApplicationResult> {\n if (\n decision === null ||\n decision.mode !== 'active' ||\n decision.reasonCodes.includes('EXPLICIT_CONFIG') ||\n original.failover\n ) {\n return { selection: original, applied: false, warning: null, fallbackFrom: [] };\n }\n\n const probe = options.probe ?? probeAgent;\n const ranked = decision.candidates\n .filter((candidate) => candidate.eligible)\n .sort((a, b) => b.score - a.score);\n const fallbackFrom: RoutingApplicationResult['fallbackFrom'] = [];\n\n for (const candidate of ranked) {\n if (!isAgentProviderId(candidate.provider)) {\n fallbackFrom.push({\n provider: candidate.provider,\n model: candidate.model ?? null,\n reason: 'unregistered provider',\n });\n continue;\n }\n if (\n candidate.model !== null &&\n candidate.model !== undefined &&\n !runnerFor(candidate.provider).capabilities.modelSelection\n ) {\n fallbackFrom.push({\n provider: candidate.provider,\n model: candidate.model,\n reason: 'rejects model selection',\n });\n continue;\n }\n\n const availability = await probe(candidate.provider);\n if (!isAttemptable(availability)) {\n fallbackFrom.push({\n provider: candidate.provider,\n model: candidate.model ?? null,\n reason: availability.installed\n ? availability.authentication === 'failed'\n ? 'not authenticated'\n : `state=${availability.state}`\n : 'not installed',\n });\n continue;\n }\n\n const warning =\n fallbackFrom.length > 0\n ? `Routing fell back to ${candidate.provider}:${candidate.model ?? 'default'} for ${phase} after ${fallbackFrom.map((entry) => `${entry.provider} (${entry.reason})`).join(', ')}.`\n : null;\n\n return {\n applied: true,\n warning,\n fallbackFrom,\n selection: {\n ...original,\n primary: candidate.provider,\n provider: candidate.provider,\n settings: {\n ...original.settings,\n provider: candidate.provider,\n model: candidate.model ?? null,\n origin: { provider: 'default', model: 'default' },\n },\n failover: false,\n reason: null,\n cooldownUntil: null,\n },\n };\n }\n\n const tried =\n fallbackFrom.length > 0\n ? fallbackFrom.map((entry) => `${entry.provider} (${entry.reason})`).join(', ')\n : 'no eligible candidates';\n return {\n selection: original,\n applied: false,\n fallbackFrom,\n warning: `Routing found no usable ranked target for ${phase} (${tried}); using ${original.provider}.`,\n };\n}\n","import { getActiveResilienceConfig } from '../config.js';\nimport { getShutdownSignal } from '../core/shutdown.js';\nimport type { FailureKind } from '../resilience/errors.js';\nimport { abortableDelay, resolvePolicy, shouldFailover } from '../resilience/policy.js';\nimport { resolveProjectPaths } from '../storage/resolve.js';\nimport type { ProviderHealthRecord, ResilienceConfig } from '../storage/schemas.js';\nimport {\n acquireHalfOpenProbe,\n openProviderCircuit,\n readProvidersHealth,\n resolveProviderHealthConfig,\n} from './health.js';\nimport { ensureRunnersRegistered, getRegisteredProviders } from './registry.js';\nimport { resolveAgentFor } from './resolve.js';\nimport {\n type AgentPhase,\n type AgentProviderId,\n isAgentProviderId,\n type ResolvedAgentSettings,\n} from './types.js';\n\nexport interface AgentSelection {\n primary: AgentProviderId;\n provider: AgentProviderId;\n settings: ResolvedAgentSettings;\n healthFile: string | null;\n failover: boolean;\n reason: FailureKind | null;\n cooldownUntil: string | null;\n}\n\nexport class AgentSelectionBlockedError extends Error {\n readonly provider: AgentProviderId;\n readonly kind: FailureKind;\n\n constructor(provider: AgentProviderId, kind: FailureKind) {\n super(\n `Authentication failed for agent provider '${provider}' (${kind}); the run is blocked. Authenticate or repair that provider before resuming.`,\n );\n this.name = 'AgentSelectionBlockedError';\n this.provider = provider;\n this.kind = kind;\n }\n}\n\ninterface CandidateVerdict {\n available: boolean;\n waitMs: number | null;\n cooldownUntil: string | null;\n reason: FailureKind | null;\n blocked: boolean;\n}\n\nfunction remainingMs(until: string | null, nowMs: number): number | null {\n if (until === null) return null;\n const parsed = Date.parse(until);\n return Number.isFinite(parsed) ? Math.max(0, parsed - nowMs) : null;\n}\n\nfunction failoverIsDue(\n record: ProviderHealthRecord | undefined,\n config: ResilienceConfig,\n): boolean {\n if (record?.lastFailureKind == null) return false;\n return shouldFailover(resolvePolicy(record.lastFailureKind, config), record.consecutiveFailures);\n}\n\nasync function verdictFor(\n provider: AgentProviderId,\n record: ProviderHealthRecord | undefined,\n options: {\n healthFile: string;\n config: ResilienceConfig;\n primary: boolean;\n nowMs: number;\n },\n): Promise<CandidateVerdict> {\n if (record === undefined || record.status === 'healthy') {\n return { available: true, waitMs: null, cooldownUntil: null, reason: null, blocked: false };\n }\n\n const reason = record.lastFailureKind;\n if (record.status === 'auth_failed') {\n const mayFailover = reason !== null && failoverIsDue(record, options.config);\n return {\n available: false,\n waitMs: null,\n cooldownUntil: null,\n reason,\n blocked: options.primary && !mayFailover,\n };\n }\n\n if (record.status === 'degraded') {\n const due = failoverIsDue(record, options.config);\n const opened = due\n ? await openProviderCircuit(options.healthFile, provider, {\n now: () => options.nowMs,\n config: options.config.providers,\n })\n : record;\n return {\n available: !due,\n waitMs: due ? remainingMs(opened.cooldownUntil, options.nowMs) : null,\n cooldownUntil: opened.cooldownUntil,\n reason,\n blocked: false,\n };\n }\n\n // `half_open` joins the two closed states on purpose: `acquireHalfOpenProbe`\n // is the only place that knows a probe went stale, and a record left\n // `probeInFlight` by a SIGKILLed run is otherwise never reclaimed — the next\n // run just waits on a cooldown that never ends.\n if (\n record.status === 'unavailable' ||\n record.status === 'rate_limited' ||\n record.status === 'half_open'\n ) {\n const waitMs = remainingMs(record.cooldownUntil, options.nowMs);\n if (waitMs !== null && waitMs > 0) {\n return {\n available: false,\n waitMs,\n cooldownUntil: record.cooldownUntil,\n reason,\n blocked: false,\n };\n }\n const probe = await acquireHalfOpenProbe(options.healthFile, provider, {\n now: () => options.nowMs,\n config: options.config.providers,\n });\n return {\n available: probe.acquired,\n waitMs: probe.acquired\n ? null\n : resolveProviderHealthConfig(options.config.providers).cooldownMs,\n cooldownUntil: probe.record.cooldownUntil,\n reason,\n blocked: false,\n };\n }\n\n return { available: true, waitMs: null, cooldownUntil: null, reason, blocked: false };\n}\n\nfunction providerOrder(primary: AgentProviderId, config: ResilienceConfig): AgentProviderId[] {\n ensureRunnersRegistered();\n const registered = getRegisteredProviders();\n const configured = (config.providers?.chain ?? []).filter(isAgentProviderId);\n return [...new Set([primary, ...configured, ...registered])];\n}\n\nfunction settingsFor(\n base: ResolvedAgentSettings,\n provider: AgentProviderId,\n): ResolvedAgentSettings {\n if (provider === base.provider) return base;\n return {\n ...base,\n provider,\n // A model name belongs to the configured primary unless the selected\n // provider is that primary. Passing a Claude alias to Codex (or vice\n // versa) is less useful than letting the fallback use its own default.\n model: null,\n };\n}\n\n/**\n * Select one provider. When every provider is cooling down, wait for the\n * earliest circuit instead of turning a temporary absence into a failed run.\n */\nexport async function selectAgentForInvocation(\n phase: AgentPhase,\n options: {\n config?: ResilienceConfig;\n now?: () => number;\n delay?: (ms: number, options: { signal?: AbortSignal }) => Promise<boolean>;\n } = {},\n): Promise<AgentSelection> {\n const config = options.config ?? getActiveResilienceConfig();\n const base = await resolveAgentFor(phase);\n const failover = config.providers?.failover === true;\n if (!failover) {\n return {\n primary: base.provider,\n provider: base.provider,\n settings: base,\n healthFile: null,\n failover: false,\n reason: null,\n cooldownUntil: null,\n };\n }\n\n let healthFile: string;\n try {\n healthFile = (await resolveProjectPaths()).providersHealthFile;\n } catch {\n return {\n primary: base.provider,\n provider: base.provider,\n settings: base,\n healthFile: null,\n failover: true,\n reason: null,\n cooldownUntil: null,\n };\n }\n\n const delay = options.delay ?? abortableDelay;\n selection: for (;;) {\n const nowMs = options.now?.() ?? Date.now();\n const health = await readProvidersHealth(healthFile);\n const waits: number[] = [];\n let primaryReason: FailureKind | null = null;\n let primaryCooldown: string | null = null;\n\n for (const provider of providerOrder(base.provider, config)) {\n const verdict = await verdictFor(provider, health.providers[provider], {\n healthFile,\n config,\n primary: provider === base.provider,\n nowMs,\n });\n if (provider === base.provider) {\n primaryReason = verdict.reason;\n primaryCooldown = verdict.cooldownUntil;\n }\n if (verdict.blocked && verdict.reason !== null) {\n throw new AgentSelectionBlockedError(provider, verdict.reason);\n }\n if (\n provider === base.provider &&\n !verdict.available &&\n verdict.waitMs !== null &&\n !failoverIsDue(health.providers[provider], config)\n ) {\n if (!(await delay(Math.max(1, verdict.waitMs), { signal: getShutdownSignal() }))) {\n throw new Error('Agent provider selection was interrupted while waiting for cooldown.');\n }\n continue selection;\n }\n if (verdict.available) {\n return {\n primary: base.provider,\n provider,\n settings: settingsFor(base, provider),\n healthFile,\n failover: provider !== base.provider,\n reason: provider === base.provider ? null : primaryReason,\n cooldownUntil: primaryCooldown,\n };\n }\n if (verdict.waitMs !== null) waits.push(verdict.waitMs);\n }\n\n const waitMs = waits.length > 0 ? Math.max(1, Math.min(...waits)) : null;\n if (waitMs === null) {\n throw new Error(\n 'No healthy agent provider is available and none has a cooldown to wait for.',\n );\n }\n if (!(await delay(waitMs, { signal: getShutdownSignal() }))) {\n throw new Error('Agent provider selection was interrupted while waiting for cooldown.');\n }\n }\n}\n","import {\n getActiveResilienceConfig,\n getAgentCliOverrides,\n loadAgentConfig,\n loadRoutingConfig,\n} from '../config.js';\nimport { getSessionPublisher } from '../core/session-publisher.js';\nimport { isoNow } from '../core/state-manager.js';\nimport { type ClassifiedFailure, classify, type FailureKind } from '../resilience/errors.js';\nimport { evaluateCeilings } from '../routing/budget.js';\nimport { decideRouting } from '../routing/decide.js';\nimport { bindDiagnosticContext, writeDiagnostic } from '../storage/diagnostics.js';\nimport type { ProviderHealthRecord } from '../storage/schemas.js';\nimport { beginExecution, endExecution } from '../telemetry/recorder.js';\nimport { redactSecrets } from '../telemetry/redact.js';\nimport type { ExecutionPurpose, ExecutionRecord, ExecutionTrigger } from '../telemetry/types.js';\nimport { printInfo } from '../ui/logger.js';\nimport { resolveAntigravityTimeoutMs } from './antigravity.js';\nimport { probeReadinessInventory } from './availability.js';\nimport { peekHarnessVersion } from './claude.js';\nimport { recordProviderFailure, recordProviderSuccess } from './health.js';\nimport { ensureCursorStorageGrant } from './permissions.js';\nimport { runnerFor } from './registry.js';\nimport { hasExplicitAgentSelection, resolveAgentFor } from './resolve.js';\nimport { applyRoutingDecision, routingRecommendationLine } from './routing-application.js';\nimport { type AgentSelection, selectAgentForInvocation } from './select.js';\nimport type { AgentInvocation, AgentProviderId, AgentRunResult } from './types.js';\n\nasync function selectionForForced(invocation: AgentInvocation): Promise<AgentSelection> {\n const settings = await resolveAgentFor(invocation.phase, {\n cli: { forceProvider: invocation.forceProvider },\n });\n return {\n primary: settings.provider,\n provider: settings.provider,\n settings,\n healthFile: null,\n failover: false,\n reason: null,\n cooldownUntil: null,\n };\n}\n\nconst attempts = new Map<string, number>();\nconst lastFailure = new Map<string, FailureKind>();\nconst issueSpend = {\n reportedUsd: 0,\n durationMs: 0,\n executions: 0,\n sawReported: false,\n};\n\n/** Declared identity of a runner — never inferred from argv or logs. */\nexport function declaredAgentIdentity(provider: AgentProviderId): {\n harness: string;\n vendor: string;\n} {\n switch (provider) {\n case 'claude':\n return { harness: 'claude-code', vendor: 'anthropic' };\n case 'codex':\n return { harness: 'codex-cli', vendor: 'openai' };\n case 'cursor':\n return { harness: 'cursor-cli', vendor: 'cursor' };\n case 'antigravity':\n return { harness: 'antigravity-cli', vendor: 'google' };\n default: {\n const _exhaustive: never = provider;\n return _exhaustive;\n }\n }\n}\n\nfunction triggerOf(\n selection: AgentSelection,\n attempt: number,\n correctionCycle = 0,\n): ExecutionTrigger {\n if (selection.failover) return 'fallback';\n if (attempt > 1) return 'retry';\n if (correctionCycle > 0) return 'correction';\n return 'initial';\n}\n\nexport interface SelectedAgentRun {\n run: AgentRunResult;\n failure: ClassifiedFailure | null;\n selection: AgentSelection;\n attempt: number;\n health: ProviderHealthRecord | null;\n blocked?: { stopReason: string; detail: string; actor: 'human' };\n}\n\nfunction nextAttempt(phase: string): number {\n const attempt = (attempts.get(phase) ?? 0) + 1;\n attempts.set(phase, attempt);\n return attempt;\n}\n\nexport function resetAgentInvocationState(): void {\n attempts.clear();\n lastFailure.clear();\n issueSpend.reportedUsd = 0;\n issueSpend.durationMs = 0;\n issueSpend.executions = 0;\n issueSpend.sawReported = false;\n}\n\n/** One invocation, including provider selection, health persistence and audit events. */\nexport async function invokeSelectedAgent(invocation: AgentInvocation): Promise<SelectedAgentRun> {\n const config = getActiveResilienceConfig();\n let selection =\n invocation.forceProvider === undefined\n ? await selectAgentForInvocation(invocation.phase, { config })\n : await selectionForForced(invocation);\n const originalIdentity = declaredAgentIdentity(selection.provider);\n const routingCfg = await loadRoutingConfig();\n const agentCfg = await loadAgentConfig();\n let readiness = null;\n if (routingCfg.mode === 'recommend' || routingCfg.mode === 'active') {\n try {\n readiness = await probeReadinessInventory({\n cooldowns: selection.cooldownUntil\n ? { [selection.provider]: selection.cooldownUntil }\n : undefined,\n });\n } catch {\n // Inventory is best-effort. A probe failure must not block the run —\n // decideRouting falls back to catalog-only scoring.\n readiness = null;\n }\n }\n const routingDecision = decideRouting({\n phase: invocation.phase,\n actualHarness: originalIdentity.harness,\n actualProvider: selection.provider,\n actualModel: selection.settings.model,\n mode: routingCfg.mode,\n profile: routingCfg.profile,\n policy: routingCfg.policy,\n skipScore: hasExplicitAgentSelection(agentCfg, getAgentCliOverrides(), invocation.phase),\n requiresExtraDirectories: (invocation.addDirs?.length ?? 0) > 0,\n readiness,\n });\n const recommendation = routingRecommendationLine(routingDecision, invocation.phase);\n if (recommendation !== null) printInfo(recommendation);\n const routed = await applyRoutingDecision(selection, routingDecision, invocation.phase);\n selection = routed.selection;\n if (routed.warning !== null) {\n writeDiagnostic({\n level: 'warning',\n message: routed.warning,\n context: { fallbackFrom: routed.fallbackFrom },\n fields: {\n phase: invocation.phase,\n harness: originalIdentity.harness,\n model: selection.settings.model,\n },\n });\n }\n const attempt = nextAttempt(invocation.phase);\n const publisher = getSessionPublisher();\n publisher.publish({\n type: 'agent:attempt',\n at: isoNow(),\n attempt,\n provider: selection.provider,\n model: selection.settings.model,\n primaryProvider: selection.primary,\n });\n if (selection.failover) {\n publisher.publish({\n type: 'failover',\n at: isoNow(),\n from: selection.primary,\n to: selection.provider,\n reason: selection.reason,\n cooldownUntil: selection.cooldownUntil,\n });\n writeDiagnostic({\n level: 'warning',\n message: `Agent failover from ${selection.primary} to ${selection.provider}`,\n context: { reason: selection.reason, cooldownUntil: selection.cooldownUntil },\n fields: {\n phase: invocation.phase,\n harness: selection.provider,\n model: selection.settings.model,\n },\n });\n }\n\n const identity = declaredAgentIdentity(selection.provider);\n const requested = selection.settings.model;\n const recordedRoutingDecision =\n routingDecision !== null && routed.applied\n ? {\n ...routingDecision,\n actual: {\n harness: identity.harness,\n provider: selection.provider,\n model: requested,\n },\n }\n : routingDecision;\n const executionId = await beginExecution({\n purpose: (invocation.purpose ?? invocation.phase) as ExecutionPurpose,\n attempt,\n trigger: triggerOf(selection, attempt, invocation.correctionCycle),\n triggerReason: selection.failover\n ? selection.reason\n : attempt > 1\n ? (lastFailure.get(invocation.phase) ?? null)\n : null,\n harness: identity.harness,\n provider: identity.vendor,\n harnessVersion: peekHarnessVersion(selection.provider) ?? null,\n modelRequested: requested,\n modelResolved: null,\n modelSource: requested ? (routed.applied ? 'routing' : 'config') : 'unavailable',\n ...(invocation.iteration === undefined ? {} : { iteration: invocation.iteration }),\n ...(invocation.correctionCycle === undefined\n ? {}\n : { correctionCycle: invocation.correctionCycle }),\n ...(invocation.storyIds === undefined ? {} : { storyIds: invocation.storyIds }),\n ...(recordedRoutingDecision === null\n ? {}\n : {\n routingDecision: recordedRoutingDecision as unknown as ExecutionRecord['routingDecision'],\n }),\n });\n bindDiagnosticContext({\n executionId,\n phase: invocation.phase,\n harness: identity.harness,\n model: requested,\n story: invocation.storyIds?.join(',') ?? null,\n });\n\n const runner = runnerFor(selection.provider);\n const ceiling = evaluateCeilings({\n ceilings: routingCfg.ceilings,\n spent: {\n reportedUsd: issueSpend.reportedUsd,\n costStatus: issueSpend.sawReported ? 'reported' : 'unknown',\n durationMs: issueSpend.durationMs,\n executions: issueSpend.executions,\n },\n });\n if (!ceiling.ok) {\n const detail = `blocked by ${ceiling.binding} ceiling (${ceiling.numbers.spent} ≥ ${ceiling.numbers.ceiling}). Enforced by Issue Flow, not by a harness flag.`;\n const run = {\n success: false,\n result: '',\n rawOutput: detail,\n exitCode: 1,\n usage: null,\n error: detail,\n agent: { provider: selection.provider, model: selection.settings.model },\n harnessVersion: peekHarnessVersion(selection.provider),\n };\n if (executionId !== null) {\n await endExecution({\n id: executionId,\n status: 'failed',\n error: detail,\n exitCode: 1,\n stopReason: ceiling.stopReason,\n });\n }\n return {\n run,\n failure: null,\n selection,\n attempt,\n health: null,\n blocked: { stopReason: ceiling.stopReason, detail, actor: 'human' },\n };\n }\n if (\n runner.capabilities.nativeTimeout &&\n invocation.timeout === 0 &&\n resolveAntigravityTimeoutMs(invocation, selection.settings) === null\n ) {\n const run = {\n success: false,\n result: '',\n rawOutput:\n 'configuration: provider has nativeTimeout and received timeout: 0 without a ceiling.',\n exitCode: 1,\n usage: null,\n error:\n 'configuration: provider has nativeTimeout and received timeout: 0 without a ceiling. Set agent.antigravity.executeTimeout.',\n agent: { provider: selection.provider, model: selection.settings.model },\n harnessVersion: peekHarnessVersion(selection.provider),\n };\n if (executionId !== null) {\n await endExecution({\n id: executionId,\n status: 'failed',\n error: run.error,\n exitCode: 1,\n });\n }\n const failure = classify({ source: 'agent', exitCode: 1, stdout: run.error });\n return { run, failure, selection, attempt, health: null };\n }\n if (\n (invocation.addDirs?.length ?? 0) > 0 &&\n runner.capabilities.extraDirectories === 'permission-file'\n ) {\n const grant =\n selection.settings.cursor.permissionsFile === 'none'\n ? { skipped: true as const, reason: 'none' as const }\n : await ensureCursorStorageGrant({\n mode: selection.settings.cursor.permissionsFile ?? 'global',\n });\n if ('skipped' in grant && selection.settings.cursor.permissionsFile !== 'none') {\n throw new Error(\n `Phase '${invocation.phase}' needs extraDirectories on '${selection.provider}', which only grants them via a permission file. Run \\`issue-flow agent use cursor\\` or set agent.cursor.permissionsFile.`,\n );\n }\n } else if (\n (invocation.addDirs?.length ?? 0) > 0 &&\n runner.capabilities.extraDirectories === 'none'\n ) {\n throw new Error(\n `Phase '${invocation.phase}' needs extraDirectories, but '${selection.provider}' cannot grant them.`,\n );\n }\n\n let run: AgentRunResult;\n const startedMs = Date.now();\n try {\n run = await runner.run(\n {\n ...invocation,\n onLine: (line) => {\n const sanitized = redactSecrets(line).slice(0, 4_000);\n publisher.publish({\n type: 'agent:activity',\n at: isoNow(),\n provider: selection.provider,\n });\n if (sanitized.trim() !== '') {\n publisher.publish({\n type: 'process:output',\n at: isoNow(),\n phase: invocation.phase,\n executionId,\n provider: selection.provider,\n stream: 'combined',\n message: sanitized,\n });\n writeDiagnostic({\n level: 'debug',\n message: sanitized,\n fields: {\n executionId,\n phase: invocation.phase,\n harness: identity.harness,\n model: selection.settings.model,\n },\n });\n }\n invocation.onLine?.(line);\n },\n },\n selection.settings,\n );\n } catch (err) {\n writeDiagnostic({\n level: 'error',\n message: `Agent invocation threw before producing a result: ${\n err instanceof Error ? err.message : String(err)\n }`,\n exception: err,\n fields: {\n executionId,\n phase: invocation.phase,\n harness: identity.harness,\n model: selection.settings.model,\n },\n });\n if (executionId !== null) {\n await endExecution({\n id: executionId,\n status: 'failed',\n error: err instanceof Error ? err.message : String(err),\n });\n }\n throw err;\n }\n issueSpend.executions += 1;\n issueSpend.durationMs += Math.max(0, Date.now() - startedMs);\n if (run.usage?.costUsd !== undefined) {\n issueSpend.reportedUsd += run.usage.costUsd;\n issueSpend.sawReported = true;\n }\n\n const failure =\n run.success && run.exitCode === 0\n ? null\n : classify({\n source: 'agent',\n exitCode: run.exitCode,\n stdout: run.rawOutput || run.error || '',\n });\n writeDiagnostic({\n level: failure === null ? 'info' : 'error',\n message:\n failure === null\n ? `Agent invocation completed with ${selection.provider}`\n : `Agent invocation failed with ${selection.provider}: ${failure.message}`,\n context: {\n attempt,\n exitCode: run.exitCode,\n failureKind: failure?.kind ?? null,\n trigger: triggerOf(selection, attempt, invocation.correctionCycle),\n },\n fields: {\n executionId,\n phase: invocation.phase,\n harness: identity.harness,\n model: run.agent.model,\n },\n });\n\n if (executionId !== null) {\n await endExecution({\n id: executionId,\n status: failure === null ? 'completed' : failure.kind === 'timeout' ? 'timeout' : 'failed',\n usage: run.usage,\n error: failure === null ? null : (run.error ?? run.rawOutput),\n exitCode: run.exitCode,\n modelResolved: run.agent.model,\n modelSource: run.agent.model\n ? requested\n ? routed.applied\n ? 'routing'\n : 'config'\n : 'provider'\n : requested\n ? routed.applied\n ? 'routing'\n : 'config'\n : 'unavailable',\n harnessVersion: run.harnessVersion ?? peekHarnessVersion(selection.provider) ?? null,\n providerSessionId: run.sessionId ?? null,\n storyIds: invocation.storyIds,\n });\n }\n\n if (failure === null) lastFailure.delete(invocation.phase);\n else lastFailure.set(invocation.phase, failure.kind);\n\n let health: ProviderHealthRecord | null = null;\n if (selection.healthFile !== null) {\n health =\n failure === null\n ? await recordProviderSuccess(selection.healthFile, selection.provider)\n : await recordProviderFailure(selection.healthFile, selection.provider, failure, {\n config: config.providers,\n });\n }\n\n publisher.publish({\n type: 'agent:result',\n at: isoNow(),\n provider: selection.provider,\n success: failure === null,\n ...(failure === null ? {} : { failureKind: failure.kind }),\n cooldownUntil: health?.cooldownUntil ?? null,\n });\n\n if (failure === null) attempts.delete(invocation.phase);\n return { run, failure, selection, attempt, health };\n}\n","import type { TaskPlan, UserStory } from '../types.js';\nimport { parseJournal } from './journal.js';\n\n/**\n * \"This issue is too large\" — detected, reported, and left to a person.\n *\n * A phase that keeps timing out, a plan with thirty stories, five iterations in\n * a row that finish nothing: each of those is ambiguous on its own, and any one\n * of them can also be a slow afternoon. Together they are the same thing said\n * three ways, and what they are saying is that the demand was never one issue.\n *\n * The tool's job here stops at saying so. **Splitting an issue is a product\n * decision**, and the default is a report plus `blocked`, not an act — which is\n * also why a failure that is merely *infrastructural* must never reach this\n * code path: an issue whose run died because the network went down is not too\n * large, and breaking it up would be the worst possible response.\n */\n\n/** The thresholds, in one place, because every one of them is a judgement. */\nexport const DECOMPOSITION_THRESHOLDS = {\n /** Timeouts on the same phase. Two is already a pattern, not bad luck. */\n timeoutsPerPhase: 2,\n /** Stories in the plan. Past this, the plan is a backlog. */\n stories: 15,\n /** Iterations in a row that completed no story. */\n barrenIterations: 5,\n /** Files touched on the branch. */\n filesTouched: 40,\n /** Characters in the issue body. */\n issueBodyChars: 20_000,\n} as const;\n\n/** How many signals have to agree before the report is written. */\nexport const DECOMPOSITION_MIN_SIGNALS = 2;\n\nexport interface DecompositionInput {\n /** Contents of `events.jsonl` (both generations), oldest first. */\n journal?: string;\n plan?: TaskPlan | null;\n /** Body of the issue as the provider resolved it. */\n issueBody?: string;\n /** Files changed on the branch, from `git diff --name-only`. */\n filesTouched?: number;\n /** Whether the execute loop stopped because it ran out of iterations. */\n hitMaxIterations?: boolean;\n}\n\nexport interface DecompositionSignal {\n id: string;\n /** One line a person can act on, naming the number that crossed the line. */\n detail: string;\n}\n\nexport interface DecompositionAssessment {\n signals: DecompositionSignal[];\n /** Two or more signals agreeing. */\n oversized: boolean;\n}\n\n/* ── the signals ────────────────────────────────────────────────────────── */\n\n/** Timeouts per phase, read off the journal. Shared with timeout escalation. */\nexport function timeoutsByPhase(journal: string): Map<string, number> {\n const counts = new Map<string, number>();\n let phase = '(unknown)';\n\n for (const { event } of parseJournal(journal)) {\n if (event.type === 'phase:start') {\n phase = event.phase;\n continue;\n }\n if (event.type !== 'retry') continue;\n const kind = (event as { kind?: string }).kind;\n const reason = (event as { reason?: string }).reason ?? '';\n const timedOut = kind === 'timeout' || kind === 'stalled' || /timed out|stalled/i.test(reason);\n if (!timedOut) continue;\n counts.set(phase, (counts.get(phase) ?? 0) + 1);\n }\n return counts;\n}\n\n/**\n * The longest run of iterations that completed no story.\n *\n * An iteration that finishes nothing is not a failure — the agent may be\n * halfway through a story — but five of them in a row means the unit of work is\n * bigger than the loop was designed for.\n */\nfunction longestBarrenRun(journal: string): number {\n let passing = 0;\n let current = 0;\n let longest = 0;\n\n for (const { event } of parseJournal(journal)) {\n if (event.type === 'iteration:start') {\n current++;\n longest = Math.max(longest, current);\n continue;\n }\n if (event.type !== 'stories:update') continue;\n const nowPassing = event.stories.filter((story) => story.passes).length;\n if (nowPassing > passing) current = 0;\n passing = Math.max(passing, nowPassing);\n }\n return longest;\n}\n\n/**\n * Weigh the evidence.\n *\n * Every signal is a number crossing a documented line, and the report quotes\n * that number: \"this is too big\" is not an argument, and \"the `prd` phase timed\n * out three times\" is.\n */\nexport function assessDecomposition(input: DecompositionInput): DecompositionAssessment {\n const signals: DecompositionSignal[] = [];\n const journal = input.journal ?? '';\n\n for (const [phase, count] of timeoutsByPhase(journal)) {\n if (count >= DECOMPOSITION_THRESHOLDS.timeoutsPerPhase) {\n signals.push({\n id: 'repeated-timeouts',\n detail: `The '${phase}' phase timed out ${count} times (threshold: ${DECOMPOSITION_THRESHOLDS.timeoutsPerPhase}).`,\n });\n }\n }\n\n const stories = input.plan?.userStories.length ?? 0;\n if (stories > DECOMPOSITION_THRESHOLDS.stories) {\n signals.push({\n id: 'story-count',\n detail: `The plan has ${stories} user stories (threshold: ${DECOMPOSITION_THRESHOLDS.stories}).`,\n });\n }\n\n const barren = longestBarrenRun(journal);\n if (barren >= DECOMPOSITION_THRESHOLDS.barrenIterations) {\n signals.push({\n id: 'barren-iterations',\n detail: `${barren} iterations in a row completed no story (threshold: ${DECOMPOSITION_THRESHOLDS.barrenIterations}).`,\n });\n }\n\n const files = input.filesTouched ?? 0;\n if (files > DECOMPOSITION_THRESHOLDS.filesTouched) {\n signals.push({\n id: 'files-touched',\n detail: `${files} files were touched on this branch (threshold: ${DECOMPOSITION_THRESHOLDS.filesTouched}).`,\n });\n }\n\n const body = input.issueBody?.length ?? 0;\n if (body > DECOMPOSITION_THRESHOLDS.issueBodyChars) {\n signals.push({\n id: 'issue-size',\n detail: `The issue body is ${body} characters (threshold: ${DECOMPOSITION_THRESHOLDS.issueBodyChars}).`,\n });\n }\n\n if (input.hitMaxIterations === true) {\n signals.push({\n id: 'max-iterations',\n detail: 'The execute loop stopped because it ran out of iterations, not because it finished.',\n });\n }\n\n return { signals, oversized: signals.length >= DECOMPOSITION_MIN_SIGNALS };\n}\n\n/* ── the report ─────────────────────────────────────────────────────────── */\n\n/** Stories per proposed sub-issue. Small enough to finish in one run. */\nconst STORIES_PER_SUBISSUE = 5;\n\nexport interface ProposedSubIssue {\n title: string;\n stories: UserStory[];\n /** Titles of the sub-issues this one has to wait for. */\n dependsOn: string[];\n}\n\n/**\n * Cut the remaining work into pieces, in priority order.\n *\n * Priority order matters twice: it is the order the execute loop already works\n * in, and it makes each piece depend only on the one before it — which is the\n * only dependency shape that can be derived without understanding the code.\n * Anything cleverer would be a guess dressed as a plan.\n */\nexport function proposeSubIssues(plan: TaskPlan | null | undefined): ProposedSubIssue[] {\n const pending = [...(plan?.userStories ?? [])]\n .filter((story) => !story.passes)\n .sort((a, b) => a.priority - b.priority);\n if (pending.length === 0) return [];\n\n const chunks: ProposedSubIssue[] = [];\n for (let index = 0; index < pending.length; index += STORIES_PER_SUBISSUE) {\n const stories = pending.slice(index, index + STORIES_PER_SUBISSUE);\n const first = stories[0];\n const last = stories[stories.length - 1];\n const range =\n first === undefined || last === undefined || first.id === last.id\n ? (first?.id ?? '')\n : `${first.id}–${last.id}`;\n chunks.push({\n title: `${plan?.description ?? 'Issue'} — part ${chunks.length + 1} (${range})`,\n stories,\n dependsOn: chunks.length === 0 ? [] : [chunks[chunks.length - 1]?.title ?? ''],\n });\n }\n return chunks;\n}\n\nexport interface DecompositionReportInput {\n issueNumber: string;\n assessment: DecompositionAssessment;\n plan: TaskPlan | null | undefined;\n at: string;\n}\n\n/**\n * The report itself: what was detected, what is proposed, and what to do.\n *\n * Written for a person to disagree with. It states each signal with its number,\n * proposes a cut it can justify, and stops — the decision is not the tool's.\n */\nexport function buildDecompositionReport(input: DecompositionReportInput): string {\n const { issueNumber, assessment, plan, at } = input;\n const proposals = proposeSubIssues(plan);\n const lines: string[] = [];\n\n lines.push(`# Issue #${issueNumber} looks larger than one run`, '');\n lines.push(`Detected at ${at}.`, '');\n lines.push(\n 'This is a report, not an action. Nothing has been split, and nothing will be',\n 'without you asking for it.',\n '',\n );\n\n lines.push('## What was detected', '');\n for (const signal of assessment.signals) {\n lines.push(`- **${signal.id}** — ${signal.detail}`);\n }\n lines.push('');\n\n if (proposals.length === 0) {\n lines.push('## Proposed split', '');\n lines.push(\n 'No pending user stories were found, so there is nothing to cut here.',\n 'The signals above are about the run rather than about the plan.',\n '',\n );\n return `${lines.join('\\n')}\\n`;\n }\n\n lines.push('## Proposed split', '');\n lines.push(\n `The ${proposals.reduce((total, proposal) => total + proposal.stories.length, 0)} pending` +\n ` stories, in priority order, cut into ${proposals.length} sub-issues of at most` +\n ` ${STORIES_PER_SUBISSUE}. Each depends on the one before it, which is the only`,\n 'dependency shape that can be derived from the plan alone — read it as a starting',\n 'point, not as an answer.',\n '',\n );\n\n for (const proposal of proposals) {\n lines.push(`### ${proposal.title}`, '');\n if (proposal.dependsOn.length > 0) {\n lines.push(`Depends on: ${proposal.dependsOn.join(', ')}`, '');\n }\n for (const story of proposal.stories) {\n lines.push(`- \\`${story.id}\\` ${story.title}`);\n }\n lines.push('');\n }\n\n lines.push('## What to do next', '');\n lines.push(\n '- Adjust the cut above until it matches how you would actually split the work;',\n '- create the sub-issues (`issue-flow generate \"…\"`) and run them as a queue;',\n '- or decide the issue is fine as it is and re-run it — nothing here blocks that,',\n ' beyond the report you are reading.',\n '',\n );\n\n return `${lines.join('\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAAA,iBAAgB;AACzB,OAAO,WAAW;;;ACQX,IAAM,mBAAoC;AAAA,EAC/C,oBAAoB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;AAAA,MACT,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,OAAO;AAAA,MACP,OAAO,EAAE,UAAU,SAAS,UAAU,OAAO,SAAS,MAAM;AAAA,IAC9D;AAAA,EACF;AACF;AAEA,SAAS,kBACP,KAQA,cACA,iBAAiB,OACD;AAChB,MAAI,iBAAiB,QAAQ;AAC3B,WAAO;AAAA,MACL,SAAS,IAAI;AAAA,MACb,QAAQ,IAAI,UAAU,IAAI,aAAa,IAAI,SAAS;AAAA,MACpD,MAAM;AAAA,MACN,OAAO,IAAI;AAAA,MACX,OAAO,IAAI;AAAA,MACX,GAAI,iBAAiB,EAAE,gBAAgB,KAAK,IAAI,CAAC;AAAA,IACnD;AAAA,EACF;AACA,MAAI,CAAC,IAAI,SAAS;AAChB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,OAAO,IAAI;AAAA,MACX,OAAO,IAAI;AAAA,MACX,GAAI,iBAAiB,EAAE,gBAAgB,KAAK,IAAI,CAAC;AAAA,IACnD;AAAA,EACF;AACA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ,IAAI;AAAA,IACZ,MAAM,IAAI;AAAA,IACV,OAAO;AAAA,IACP,OAAO,IAAI;AAAA,IACX,GAAI,iBAAiB,EAAE,gBAAgB,KAAK,IAAI,CAAC;AAAA,EACnD;AACF;","names":["readFile","run","failure","readFile","prefix"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/agent.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { probeReadinessInventory } from '../agents/availability.js';\nimport { describeRunAgents } from '../agents/resolve.js';\nimport {\n AGENT_PHASES,\n AGENT_SCHEMA_VERSION,\n type AgentPhase,\n type AgentProviderId,\n isAgentPhase,\n isAgentProviderId,\n} from '../agents/types.js';\nimport { GLOBAL_CONFIG_FILENAME, loadAgentConfig, PROJECT_CONFIG_FILENAME } from '../config.js';\nimport { getGlobalRoot } from '../storage/paths.js';\nimport { printError, printSuccess } from '../ui/logger.js';\nimport { writeFileAtomic } from '../utils/fs.js';\nimport { getProjectRoot } from '../utils/git.js';\n\nexport const AGENT_COMMAND_SCHEMA_VERSION = AGENT_SCHEMA_VERSION;\n\nexport interface AgentCommandOptions {\n json?: boolean;\n}\n\nexport interface AgentUseOptions {\n model?: string;\n global?: boolean;\n project?: boolean;\n phase?: string;\n}\n\nfunction originLabel(origin: string): string {\n switch (origin) {\n case 'default':\n return 'default';\n case 'global':\n return '~/.issue-flow/config.json';\n case 'project':\n return '.issue-flow.json';\n case 'env':\n return 'ISSUE_FLOW_*';\n case 'cli':\n return 'CLI';\n default:\n return origin;\n }\n}\n\nfunction formatPhaseLine(\n phase: AgentPhase,\n provider: string,\n model: string | null,\n origin: string,\n inherited: boolean,\n): string {\n const modelBit = model ? ` · ${model}` : '';\n const source = inherited ? 'herdado do padrão' : originLabel(origin);\n return `${` ${phase.padEnd(12)} ${provider}${modelBit}`.padEnd(40)}(${source})`;\n}\n\nexport async function runAgent(options: AgentCommandOptions = {}): Promise<number> {\n const config = await loadAgentConfig();\n const summary = await describeRunAgents();\n const inventory = await probeReadinessInventory();\n const providers = Object.values(inventory.providers);\n\n if (options.json === true) {\n const phases: Record<string, unknown> = {};\n for (const phase of AGENT_PHASES) {\n const resolved = summary.byPhase[phase];\n const inherited = config.phases[phase] === undefined;\n phases[phase] = {\n provider: resolved.provider,\n model: resolved.model,\n origin: resolved.origin,\n inherited,\n };\n }\n console.log(\n JSON.stringify(\n {\n schemaVersion: AGENT_COMMAND_SCHEMA_VERSION,\n default: {\n provider: summary.defaultProvider,\n model: summary.defaultModel,\n origin: summary.defaultOrigin,\n },\n phases,\n inventory,\n availability: providers.map((entry) => ({\n id: entry.provider,\n harness: entry.harness,\n installed: entry.installed,\n version: entry.version,\n authenticated: entry.authentication !== 'failed' && entry.installed,\n authentication: entry.authentication,\n state: entry.state,\n source: entry.source,\n observedAt: entry.observedAt,\n expiresAt: entry.expiresAt,\n detail: entry.detail,\n ...(entry.provider === 'antigravity' || entry.provider === 'claude'\n ? { authProbe: 'none' as const }\n : {}),\n })),\n },\n null,\n 2,\n ),\n );\n return 0;\n }\n\n const modelLabel = summary.defaultModel ?? '(default do provider)';\n console.log(\n `Agente padrão ${summary.defaultProvider.padEnd(22)} (${originLabel(summary.defaultOrigin.provider)})`,\n );\n console.log(`Modelo ${modelLabel} (${originLabel(summary.defaultOrigin.model)})`);\n console.log('');\n console.log('Por fase');\n for (const phase of AGENT_PHASES) {\n const resolved = summary.byPhase[phase];\n const inherited = config.phases[phase] === undefined;\n console.log(\n formatPhaseLine(\n phase,\n resolved.provider,\n resolved.model,\n resolved.origin.provider,\n inherited,\n ),\n );\n }\n console.log('');\n console.log('Disponibilidade');\n for (const entry of providers) {\n const authNote = entry.authentication === 'unverified' ? ' (auth unverified)' : '';\n console.log(\n ` ${entry.provider.padEnd(12)} ${(entry.version ?? '—').padEnd(16)} ${entry.state.padEnd(12)} ${entry.detail}${authNote}`,\n );\n }\n if (inventory.providers.antigravity?.installed) {\n console.log(\n ' Warning: every Antigravity invocation passes --dangerously-skip-permissions. --mode plan is the write containment.',\n );\n }\n return 0;\n}\n\nexport async function runAgentUse(\n providerRaw: string,\n options: AgentUseOptions = {},\n): Promise<number> {\n if (!isAgentProviderId(providerRaw)) {\n printError(\n `Unknown agent provider '${providerRaw}'. Valid providers: claude, codex, cursor, antigravity.`,\n );\n return 1;\n }\n const provider = providerRaw as AgentProviderId;\n\n let phase: AgentPhase | undefined;\n if (options.phase !== undefined) {\n if (!isAgentPhase(options.phase)) {\n printError(\n `Unknown agent phase '${options.phase}'. Valid phases: ${AGENT_PHASES.join(', ')}.`,\n );\n return 1;\n }\n phase = options.phase;\n }\n\n const target: 'global' | 'project' = options.project === true ? 'project' : 'global';\n try {\n const path = await writeAgentPreference({\n target,\n provider,\n model: options.model,\n phase,\n });\n printSuccess(`Wrote agent preference to ${path}`);\n return 0;\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n return 1;\n }\n}\n\nexport async function writeAgentPreference(input: {\n target: 'global' | 'project';\n provider: AgentProviderId;\n model?: string;\n phase?: AgentPhase;\n projectRoot?: string;\n}): Promise<string> {\n const path =\n input.target === 'global'\n ? join(getGlobalRoot(), GLOBAL_CONFIG_FILENAME)\n : join(input.projectRoot ?? (await getProjectRoot()), PROJECT_CONFIG_FILENAME);\n\n let existing: Record<string, unknown> = {};\n try {\n const raw = await readFile(path, 'utf-8');\n const parsed: unknown = JSON.parse(raw);\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n existing = parsed as Record<string, unknown>;\n }\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw new Error(`Could not read ${path}: ${(err as Error).message}`);\n }\n }\n\n const currentAgent =\n existing.agent !== null && typeof existing.agent === 'object' && !Array.isArray(existing.agent)\n ? { ...(existing.agent as Record<string, unknown>) }\n : {};\n\n if (input.phase) {\n const phases =\n currentAgent.phases !== null &&\n typeof currentAgent.phases === 'object' &&\n !Array.isArray(currentAgent.phases)\n ? { ...(currentAgent.phases as Record<string, unknown>) }\n : {};\n phases[input.phase] = {\n provider: input.provider,\n ...(input.model ? { model: input.model } : {}),\n };\n currentAgent.phases = phases;\n } else {\n currentAgent.provider = input.provider;\n if (input.model) currentAgent.model = input.model;\n else delete currentAgent.model;\n }\n\n existing.agent = currentAgent;\n await mkdir(dirname(path), { recursive: true });\n await writeFileAtomic(path, `${JSON.stringify(existing, null, 2)}\\n`);\n if (input.provider === 'cursor') {\n const { ensureCursorStorageGrant } = await import('../agents/permissions.js');\n await ensureCursorStorageGrant({\n mode: input.target === 'project' ? 'project' : 'global',\n ...(input.projectRoot === undefined ? {} : { projectRoot: input.projectRoot }),\n });\n }\n return path;\n}\n\n/** Used by init to persist a first-run choice without touching other keys. */\nexport async function persistFirstAgentChoice(provider: AgentProviderId): Promise<string> {\n return writeAgent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