issue-flow 0.13.0 → 0.14.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/dist/agent-OX3KPHE4.js +30 -0
- package/dist/{analyze-WS47UYGN.js → analyze-WIND2SEB.js} +21 -18
- package/dist/{analyze-WS47UYGN.js.map → analyze-WIND2SEB.js.map} +1 -1
- package/dist/{apply-OS62UWRN.js → apply-JNOI2LR4.js} +14 -11
- package/dist/{apply-OS62UWRN.js.map → apply-JNOI2LR4.js.map} +1 -1
- package/dist/{bench-SA3BOME5.js → bench-B4VZON7E.js} +30 -26
- package/dist/{bench-SA3BOME5.js.map → bench-B4VZON7E.js.map} +1 -1
- package/dist/{chunk-PIVGJM6K.js → chunk-2IQ6M4ZE.js} +11 -11
- package/dist/{chunk-QCXPNSEL.js → chunk-3BWZO4YI.js} +2 -2
- package/dist/chunk-3WFZETIM.js +163 -0
- package/dist/chunk-3WFZETIM.js.map +1 -0
- package/dist/{chunk-6FDFRNXZ.js → chunk-67YIU2VB.js} +25 -20
- package/dist/chunk-67YIU2VB.js.map +1 -0
- package/dist/{chunk-TM67EHSV.js → chunk-6BENHR2I.js} +19 -19
- package/dist/chunk-6BENHR2I.js.map +1 -0
- package/dist/{chunk-IYV6KNVF.js → chunk-6QYMSNVA.js} +66 -240
- package/dist/chunk-6QYMSNVA.js.map +1 -0
- package/dist/{chunk-IV5SS4JN.js → chunk-76MMPJ53.js} +9 -7
- package/dist/{chunk-IV5SS4JN.js.map → chunk-76MMPJ53.js.map} +1 -1
- package/dist/{chunk-LZ6GFQAG.js → chunk-B72RQZBV.js} +35 -25
- package/dist/chunk-B72RQZBV.js.map +1 -0
- package/dist/{chunk-KQHB7ZT3.js → chunk-BEZ5BA5U.js} +82 -16
- package/dist/chunk-BEZ5BA5U.js.map +1 -0
- package/dist/{chunk-BQDQTIM7.js → chunk-BRCNQXYQ.js} +4 -4
- package/dist/{chunk-ARFVHC2F.js → chunk-CGKLE6WR.js} +115 -23
- package/dist/chunk-CGKLE6WR.js.map +1 -0
- package/dist/{chunk-BHJCGWQX.js → chunk-F6TOYSYY.js} +9 -9
- package/dist/chunk-G5EK2XRN.js +25 -0
- package/dist/chunk-G5EK2XRN.js.map +1 -0
- package/dist/{chunk-TX5WIVYP.js → chunk-HAKDLR6N.js} +6 -1
- package/dist/chunk-HAKDLR6N.js.map +1 -0
- package/dist/{chunk-DIG5XKQQ.js → chunk-J3SOTUVI.js} +2 -2
- package/dist/{chunk-SNTTOQAD.js → chunk-JN6D3MY6.js} +2 -2
- package/dist/{chunk-MIVHK5YI.js → chunk-KMRFRXIT.js} +3 -3
- package/dist/{chunk-5TB6KLC2.js → chunk-KT7JKOXB.js} +8 -8
- package/dist/{chunk-NEZZ6KDR.js → chunk-LBGHI4S2.js} +49 -2
- package/dist/chunk-LBGHI4S2.js.map +1 -0
- package/dist/{chunk-3XLCNVMD.js → chunk-LEW4QM74.js} +2 -2
- package/dist/{chunk-IHIEXUTC.js → chunk-LFEQIZLB.js} +85 -10
- package/dist/chunk-LFEQIZLB.js.map +1 -0
- package/dist/{chunk-TVN2JVOF.js → chunk-OOVG2KBY.js} +3 -3
- package/dist/{chunk-7KD66LIM.js → chunk-OR43364P.js} +3 -3
- package/dist/{chunk-J62QSVP6.js → chunk-PBTA3QQX.js} +8 -7
- package/dist/{chunk-J62QSVP6.js.map → chunk-PBTA3QQX.js.map} +1 -1
- package/dist/{chunk-664Y3NDX.js → chunk-PHW2YV6N.js} +8 -8
- package/dist/{chunk-PV4OX5TC.js → chunk-PZTWU277.js} +11 -11
- package/dist/{chunk-HJGGNLWI.js → chunk-QD4VOILZ.js} +9 -9
- package/dist/{chunk-CNBYCMSU.js → chunk-QJ5UZAH5.js} +27 -18
- package/dist/{chunk-CNBYCMSU.js.map → chunk-QJ5UZAH5.js.map} +1 -1
- package/dist/{chunk-HQAHNIAR.js → chunk-QK7WUO7A.js} +14 -14
- package/dist/{chunk-UJ7XWK7J.js → chunk-QZVKRDJY.js} +16 -14
- package/dist/{chunk-UJ7XWK7J.js.map → chunk-QZVKRDJY.js.map} +1 -1
- package/dist/{chunk-FZDR7CGH.js → chunk-REO3PXXO.js} +3 -3
- package/dist/{chunk-UOCPC2Y2.js → chunk-RVO7L4FX.js} +4 -4
- package/dist/{chunk-QXDNBYQF.js → chunk-SZMHCEYV.js} +21 -10
- package/dist/chunk-SZMHCEYV.js.map +1 -0
- package/dist/chunk-TYRNTSPJ.js +243 -0
- package/dist/chunk-TYRNTSPJ.js.map +1 -0
- package/dist/{agent-BXRIEKVM.js → chunk-UJ3L2MS7.js} +22 -22
- package/dist/chunk-UJ3L2MS7.js.map +1 -0
- package/dist/{chunk-37N2RJW2.js → chunk-V7MO5EDS.js} +3 -3
- package/dist/{chunk-HEF2RMKN.js → chunk-WB2X37MO.js} +18 -16
- package/dist/{chunk-HEF2RMKN.js.map → chunk-WB2X37MO.js.map} +1 -1
- package/dist/{chunk-OPNGPUKJ.js → chunk-X44FKNKP.js} +133 -42
- package/dist/chunk-X44FKNKP.js.map +1 -0
- package/dist/cli.js +43 -40
- package/dist/cli.js.map +1 -1
- package/dist/{config-MEM2IWWN.js → config-HMFMCY2M.js} +12 -9
- package/dist/{conventions-WV4NDXGH.js → conventions-NJF2OPVQ.js} +14 -11
- package/dist/{conventions-WV4NDXGH.js.map → conventions-NJF2OPVQ.js.map} +1 -1
- package/dist/diagnostics-THH42ZMP.js +23 -0
- package/dist/execute-KFNNZZHI.js +35 -0
- package/dist/{generate-MVQI7A45.js → generate-FW5C6NP7.js} +23 -20
- package/dist/{generate-MVQI7A45.js.map → generate-FW5C6NP7.js.map} +1 -1
- package/dist/{git-YRVRUN3C.js → git-W72QQ6GT.js} +4 -2
- package/dist/init-HTN4V67Q.js +24 -0
- package/dist/{operations-LU6JA3BX.js → operations-BCFOBH42.js} +17 -14
- package/dist/{operations-LU6JA3BX.js.map → operations-BCFOBH42.js.map} +1 -1
- package/dist/{permissions-7NMDFU27.js → permissions-4AKNQZHK.js} +4 -4
- package/dist/plan-SIZLGA4V.js +34 -0
- package/dist/{policy-JSYEK5B2.js → policy-DT6Q6ZVM.js} +13 -10
- package/dist/{policy-JSYEK5B2.js.map → policy-DT6Q6ZVM.js.map} +1 -1
- package/dist/pr-OMWCGUOW.js +39 -0
- package/dist/pr-review-N24CZPKR.js +32 -0
- package/dist/prd-5OFTZAHJ.js +33 -0
- package/dist/{ps-TNE44R5V.js → ps-RFORTCUD.js} +11 -8
- package/dist/{ps-TNE44R5V.js.map → ps-RFORTCUD.js.map} +1 -1
- package/dist/{recorder-XGF55WXI.js → recorder-KCCPMKQG.js} +5 -4
- package/dist/registry-GLPXOMFG.js +15 -0
- package/dist/{resume-QMEPMSZW.js → resume-M5RLKP4I.js} +44 -40
- package/dist/{resume-QMEPMSZW.js.map → resume-M5RLKP4I.js.map} +1 -1
- package/dist/review-YM4JAABY.js +35 -0
- package/dist/{routing-2ZUMZPJB.js → routing-NNT5WKGX.js} +13 -10
- package/dist/{routing-2ZUMZPJB.js.map → routing-NNT5WKGX.js.map} +1 -1
- package/dist/run-PZUKHPQK.js +54 -0
- package/dist/run-PZUKHPQK.js.map +1 -0
- package/dist/session-publisher-T7EI3CIP.js +11 -0
- package/dist/session-publisher-T7EI3CIP.js.map +1 -0
- package/dist/{state-manager-X3PT3FGT.js → state-manager-GQH32C44.js} +3 -3
- package/dist/state-manager-GQH32C44.js.map +1 -0
- package/dist/{usage-VCFLDA5Y.js → usage-V2CHE5PY.js} +13 -10
- package/dist/{usage-VCFLDA5Y.js.map → usage-V2CHE5PY.js.map} +1 -1
- package/dist/{web-XVHLX62B.js → web-EA3KGNFN.js} +18 -14
- package/dist/{web-XVHLX62B.js.map → web-EA3KGNFN.js.map} +1 -1
- package/package.json +1 -1
- package/web/AGENTS.md +150 -11
- package/web/public/app.css +343 -110
- package/web/public/app.js +408 -18
- package/web/public/index.html +44 -1
- package/dist/agent-BXRIEKVM.js.map +0 -1
- package/dist/chunk-6FDFRNXZ.js.map +0 -1
- package/dist/chunk-ARFVHC2F.js.map +0 -1
- package/dist/chunk-IHIEXUTC.js.map +0 -1
- package/dist/chunk-IYV6KNVF.js.map +0 -1
- package/dist/chunk-KQHB7ZT3.js.map +0 -1
- package/dist/chunk-LZ6GFQAG.js.map +0 -1
- package/dist/chunk-NEZZ6KDR.js.map +0 -1
- package/dist/chunk-OPNGPUKJ.js.map +0 -1
- package/dist/chunk-QXDNBYQF.js.map +0 -1
- package/dist/chunk-TM67EHSV.js.map +0 -1
- package/dist/chunk-TX5WIVYP.js.map +0 -1
- package/dist/execute-NITIHHCK.js +0 -31
- package/dist/init-OKWEC3EV.js +0 -21
- package/dist/plan-LEJJF3DE.js +0 -31
- package/dist/pr-HPVUZ7S3.js +0 -36
- package/dist/pr-review-R2QZBT3F.js +0 -29
- package/dist/prd-5O6GYCC6.js +0 -30
- package/dist/registry-LGPE53QD.js +0 -15
- package/dist/review-YKWD6SNN.js +0 -32
- package/dist/run-YU4TR62R.js +0 -50
- /package/dist/{config-MEM2IWWN.js.map → agent-OX3KPHE4.js.map} +0 -0
- /package/dist/{chunk-PIVGJM6K.js.map → chunk-2IQ6M4ZE.js.map} +0 -0
- /package/dist/{chunk-QCXPNSEL.js.map → chunk-3BWZO4YI.js.map} +0 -0
- /package/dist/{chunk-BQDQTIM7.js.map → chunk-BRCNQXYQ.js.map} +0 -0
- /package/dist/{chunk-BHJCGWQX.js.map → chunk-F6TOYSYY.js.map} +0 -0
- /package/dist/{chunk-DIG5XKQQ.js.map → chunk-J3SOTUVI.js.map} +0 -0
- /package/dist/{chunk-SNTTOQAD.js.map → chunk-JN6D3MY6.js.map} +0 -0
- /package/dist/{chunk-MIVHK5YI.js.map → chunk-KMRFRXIT.js.map} +0 -0
- /package/dist/{chunk-5TB6KLC2.js.map → chunk-KT7JKOXB.js.map} +0 -0
- /package/dist/{chunk-3XLCNVMD.js.map → chunk-LEW4QM74.js.map} +0 -0
- /package/dist/{chunk-TVN2JVOF.js.map → chunk-OOVG2KBY.js.map} +0 -0
- /package/dist/{chunk-7KD66LIM.js.map → chunk-OR43364P.js.map} +0 -0
- /package/dist/{chunk-664Y3NDX.js.map → chunk-PHW2YV6N.js.map} +0 -0
- /package/dist/{chunk-PV4OX5TC.js.map → chunk-PZTWU277.js.map} +0 -0
- /package/dist/{chunk-HJGGNLWI.js.map → chunk-QD4VOILZ.js.map} +0 -0
- /package/dist/{chunk-HQAHNIAR.js.map → chunk-QK7WUO7A.js.map} +0 -0
- /package/dist/{chunk-FZDR7CGH.js.map → chunk-REO3PXXO.js.map} +0 -0
- /package/dist/{chunk-UOCPC2Y2.js.map → chunk-RVO7L4FX.js.map} +0 -0
- /package/dist/{chunk-37N2RJW2.js.map → chunk-V7MO5EDS.js.map} +0 -0
- /package/dist/{execute-NITIHHCK.js.map → config-HMFMCY2M.js.map} +0 -0
- /package/dist/{git-YRVRUN3C.js.map → diagnostics-THH42ZMP.js.map} +0 -0
- /package/dist/{init-OKWEC3EV.js.map → execute-KFNNZZHI.js.map} +0 -0
- /package/dist/{permissions-7NMDFU27.js.map → git-W72QQ6GT.js.map} +0 -0
- /package/dist/{plan-LEJJF3DE.js.map → init-HTN4V67Q.js.map} +0 -0
- /package/dist/{pr-HPVUZ7S3.js.map → permissions-4AKNQZHK.js.map} +0 -0
- /package/dist/{pr-review-R2QZBT3F.js.map → plan-SIZLGA4V.js.map} +0 -0
- /package/dist/{prd-5O6GYCC6.js.map → pr-OMWCGUOW.js.map} +0 -0
- /package/dist/{recorder-XGF55WXI.js.map → pr-review-N24CZPKR.js.map} +0 -0
- /package/dist/{registry-LGPE53QD.js.map → prd-5OFTZAHJ.js.map} +0 -0
- /package/dist/{review-YKWD6SNN.js.map → recorder-KCCPMKQG.js.map} +0 -0
- /package/dist/{run-YU4TR62R.js.map → registry-GLPXOMFG.js.map} +0 -0
- /package/dist/{state-manager-X3PT3FGT.js.map → review-YM4JAABY.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/types.ts","../src/policy/schemas.ts","../src/schemas.ts","../src/agents/schemas.ts","../src/storage/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';\n\n/**\n * Zod schemas for the `policy` key of `.issue-flow.json`.\n *\n * Two shapes, and the difference matters:\n *\n * - {@link policyConfigInputSchema} validates what the user *wrote*, with no\n * defaults materialized. It is what the file, env and CLI layers are parsed\n * with, so an absent key stays absent and never shadows the layer below it\n * (the caveat documented on `mergeConfigLayers`).\n * - {@link policyConfigSchema} is the resolved shape, with `enabled` and the\n * discovery toggles filled in. The declarations stay optional there too:\n * materializing them as `null` would make an unset `baseBranch` override the\n * one discovery found.\n */\n\n/** Which discovery passes run. Every one defaults to on. */\nexport const policyDiscoveryConfigSchema = z.object({\n issueTemplates: z.boolean().default(true),\n pullRequestTemplate: z.boolean().default(true),\n docs: z.boolean().default(true),\n codeowners: z.boolean().default(true),\n labels: z.boolean().default(true),\n issueTypes: z.boolean().default(true),\n});\n\nconst policyIssuesDeclarationSchema = z.object({\n titleConvention: z.string().min(1).optional(),\n /**\n * Whether Issue Flow may create a label the repository does not have.\n *\n * `.optional()` rather than `.default(false)`: the resolved declarations must\n * stay \"only what was written\", or the group would always look declared and\n * `sources` would report a provenance nobody asked for. The effective default\n * — false — lives at the call site.\n *\n * That default is a deliberate change of behaviour: creating taxonomy without\n * asking is the defect this exists to stop. A repository that wants the old\n * behaviour opts back into it.\n */\n allowLabelCreation: z.boolean().optional(),\n});\n\nconst policyPullRequestsDeclarationSchema = z.object({\n baseBranch: z.string().min(1).optional(),\n titleConvention: z.string().min(1).optional(),\n});\n\nconst policyGitDeclarationSchema = z.object({\n branchConvention: z.string().min(1).optional(),\n commitConvention: z.string().min(1).optional(),\n pullRequestTitleConvention: z.string().min(1).optional(),\n issueReference: z.enum(['closes', 'refs']).optional(),\n typeMap: z.record(z.string(), z.string().min(1)).optional(),\n});\n\n/**\n * Resolved policy configuration.\n *\n * `.prefault({})` rather than `.default({})`: in zod 4 a `.default()` value is\n * substituted *without* being parsed by the inner schema, so `discovery` would\n * come back as `{}` with none of its toggles filled in.\n */\nexport const policyConfigSchema = z.object({\n enabled: z.boolean().default(true),\n /**\n * Token budget for the `__REPO_POLICY__` projection. Sections above it are\n * replaced whole by a pointer rather than truncated — see\n * `policy/placeholders.ts`.\n */\n contextBudget: z.number().int().positive().default(1500),\n discovery: policyDiscoveryConfigSchema.prefault({}),\n issues: policyIssuesDeclarationSchema.prefault({}),\n pullRequests: policyPullRequestsDeclarationSchema.prefault({}),\n git: policyGitDeclarationSchema.prefault({}),\n});\n\n/**\n * What the user may write. `.nullish()` on every declaration is deliberate:\n * `\"baseBranch\": null` is the natural way to spell \"I do not declare this\",\n * and the loader drops it instead of rejecting the whole key.\n */\nexport const policyConfigInputSchema = z.object({\n enabled: z.boolean().optional(),\n contextBudget: z.number().int().positive().optional(),\n // Spelled out rather than `policyDiscoveryConfigSchema.partial()`: in zod 4\n // a `.default()` survives `.partial()`, so every toggle would come back\n // materialized and the input layer would stop meaning \"what the user wrote\".\n discovery: z\n .object({\n issueTemplates: z.boolean().optional(),\n pullRequestTemplate: z.boolean().optional(),\n docs: z.boolean().optional(),\n codeowners: z.boolean().optional(),\n labels: z.boolean().optional(),\n issueTypes: z.boolean().optional(),\n })\n .optional(),\n issues: z\n .object({ titleConvention: z.string().nullish(), allowLabelCreation: z.boolean().optional() })\n .optional(),\n pullRequests: z\n .object({ baseBranch: z.string().nullish(), titleConvention: z.string().nullish() })\n .optional(),\n git: z\n .object({\n branchConvention: z.string().nullish(),\n commitConvention: z.string().nullish(),\n pullRequestTitleConvention: z.string().nullish(),\n issueReference: z.enum(['closes', 'refs']).nullish(),\n typeMap: z.record(z.string(), z.string().min(1)).nullish(),\n })\n .optional(),\n});\n\nexport type PolicyConfig = z.infer<typeof policyConfigSchema>;\nexport type PolicyDiscoveryConfig = z.infer<typeof policyDiscoveryConfigSchema>;\nexport type PolicyConfigInput = z.infer<typeof policyConfigInputSchema>;\n","import { z } from 'zod';\nimport type { ClaudeUsage } from './core/metrics.js';\nimport type { SessionSnapshot } from './core/session-state.js';\nimport type { IssueMetadata, IssuesConfig } from './issues/types.js';\nimport type { ExecutionRecord } from './telemetry/types.js';\n\n/**\n * Zod schemas for validating tasks.json structure, Issue metadata, headless\n * invocation outputs, the web monitoring session snapshot and the web\n * configuration.\n */\n\n/**\n * Token/cost metrics of a single `claude` invocation, mirroring ClaudeUsage in\n * src/core/metrics.ts. Every field is optional: the CLI only reports what it\n * knows, and an absent field means \"not reported\", never zero.\n */\nexport const claudeUsageSchema = z.object({\n inputTokens: z.number().optional(),\n outputTokens: z.number().optional(),\n cacheReadTokens: z.number().optional(),\n cacheCreationTokens: z.number().optional(),\n costUsd: z.number().optional(),\n}) satisfies z.ZodType<ClaudeUsage>;\n\nexport const userStoryStatusSchema = z.enum(['backlog', 'in_progress', 'in_review', 'done']);\n\n/**\n * Fine-grained execution stage — mirrors `StoryStage` in `src/types.ts`. See\n * that type's doc comment for what each value means and which pipeline event\n * produces it.\n */\nexport const storyStageSchema = z.enum([\n 'pending',\n 'executing',\n 'awaiting_review',\n 'in_review',\n 'in_correction',\n 'done',\n 'failed',\n]);\n\n/**\n * The metrics fields are additive and optional: plans written before they\n * existed keep parsing, and nothing is filled in with artificial zeros.\n *\n * `status` and `dependencies` follow the same rule and are `.optional()` rather\n * than `.default()` on purpose: a legacy plan must not gain a `'backlog'` and an\n * empty array it never declared just because `saveTaskPlan` rewrote it. `stage`\n * and friends follow the exact same treatment — nothing in the pipeline writes\n * them back onto `tasks.json`, so they stay `.optional()` too.\n */\nexport const userStorySchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n acceptanceCriteria: z.array(z.string()),\n priority: z.number().int().positive(),\n passes: z.boolean(),\n notes: z.string(),\n ...claudeUsageSchema.shape,\n durationSeconds: z.number().optional(),\n status: userStoryStatusSchema.optional(),\n dependencies: z.array(z.string()).optional(),\n stage: storyStageSchema.optional(),\n stageSince: z.string().optional(),\n stageDetail: z.string().optional(),\n});\n\nexport const pipelineStateSchema = z.object({\n analyzeCompleted: z.boolean().optional(),\n prdCompleted: z.boolean(),\n jsonCompleted: z.boolean(),\n executionCompleted: z.boolean(),\n reviewCompleted: z.boolean(),\n prCreated: z.boolean(),\n prReviewCompleted: z.boolean().optional(),\n});\n\n/**\n * Pull Request opened by the `pr` phase. Optional on the plan: plans written\n * before the field existed (and runs with `--no-branch`) simply omit it.\n */\nexport const pullRequestRefSchema = z.object({\n number: z.number().int().positive(),\n url: z.string(),\n headBranch: z.string(),\n createdAt: z.string(),\n});\n\nexport const prReviewRecommendationSchema = z.enum([\n 'APPROVE',\n 'APPROVE_WITH_SUGGESTIONS',\n 'REQUEST_CHANGES',\n]);\n\n/**\n * State of the opt-in `pr-review` phase. `enabled` and `rounds` carry defaults\n * so a partially written object still parses instead of invalidating the plan.\n */\nexport const prReviewStateSchema = z.object({\n enabled: z.boolean().default(false),\n pullRequestNumber: z.number().int().positive().optional(),\n rounds: z.number().int().min(0).default(0),\n lastRecommendation: prReviewRecommendationSchema.optional(),\n lastReviewedAt: z.string().optional(),\n});\n\nconst lastErrorSchema = z.object({\n category: z.string(),\n message: z.string(),\n at: z.string(),\n});\n\n/**\n * Persisted metadata for an Issue stored on disk (issues/<id>/metadata.json).\n * `satisfies` keeps this schema in lockstep with the IssueMetadata interface in\n * src/issues/types.ts — changing one without the other fails the typecheck.\n */\nexport const issueMetadataSchema = z.object({\n schemaVersion: z.literal(1),\n id: z.string().min(1),\n number: z.number().int().positive().nullable(),\n source: z.enum(['github', 'local']),\n title: z.string(),\n labels: z.array(z.string()),\n state: z.enum(['open', 'closed']),\n createdAt: z.string(),\n updatedAt: z.string(),\n contentHash: z.string(),\n remote: z\n .object({\n provider: z.enum(['github', 'local']),\n ref: z.string(),\n syncedAt: z.string(),\n syncedContentHash: z.string(),\n })\n .optional(),\n}) satisfies z.ZodType<IssueMetadata>;\n\n/**\n * tasks.json structure. Deliberately permissive: plans written by older\n * versions must keep loading, so `issueUrl` is optional (Issues with no remote\n * have no URL) and `issueNumber` accepts non-numeric local identifiers.\n */\n/**\n * `TaskPlan.runState`, written by the pipeline and read on resumption.\n *\n * Optional as a whole — a plan from before it existed has none — but every\n * field inside carries a default, so a partially written object (a process\n * killed mid-write) still parses into a usable state instead of invalidating\n * the plan. That is the same discipline `prReviewStateSchema` follows.\n */\nexport const runOwnerSchema = z.object({\n pid: z.number().int().positive(),\n host: z.string(),\n startedAt: z.string(),\n});\n\nexport const issueRunStateSchema = z.object({\n status: z\n .enum(['idle', 'running', 'waiting', 'retrying', 'paused', 'blocked', 'failed'])\n .default('idle'),\n currentPhase: z.string().nullable().default(null),\n attempt: z.number().int().min(0).default(0),\n lastHeartbeatAt: z.string().nullable().default(null),\n blockedReason: z.string().nullable().default(null),\n owner: runOwnerSchema.nullable().default(null),\n});\n\nconst failureKindSchema = 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\nconst normalizedUsageSchema = z.object({\n inputTokens: z.number().optional(),\n outputTokens: z.number().optional(),\n cacheReadTokens: z.number().optional(),\n cacheCreationTokens: z.number().optional(),\n reasoningTokens: z.number().optional(),\n details: z.record(z.string(), z.number()).optional(),\n source: z.enum(['provider', 'unavailable']),\n});\n\nconst pricingSnapshotSchema = z.object({\n tableVersion: z.string(),\n modelKey: z.string(),\n inputPerMillion: z.number(),\n outputPerMillion: z.number(),\n cacheReadPerMillion: z.number().optional(),\n cacheWritePerMillion: z.number().optional(),\n capturedAt: z.string(),\n});\n\nconst costRecordSchema = z.discriminatedUnion('status', [\n z.object({ status: z.literal('reported'), amount: z.number(), currency: z.literal('USD') }),\n z.object({\n status: z.literal('estimated'),\n amount: z.number(),\n currency: z.literal('USD'),\n pricing: pricingSnapshotSchema,\n }),\n z.object({\n status: z.literal('unknown'),\n reason: z.enum(['not_reported', 'no_pricing', 'unknown_model', 'subscription', 'zero_rated']),\n }),\n]);\n\n/**\n * One agent invocation. Optional on the plan and without a default array:\n * a plan that never recorded executions must not gain `[]` on rewrite.\n */\nexport const executionRecordSchema = z.object({\n id: z.string(),\n sessionId: z.string().nullable(),\n purpose: z.enum([\n 'analyze',\n 'generate',\n 'prd',\n 'plan',\n 'execute',\n 'review',\n 'pr',\n 'pr-review',\n 'verify',\n ]),\n attempt: z.number().int().positive(),\n trigger: z.enum(['initial', 'retry', 'fallback', 'correction', 'escalation']),\n triggerReason: failureKindSchema.nullable(),\n agent: z.object({\n harness: z.string(),\n provider: z.string().nullable(),\n harnessVersion: z.string().nullable().optional(),\n model: z.object({\n requested: z.string().nullable(),\n resolved: z.string().nullable(),\n source: z.enum(['provider', 'config', 'unavailable']),\n }),\n providerSessionId: z.string().nullable(),\n }),\n startedAt: z.string(),\n finishedAt: z.string().nullable(),\n durationMs: z.number().nullable(),\n cliDurationMs: z.number().nullable().optional(),\n harnessStartupMs: z.number().nullable().optional(),\n apiDurationMs: z.number().nullable().optional(),\n ttftMs: z.number().nullable().optional(),\n numTurns: z.number().nullable().optional(),\n usage: normalizedUsageSchema.nullable(),\n cost: costRecordSchema,\n status: z.enum(['running', 'completed', 'failed', 'timeout', 'cancelled', 'interrupted']),\n failure: z\n .object({\n kind: failureKindSchema,\n message: z.string(),\n exitCode: z.number().nullable(),\n })\n .nullable(),\n stopReason: z\n .enum([\n 'completed',\n 'failed',\n 'timeout',\n 'cancelled',\n 'max_attempts',\n 'max_cost',\n 'max_duration',\n ])\n .nullable()\n .optional(),\n iteration: z.number().int().optional(),\n correctionCycle: z.number().int().min(0).optional(),\n storyIds: z.array(z.string()).optional(),\n owner: z.object({ pid: z.number().int(), host: z.string() }).nullable().optional(),\n routingDecision: z\n .object({\n selected: z.string(),\n actual: z.string().optional(),\n candidates: z.array(z.unknown()).optional(),\n reasonCodes: z.array(z.string()).optional(),\n })\n .passthrough()\n .nullable()\n .optional(),\n verdict: z\n .object({\n status: z.enum(['passed', 'failed', 'unverified']),\n level: z.string().nullable().optional(),\n independence: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n}) satisfies z.ZodType<ExecutionRecord>;\n\nexport const taskPlanSchema = z.object({\n project: z.string(),\n issueNumber: z.union([z.number().int().positive(), z.string().min(1)]),\n issueUrl: z.string().optional().default(''),\n branchName: z.string(),\n noBranch: z.boolean().optional().default(false),\n description: z.string(),\n issueStatus: z.enum(['pending', 'in_progress', 'completed']),\n completedAt: z.string().nullable(),\n lastAttemptAt: z.string().nullable(),\n lastError: lastErrorSchema.nullable(),\n correctionCycle: z.number().int().min(0),\n maxCorrectionCycles: z.number().int().min(0),\n /**\n * Findings from the most recent failed review, verbatim. Non-null means the\n * issue has a pending correction even if every userStories[].passes is\n * already true — the execute phase must address these before the field is\n * cleared back to null. See core/engine.ts's early-return guards.\n */\n lastReviewFindings: z.string().nullable().optional().default(null),\n pipeline: pipelineStateSchema,\n /**\n * Where the run stands right now. Purely additive: absent in every plan\n * written before it, and absent is not the same as `idle` — it means the\n * plan predates the field, which is why there is no `.default()` here.\n */\n runState: issueRunStateSchema.optional(),\n pullRequest: pullRequestRefSchema.optional(),\n prReview: prReviewStateSchema.optional(),\n userStories: z.array(userStorySchema),\n /**\n * Per-invocation history. `.optional()` and no `.default([])`: a plan that\n * predates the field must not grow an empty array just because it was saved.\n */\n executions: z.array(executionRecordSchema).optional(),\n});\n\nexport const headlessResultSchema = z.object({\n success: z.boolean(),\n result: z.string(),\n cost: claudeUsageSchema.nullable(),\n error: z.string().nullable(),\n});\n\nconst sessionLogEntrySchema = z.object({\n at: z.string(),\n level: z.enum(['info', 'warn', 'error']),\n message: z.string(),\n});\n\n/**\n * Usage counters attached to a phase or a story in the session snapshot.\n * Unlike claudeUsageSchema (a single invocation, optional fields), these are\n * always present and nullable: null means \"never reported\", not zero.\n *\n * They default to null on input so a session.json written before the metrics\n * existed still parses -- absent and null mean the same thing here, and the\n * parsed value keeps the `number | null` shape the snapshot interface declares.\n */\nconst sessionUsageShape = {\n inputTokens: z.number().nullable().default(null),\n outputTokens: z.number().nullable().default(null),\n cacheReadTokens: z.number().nullable().default(null),\n cacheCreationTokens: z.number().nullable().default(null),\n costUsd: z.number().nullable().default(null),\n};\n\nconst sessionPhaseSchema = z.object({\n name: z.string(),\n status: z.enum(['pending', 'running', 'completed', 'failed']),\n startedAt: z.string().nullable(),\n endedAt: z.string().nullable(),\n durationSeconds: z.number().nullable(),\n error: z.string().nullable(),\n harnessExecutionMs: z.number().nullable().default(null),\n orchestrationOverheadMs: z.number().nullable().default(null),\n harnessStartupMs: z.number().nullable().default(null),\n ttftMs: z.number().nullable().default(null),\n attemptCount: z.number().nullable().default(null),\n retryDurationMs: z.number().nullable().default(null),\n ...sessionUsageShape,\n});\n\nconst sessionStorySchema = z.object({\n id: z.string(),\n title: z.string(),\n priority: z.number(),\n passes: z.boolean(),\n completedAt: z.string().nullable(),\n // Also introduced with the metrics, hence the same tolerant default.\n durationSeconds: z.number().nullable().default(null),\n // Snapshot fields are always present on output and defaulted on input, so a\n // session.json written before they existed still parses. This is the mirror\n // image of userStorySchema, where the same two fields are plainly optional.\n status: userStoryStatusSchema.default('backlog'),\n dependencies: z.array(z.string()).default([]),\n // Published for the panel's story detail view. Same tolerant default as the\n // fields above: absent (older session.json) and empty resolve to the same\n // value, so the client never has to tell them apart.\n description: z.string().default(''),\n acceptanceCriteria: z.array(z.string()).default([]),\n // Additive like the rest of this schema: a session.json written before\n // `stage` existed parses into 'pending'/null, the same values a fresh\n // snapshot starts a story at.\n stage: storyStageSchema.default('pending'),\n stageSince: z.string().nullable().default(null),\n stageDetail: z.string().nullable().default(null),\n history: z\n .array(\n z.object({\n at: z.string(),\n stage: storyStageSchema,\n detail: z.string().nullable(),\n }),\n )\n .default([]),\n ...sessionUsageShape,\n});\n\nconst sessionConfigurationValueSchema = z.object({\n value: z.string().nullable(),\n source: z.enum(['default', 'global', 'project', 'env', 'cli', 'fallback']),\n});\n\nconst sessionConfigurationSchema = z.object({\n precedence: z.array(z.string()),\n defaultProvider: sessionConfigurationValueSchema,\n defaultModel: sessionConfigurationValueSchema,\n phases: z.array(\n z.object({\n phase: z.string(),\n provider: sessionConfigurationValueSchema,\n model: sessionConfigurationValueSchema,\n }),\n ),\n fallbacks: z.array(z.string()),\n overrides: z.array(z.string()),\n});\n\n/**\n * Session snapshot served by the web monitoring mode (session.json and the\n * HTTP endpoint). `satisfies` keeps this schema in lockstep with the\n * SessionSnapshot interface in src/core/session-state.ts — changing one\n * without the other fails the typecheck.\n */\nexport const sessionSnapshotSchema = z.object({\n schemaVersion: z.literal(1),\n sessionId: z.string().nullable(),\n readOnly: z.literal(true),\n capabilities: z.array(z.string()),\n issue: z.object({\n number: z.number().nullable(),\n url: z.string().nullable(),\n // Additive: a session.json written before the Issue section was enriched\n // parses into the same \"not reported\" values createInitialSnapshot() uses.\n title: z.string().nullable().default(null),\n description: z.string().nullable().default(null),\n labels: z.array(z.string()).default([]),\n state: z.string().nullable().default(null),\n }),\n status: z.enum(['idle', 'running', 'completed', 'failed']),\n startedAt: z.string().nullable(),\n updatedAt: z.string().nullable(),\n endedAt: z.string().nullable(),\n elapsedSeconds: z.number().nullable(),\n estimatedRemainingSeconds: z.number().nullable(),\n progress: z.object({\n percent: z.number(),\n phasesCompleted: z.number(),\n phasesTotal: z.number(),\n storiesCompleted: z.number(),\n storiesTotal: z.number(),\n }),\n currentPhase: z.string().nullable(),\n currentActivity: z\n .object({\n story: z.string().nullable(),\n tool: z.string().nullable(),\n detail: z.string().nullable(),\n since: z.string(),\n })\n .nullable(),\n phases: z.array(sessionPhaseSchema),\n stories: z.array(sessionStorySchema),\n // The whole aggregate is additive: a snapshot from before it existed parses\n // into the same \"nothing reported\" object the reducer starts from.\n metrics: z\n .object({\n totalInputTokens: z.number().nullable().default(null),\n totalOutputTokens: z.number().nullable().default(null),\n totalCacheReadTokens: z.number().nullable().default(null),\n totalCacheCreationTokens: z.number().nullable().default(null),\n totalCostUsd: z.number().nullable().default(null),\n })\n .default({\n totalInputTokens: null,\n totalOutputTokens: null,\n totalCacheReadTokens: null,\n totalCacheCreationTokens: null,\n totalCostUsd: null,\n }),\n execution: z.object({\n iteration: z.number(),\n retries: z.number(),\n correctionCycle: z.number(),\n maxCorrectionCycles: z.number().nullable(),\n }),\n executions: z.array(executionRecordSchema).default([]),\n processLogs: z\n .array(\n z.object({\n at: z.string(),\n phase: z.string(),\n executionId: z.string().nullable(),\n provider: z.string(),\n stream: z.enum(['stdout', 'stderr', 'combined']),\n message: z.string(),\n }),\n )\n .default([]),\n configuration: sessionConfigurationSchema.nullable().default(null),\n // Additive resilience projection. Every field defaults so session.json from\n // before provider failover/observability remains readable without a schema\n // version bump.\n resilience: z\n .object({\n attempt: z.number().int().nonnegative().default(0),\n provider: z.string().nullable().default(null),\n model: 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 cooldownUntil: z.string().nullable().default(null),\n lastActivityAt: z.string().nullable().default(null),\n })\n .default({\n attempt: 0,\n provider: null,\n model: null,\n lastFailureKind: null,\n cooldownUntil: null,\n lastActivityAt: null,\n }),\n git: z.object({\n branch: z.string().nullable(),\n baseBranch: z.string().nullable(),\n branchCreated: z.boolean().nullable().default(null),\n startCommit: z.string().nullable().default(null),\n commits: z.array(\n z.object({\n hash: z.string(),\n subject: z.string(),\n committedAt: z.string().nullable().default(null),\n storyId: z.string().nullable().default(null),\n }),\n ),\n }),\n // Additive like the metrics aggregate: a session.json written before the\n // repository section existed parses into the same all-null object\n // createInitialSnapshot() starts from.\n repository: z\n .object({\n name: z.string().nullable().default(null),\n remoteUrl: z.string().nullable().default(null),\n branch: z.string().nullable().default(null),\n headCommit: z.string().nullable().default(null),\n root: z.string().nullable().default(null),\n })\n .default({ name: null, remoteUrl: null, branch: null, headCommit: null, root: null }),\n pullRequests: z.array(z.object({ number: z.number(), url: z.string(), title: z.string() })),\n logs: z.array(sessionLogEntrySchema),\n errors: z.array(sessionLogEntrySchema),\n warnings: z.array(sessionLogEntrySchema),\n lastError: z.object({ message: z.string(), at: z.string() }).nullable(),\n nextSteps: z.array(z.string()),\n environment: z\n .object({\n node: z.string(),\n platform: z.string(),\n agent: z.string().nullable().default(null),\n model: z.string().nullable().default(null),\n })\n .nullable(),\n // Additive: a session.json written before the acceptance contract existed\n // parses as \"not reported\". schemaVersion stays 1.\n verification: z\n .object({\n verdict: z.enum(['passed', 'failed', 'unverified']).nullable(),\n level: z.string().nullable(),\n independence: z.string().nullable(),\n })\n .nullable()\n .default(null),\n}) satisfies z.ZodType<SessionSnapshot>;\n\n/**\n * Resolved web monitoring configuration. Every field has a default, so\n * parsing a partial object (e.g. the `web` key of .issue-flow.json) fills in\n * the documented defaults.\n */\nexport const webConfigSchema = z.object({\n enabled: z.boolean().default(false),\n port: z.number().int().min(1).max(65535).default(3737),\n host: z.string().min(1).default('0.0.0.0'),\n refreshSeconds: z.number().positive().default(5),\n logLimit: z.number().int().positive().default(200),\n includeLogs: z.boolean().default(true),\n});\n\n/**\n * Resolved Issue provider configuration. Every field has a default that keeps\n * the GitHub-only behaviour, so parsing an empty object yields the exact\n * behaviour of releases without the provider layer.\n */\nexport const issuesConfigSchema = z.object({\n defaultGenerateTarget: z.enum(['github', 'local', 'both']).default('github'),\n preferredProvider: z.enum(['github', 'local']).default('github'),\n conflictPolicy: z.enum(['ask', 'prefer-local', 'prefer-github']).default('ask'),\n requireConfirmation: z.boolean().default(true),\n}) satisfies z.ZodType<IssuesConfig>;\n\n/**\n * Resolved `pr-review` configuration (the `prReview` key of .issue-flow.json).\n *\n * `publisher` selects the implementation `createPrReviewPublisher()` builds:\n * `local` writes the artifacts under the issue directory, and `github` does\n * that **and** comments on the Pull Request, updating the comment of the same\n * round instead of stacking a new one on every republication.\n *\n * `local` stays the default, so a repository that configures nothing publishes\n * exactly where it always did and never writes to GitHub by surprise.\n */\nexport const prReviewConfigSchema = z.object({\n publisher: z.enum(['local', 'github']).default('local'),\n});\n\n/**\n * The `policy` key of .issue-flow.json — the repository policy layer. Defined\n * in `policy/schemas.ts` next to the module that consumes it, and re-exported\n * here so `schemas.ts` stays the single index of the file's keys.\n */\nexport {\n type PolicyConfig,\n type PolicyConfigInput,\n type PolicyDiscoveryConfig,\n policyConfigInputSchema,\n policyConfigSchema,\n policyDiscoveryConfigSchema,\n} from './policy/schemas.js';\n\nexport type ValidatedTaskPlan = z.infer<typeof taskPlanSchema>;\nexport type ValidatedIssueMetadata = z.infer<typeof issueMetadataSchema>;\nexport type ValidatedHeadlessResult = z.infer<typeof headlessResultSchema>;\nexport type ValidatedSessionSnapshot = z.infer<typeof sessionSnapshotSchema>;\nexport const verifyCheckSchema = z.object({\n id: z.string().min(1),\n run: z.string().optional(),\n expectFiles: z.array(z.string()).optional(),\n fatal: z.boolean().optional(),\n});\n\nexport const verifyConfigSchema = z.object({\n level: z.enum(['L0', 'L1', 'L2', 'L3', 'L5']).default('L1'),\n triggers: z.array(z.string()).default([]),\n pairings: z.record(z.string(), z.string()).default({}),\n contract: z.array(verifyCheckSchema).optional(),\n crossVerify: z.boolean().default(true),\n});\n\nexport type WebConfig = z.infer<typeof webConfigSchema>;\nexport type PrReviewConfig = z.infer<typeof prReviewConfigSchema>;\nexport const routingConfigSchema = z.object({\n mode: z.enum(['off', 'shadow', 'recommend', 'active']).default('shadow'),\n profile: z.enum(['economy', 'balanced', 'quality', 'speed']).default('balanced'),\n escalation: z\n .object({\n enabled: z.boolean().default(false),\n minAttemptsBeforeEscalation: z.number().int().positive().default(2),\n maxEscalations: z.number().int().nonnegative().default(2),\n maxRungs: z\n .array(z.enum(['effort', 'model', 'harness', 'review', 'decompose']))\n .default(['effort', 'model', 'harness']),\n })\n .default({\n enabled: false,\n minAttemptsBeforeEscalation: 2,\n maxEscalations: 2,\n maxRungs: ['effort', 'model', 'harness'],\n }),\n ceilings: z\n .object({\n maxCostUsdPerIssue: z.number().nonnegative().nullable().default(null),\n maxDurationMsPerIssue: z.number().nonnegative().nullable().default(null),\n maxExecutionsPerIssue: z.number().int().nonnegative().nullable().default(null),\n onCeiling: z.literal('block').default('block'),\n })\n .default({\n maxCostUsdPerIssue: null,\n maxDurationMsPerIssue: null,\n maxExecutionsPerIssue: null,\n onCeiling: 'block',\n }),\n});\n\nexport type VerifyConfig = z.infer<typeof verifyConfigSchema>;\nexport type RoutingConfig = z.infer<typeof routingConfigSchema>;\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 { 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, 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 * `~/.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 web: globalWebConfigSchema,\n retry: globalRetryConfigSchema,\n commit: globalCommitConfigSchema,\n resilience: resilienceConfigSchema,\n agent: agentConfigInputSchema,\n telemetry: telemetryConfigInputSchema,\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});\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 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 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 { 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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,aAAa,OAAoC;AAC/D,SAAQ,aAAmC,SAAS,KAAK;AAC3D;AAEO,SAAS,kBAAkB,OAAyC;AACzE,SAAO,UAAU,YAAY,UAAU,WAAW,UAAU,YAAY,UAAU;AACpF;AAkMO,IAAM,sBAAyC;AAAA,EACpD,kBAAkB;AAAA,EAClB,SAAS;AAAA,EACT,eAAe;AAAA,EACf,UAAU;AAAA,EACV,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,OAAO;AAAA,EACP,cAAc;AAAA,EACd,aAAa;AAAA,EACb,eAAe;AAAA,EACf,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,qBAAqB;AAAA,EACrB,cAAc;AAAA,EACd,cAAc;AAChB;AAEO,IAAM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I,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","z","z","z"]}
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
CLAUDE_CAPABILITIES,
|
|
5
5
|
CODEX_CAPABILITIES,
|
|
6
6
|
CURSOR_CAPABILITIES
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-LBGHI4S2.js";
|
|
8
8
|
|
|
9
9
|
// src/routing/priors.ts
|
|
10
10
|
var PRIORS_VERSION = "1";
|
|
@@ -177,4 +177,4 @@ export {
|
|
|
177
177
|
PRIORS_VERSION,
|
|
178
178
|
decideRouting
|
|
179
179
|
};
|
|
180
|
-
//# sourceMappingURL=chunk-
|
|
180
|
+
//# sourceMappingURL=chunk-LEW4QM74.js.map
|
|
@@ -1,22 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
writeAgentPreference
|
|
4
|
+
} from "./chunk-UJ3L2MS7.js";
|
|
2
5
|
import {
|
|
3
6
|
resolvePackageDir
|
|
4
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-KMRFRXIT.js";
|
|
5
8
|
import {
|
|
6
|
-
NullPublisher,
|
|
7
9
|
printInfo,
|
|
8
10
|
printWarning
|
|
9
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-TYRNTSPJ.js";
|
|
12
|
+
import {
|
|
13
|
+
NullPublisher
|
|
14
|
+
} from "./chunk-6QYMSNVA.js";
|
|
15
|
+
import {
|
|
16
|
+
readDiagnostics
|
|
17
|
+
} from "./chunk-3WFZETIM.js";
|
|
18
|
+
import {
|
|
19
|
+
getGlobalRoot
|
|
20
|
+
} from "./chunk-HAKDLR6N.js";
|
|
10
21
|
import {
|
|
11
22
|
isoNow
|
|
12
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-J3SOTUVI.js";
|
|
13
24
|
import {
|
|
25
|
+
isAgentPhase,
|
|
26
|
+
isAgentProviderId,
|
|
14
27
|
isProcessAlive,
|
|
15
28
|
webLockSchema
|
|
16
|
-
} from "./chunk-
|
|
17
|
-
import {
|
|
18
|
-
getGlobalRoot
|
|
19
|
-
} from "./chunk-TX5WIVYP.js";
|
|
29
|
+
} from "./chunk-LBGHI4S2.js";
|
|
20
30
|
|
|
21
31
|
// src/web/lock.ts
|
|
22
32
|
import { spawn as nodeSpawn } from "child_process";
|
|
@@ -103,6 +113,20 @@ function respond(res, status, contentType, body) {
|
|
|
103
113
|
function respondJson(res, status, payload) {
|
|
104
114
|
respond(res, status, JSON_TYPE, JSON.stringify(payload));
|
|
105
115
|
}
|
|
116
|
+
function isLoopbackHost(host) {
|
|
117
|
+
return host === "127.0.0.1" || host === "::1" || host === "localhost";
|
|
118
|
+
}
|
|
119
|
+
async function readJsonBody(req) {
|
|
120
|
+
const chunks = [];
|
|
121
|
+
let size = 0;
|
|
122
|
+
for await (const chunk of req) {
|
|
123
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
124
|
+
size += buffer.length;
|
|
125
|
+
if (size > 64 * 1024) throw new Error("Request body too large.");
|
|
126
|
+
chunks.push(buffer);
|
|
127
|
+
}
|
|
128
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf-8") || "{}");
|
|
129
|
+
}
|
|
106
130
|
async function startWebServer(options) {
|
|
107
131
|
const info = options.info ?? printInfo;
|
|
108
132
|
const warn = options.warn ?? printWarning;
|
|
@@ -127,6 +151,40 @@ async function startWebServer(options) {
|
|
|
127
151
|
baseHeaders(res);
|
|
128
152
|
const requestUrl = new URL(req.url ?? "/", "http://localhost");
|
|
129
153
|
const path = requestUrl.pathname;
|
|
154
|
+
if (req.method === "POST" && path === "/api/config/agent") {
|
|
155
|
+
if (!isLoopbackHost(options.host)) {
|
|
156
|
+
respondJson(res, 403, {
|
|
157
|
+
error: "Configuration writes are disabled when the monitor is not bound to loopback."
|
|
158
|
+
});
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const body = await readJsonBody(req);
|
|
162
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
163
|
+
respondJson(res, 400, { error: "Expected a JSON object." });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const input = body;
|
|
167
|
+
if (typeof input.provider !== "string" || !isAgentProviderId(input.provider)) {
|
|
168
|
+
respondJson(res, 400, { error: "Invalid provider." });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (input.phase !== void 0 && (typeof input.phase !== "string" || !isAgentPhase(input.phase))) {
|
|
172
|
+
respondJson(res, 400, { error: "Invalid phase." });
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (input.model !== void 0 && typeof input.model !== "string") {
|
|
176
|
+
respondJson(res, 400, { error: "Invalid model." });
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const file = await writeAgentPreference({
|
|
180
|
+
target: "global",
|
|
181
|
+
provider: input.provider,
|
|
182
|
+
...input.model ? { model: input.model } : {},
|
|
183
|
+
...input.phase ? { phase: input.phase } : {}
|
|
184
|
+
});
|
|
185
|
+
respondJson(res, 200, { ok: true, file, appliesTo: "future executions" });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
130
188
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
131
189
|
respondJson(res, 404, { error: "Not found" });
|
|
132
190
|
return;
|
|
@@ -213,12 +271,29 @@ async function startWebServer(options) {
|
|
|
213
271
|
respondJson(res, 200, entries);
|
|
214
272
|
return;
|
|
215
273
|
}
|
|
274
|
+
if (path === "/api/diagnostics") {
|
|
275
|
+
const sessionId = requestUrl.searchParams.get("session") ?? void 0;
|
|
276
|
+
respondJson(res, 200, await readDiagnostics({ sessionId, limit: 500 }));
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (path === "/api/config") {
|
|
280
|
+
const sessionId = requestUrl.searchParams.get("session");
|
|
281
|
+
const snapshot = sessionId === null ? void 0 : source.get(sessionId);
|
|
282
|
+
respondJson(res, 200, {
|
|
283
|
+
effective: snapshot?.configuration ?? null,
|
|
284
|
+
capturedForSession: snapshot?.sessionId ?? null,
|
|
285
|
+
writable: isLoopbackHost(options.host),
|
|
286
|
+
writeScope: "global preferences for future executions"
|
|
287
|
+
});
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
216
290
|
if (path === "/api/health") {
|
|
217
291
|
respondJson(res, 200, {
|
|
218
292
|
ok: true,
|
|
219
293
|
uptime: Math.round((Date.now() - startedAtMs) / 1e3),
|
|
220
294
|
version,
|
|
221
|
-
refreshSeconds: options.refreshSeconds ?? 5
|
|
295
|
+
refreshSeconds: options.refreshSeconds ?? 5,
|
|
296
|
+
capabilities: isLoopbackHost(options.host) ? ["config:agent:write"] : []
|
|
222
297
|
});
|
|
223
298
|
return;
|
|
224
299
|
}
|
|
@@ -480,4 +555,4 @@ export {
|
|
|
480
555
|
ensureSingleWebServer,
|
|
481
556
|
ensureWebMonitor
|
|
482
557
|
};
|
|
483
|
-
//# sourceMappingURL=chunk-
|
|
558
|
+
//# sourceMappingURL=chunk-LFEQIZLB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/web/lock.ts","../src/web/server.ts"],"sourcesContent":["import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process';\nimport { readFile, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport chalk from 'chalk';\nimport { isoNow } from '../core/state-manager.js';\n// The liveness probe is shared with `storage/lock.ts`, which generalised this\n// module's guard into run ownership: one definition of \"is that pid alive\",\n// with one place to get the EPERM case right.\nimport { isProcessAlive } from '../storage/lock.js';\nimport { type GetGlobalRootOptions, getGlobalRoot } from '../storage/paths.js';\nimport { type WebLock, webLockSchema } from '../storage/schemas.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport { startWebServer, type WebServerHandle, type WebServerOptions } from './server.js';\n\n/**\n * Single-instance guard for the web monitoring server (`~/.issue-flow/web.lock`).\n *\n * A machine runs at most one monitoring server. Two entry points build on top\n * of the same lock:\n *\n * - `ensureSingleWebServer` binds (or reuses) a server **in the calling\n * process**. It is the low-level primitive, used by the `web serve` command\n * (the standalone process that ends up owning the lock) and by this\n * module's own tests. Nothing else should call it directly.\n * - `ensureWebMonitor` (US-002) is what `run`/`execute` call: it reuses an\n * active instance exactly like `ensureSingleWebServer`, but when none\n * exists it spawns `web serve` as a **detached** child instead of binding\n * locally, so the server outlives the pipeline process. Falls back to the\n * legacy in-process `startWebServer` (US-006) when the global storage tree\n * itself is unreachable.\n */\n\n/** Lock file name, sibling of `config.json` at the global storage root. */\nexport const WEB_LOCK_FILENAME = 'web.lock';\n\n/** How long a health probe against a candidate instance waits before giving up. */\nconst HEALTH_PROBE_TIMEOUT_MS = 1000;\n\n/**\n * A process that loses the atomic lock creation retries this many times,\n * waiting for the winner to finish starting up, before giving up.\n */\nconst LOCK_CLAIM_RETRIES = 5;\nconst LOCK_CLAIM_RETRY_DELAY_MS = 100;\n\nexport function getWebLockFile(options: GetGlobalRootOptions = {}): string {\n return join(getGlobalRoot(options), WEB_LOCK_FILENAME);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** 0.0.0.0 is not a connectable address; probe loopback instead, same mapping\n * `startWebServer` uses to build its own display URL. */\nfunction probeUrl(host: string, port: number): string {\n const probeHost = host === '0.0.0.0' ? '127.0.0.1' : host;\n return `http://${probeHost}:${port}/api/health`;\n}\n\nasync function probeHealth(host: string, port: number): Promise<boolean> {\n try {\n const res = await fetch(probeUrl(host, port), {\n signal: AbortSignal.timeout(HEALTH_PROBE_TIMEOUT_MS),\n });\n return res.ok;\n } catch {\n return false;\n }\n}\n\n/** Malformed content (partial write, older/newer incompatible shape) reads as\n * \"no lock\" — the same degrade-to-absent behavior as `loadGlobalConfig()`. */\nexport async function readWebLock(lockFile: string): Promise<WebLock | 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 = webLockSchema.safeParse(JSON.parse(raw));\n return result.success ? result.data : null;\n } catch {\n return null;\n }\n}\n\nexport async function removeWebLock(lockFile: string): Promise<void> {\n try {\n await rm(lockFile, { force: true });\n } catch {\n /* best-effort cleanup */\n }\n}\n\n/**\n * A lock is only trustworthy when both signals agree: the owning process is\n * alive AND it answers `/api/health`. A dead pid is the obvious stale case;\n * a live pid that does not answer covers a process that still exists but\n * crashed before binding, was killed -9 leaving a zombie-adjacent state, or\n * whose port was reclaimed by something else entirely. Either way the lock is\n * removed so the next attempt starts clean instead of looping on it forever.\n */\nexport async function detectActiveInstance(lockFile: string): Promise<WebLock | null> {\n const lock = await readWebLock(lockFile);\n if (lock === null) return null;\n\n if (isProcessAlive(lock.pid) && (await probeHealth(lock.host, lock.port))) {\n return lock;\n }\n\n await removeWebLock(lockFile);\n return null;\n}\n\n/**\n * Atomic exclusive create: `wx` fails with EEXIST when another process won\n * the race, which is what lets two concurrent invocations agree on a single\n * winner without a separate lock-of-the-lock.\n */\nasync function claimWebLock(lockFile: string, lock: WebLock): Promise<boolean> {\n try {\n await writeFile(lockFile, JSON.stringify(lock, null, 2), { encoding: 'utf-8', flag: 'wx' });\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;\n throw err;\n }\n}\n\n/** Handle returned when reusing an already-running instance instead of\n * binding a new one — there is no local `Server` to hold, and closing it\n * must not tear down a server another process owns. */\nfunction reusedHandle(lock: WebLock): WebServerHandle {\n const displayHost = lock.host === '0.0.0.0' ? 'localhost' : lock.host;\n return {\n host: lock.host,\n port: lock.port,\n url: `http://${displayHost}:${lock.port}`,\n close: async () => {},\n };\n}\n\n/**\n * Start the web monitoring server, first checking whether a live instance\n * already owns `web.lock` and reusing it instead of binding a second one.\n *\n * The lock is claimed only *after* a successful bind, never before: claiming\n * it with the port the server is about to (but hasn't yet) listen on would\n * make that lock briefly answer no health probe at all, and a concurrent\n * invocation would misread that gap as \"stale\" and delete a perfectly good\n * lock out from under its owner. Binding first also means two invocations\n * racing for the same fixed port never both reach the claim step — the OS\n * itself lets only one `listen()` succeed. The `wx` claim then exists for the\n * remaining race: two invocations that *both* manage to bind (only possible\n * with an ephemeral port) still agree on exactly one winner. The loser closes\n * the server it just opened and defers to whichever lock exists.\n *\n * Returns null exactly when `startWebServer` would: nothing here may affect\n * the pipeline, so a lock we cannot resolve after every retry degrades to \"no\n * server\" rather than throwing.\n */\nexport async function ensureSingleWebServer(\n options: WebServerOptions,\n lockOptions: GetGlobalRootOptions = {},\n): Promise<WebServerHandle | null> {\n const warn = options.warn ?? printWarning;\n const info = options.info ?? printInfo;\n const lockFile = getWebLockFile(lockOptions);\n\n for (let attempt = 0; attempt <= LOCK_CLAIM_RETRIES; attempt++) {\n const active = await detectActiveInstance(lockFile);\n if (active !== null) {\n info(`Reusing existing web monitor at ${reusedHandle(active).url}`);\n return reusedHandle(active);\n }\n\n const handle = await startWebServer(options);\n if (handle === null) {\n // Could not bind. Most likely another instance's listen() won a race\n // on the same fixed port between our detection above and this call —\n // its lock should be visible shortly. Anything else (port taken by an\n // unrelated process, invalid host, ...) fails the same way on the next\n // retry too, and the loop's own limit stops it from spinning forever.\n await sleep(LOCK_CLAIM_RETRY_DELAY_MS);\n continue;\n }\n\n let claimed: boolean;\n try {\n claimed = await claimWebLock(lockFile, {\n pid: process.pid,\n port: handle.port,\n host: handle.host,\n startedAt: isoNow(),\n });\n } catch (err) {\n await handle.close();\n throw err;\n }\n\n if (!claimed) {\n // We bound successfully (an ephemeral port let both of us through),\n // but another invocation's lock got written first. We are not the\n // canonical instance: close what we just opened and defer to it.\n await handle.close();\n await sleep(LOCK_CLAIM_RETRY_DELAY_MS);\n continue;\n }\n\n const originalClose = handle.close;\n handle.close = async () => {\n await originalClose();\n await removeWebLock(lockFile);\n };\n return handle;\n }\n\n warn('Could not determine the web monitor lock ownership. Continuing without the web server.');\n return null;\n}\n\n/** Bounded wait for a freshly spawned `web serve` child to claim the lock. */\nconst DETACHED_CLAIM_TIMEOUT_MS = 5000;\nconst DETACHED_CLAIM_POLL_MS = 150;\n\nexport interface EnsureWebMonitorOptions extends GetGlobalRootOptions {\n /** Injectable for tests. Defaults to `node:child_process`'s `spawn`. */\n spawn?: (\n command: string,\n args: string[],\n options: { detached: true; stdio: 'ignore' },\n ) => ChildProcess;\n /** Node executable to spawn. Defaults to `process.execPath`. */\n execPath?: string;\n /** CLI entry script re-invoked as `<entry> web serve ...`. Defaults to `process.argv[1]`. */\n entryScript?: string;\n /** How long to wait for the spawned instance's lock to become healthy. */\n claimTimeoutMs?: number;\n claimPollIntervalMs?: number;\n}\n\n/**\n * Entry point for `run`/`execute`: get a web monitor without binding one in\n * this process (US-002).\n *\n * 1. Reuse a live, healthy instance exactly like `ensureSingleWebServer`.\n * 2. Otherwise, spawn `<node> <cli> web serve --port … --host … [--refresh …]`\n * detached (`{ detached: true, stdio: 'ignore' }`) and `unref()`ed, so it\n * survives this process exiting and never pipes its own stdio back here.\n * 3. Poll the lock file (bounded) until the spawned instance claims it, then\n * return a *reused* handle for it — this process never owns that `Server`,\n * the same shape `ensureSingleWebServer`'s reuse path already returns.\n *\n * Two failure modes degrade gracefully rather than affecting the pipeline:\n * the global storage tree being unreachable (no resolvable home directory)\n * falls back to `startWebServer` bound right here, exactly the pre-US-001\n * behavior (US-006); a spawn or claim failure with the storage tree otherwise\n * healthy just returns null, same contract `startWebServer` itself has.\n */\nexport async function ensureWebMonitor(\n options: WebServerOptions,\n monitorOptions: EnsureWebMonitorOptions = {},\n): Promise<WebServerHandle | null> {\n const warn = options.warn ?? printWarning;\n const info = options.info ?? printInfo;\n\n let lockFile: string;\n try {\n lockFile = getWebLockFile(monitorOptions);\n } catch (err) {\n warn(\n `Web monitor: global storage unavailable (${err instanceof Error ? err.message : String(err)}). Falling back to legacy in-process mode.`,\n );\n return startWebServer(options);\n }\n\n const active = await detectActiveInstance(lockFile);\n if (active !== null) {\n info(`Reusing existing web monitor at ${reusedHandle(active).url}`);\n return reusedHandle(active);\n }\n\n const execPath = monitorOptions.execPath ?? process.execPath;\n const entryScript = monitorOptions.entryScript ?? process.argv[1];\n if (entryScript === undefined) {\n warn('Web monitor: could not determine the CLI entry point to spawn a detached server.');\n return null;\n }\n\n const args = [\n entryScript,\n 'web',\n 'serve',\n '--port',\n String(options.port),\n '--host',\n options.host,\n ];\n if (options.refreshSeconds !== undefined) {\n args.push('--refresh', String(options.refreshSeconds));\n }\n\n const spawnFn = monitorOptions.spawn ?? nodeSpawn;\n try {\n const child = spawnFn(execPath, args, { detached: true, stdio: 'ignore' });\n child.unref();\n } catch (err) {\n warn(\n `Web monitor: failed to start the detached server (${err instanceof Error ? err.message : String(err)}). Continuing without the web server.`,\n );\n return null;\n }\n\n const timeoutMs = monitorOptions.claimTimeoutMs ?? DETACHED_CLAIM_TIMEOUT_MS;\n const pollMs = monitorOptions.claimPollIntervalMs ?? DETACHED_CLAIM_POLL_MS;\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const claimed = await detectActiveInstance(lockFile);\n if (claimed !== null) {\n info(`Web monitor running at ${chalk.bold.cyan(reusedHandle(claimed).url)}`);\n return reusedHandle(claimed);\n }\n await sleep(pollMs);\n }\n\n warn(\n 'Web monitor: the detached server did not start in time. Continuing without the web server.',\n );\n return null;\n}\n","import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport { createRequire } from 'node:module';\nimport type { AddressInfo } from 'node:net';\nimport { join } from 'node:path';\nimport chalk from 'chalk';\nimport { isAgentPhase, isAgentProviderId } from '../agents/types.js';\nimport { writeAgentPreference } from '../commands/agent.js';\nimport type { JournalEntry } from '../core/journal.js';\nimport { resolvePackageDir } from '../core/prompt-resolver.js';\nimport {\n NullPublisher,\n type SessionPublisher,\n type SessionSnapshot,\n} from '../core/session-state.js';\nimport { readDiagnostics } from '../storage/diagnostics.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport type { SessionDirectoryHandle } from './session-directory.js';\n\n/**\n * HTTP server for the web monitoring mode. Plain node:http — no new runtime\n * dependencies. Serves the publisher's in-memory snapshot (it never re-reads\n * issues/N/session.json) and the static UI assets.\n *\n * Resilience contract: nothing here may ever affect the pipeline. Listen\n * failures (EADDRINUSE included) log a warning and the execution continues\n * without a server; the server is unref()'d so it cannot keep the process\n * alive; request handling is wrapped so a handler error answers 500 instead\n * of crashing the process.\n */\n\nconst require = createRequire(import.meta.url);\n\n/** Max length of `issueDescription` on GET /api/sessions (dashboard preview). */\nexport const SESSION_LIST_DESCRIPTION_MAX = 280;\n\nfunction readPackageVersion(): string {\n try {\n return (require('../../package.json') as { version: string }).version;\n } catch {\n return '0.0.0';\n }\n}\n\n/** Collapse whitespace and truncate for the sessions list payload. */\nexport function truncateSessionDescription(\n text: string | null | undefined,\n max = SESSION_LIST_DESCRIPTION_MAX,\n): string | null {\n if (text === null || text === undefined) return null;\n const normalized = text.replace(/\\s+/g, ' ').trim();\n if (normalized.length === 0) return normalized;\n if (normalized.length <= max) return normalized;\n return `${normalized.slice(0, max - 1).trimEnd()}…`;\n}\n\nexport interface WebServerOptions {\n /**\n * Legacy single-session mode (pre-US-003, still used by the US-006\n * fallback): serves this publisher's in-memory snapshot directly, with no\n * directory scan and no lock file involved. Mutually exclusive with\n * `sessions` — when both are given, `sessions` wins.\n */\n publisher?: SessionPublisher;\n /**\n * Multi-session mode: sessions discovered by polling the global storage\n * tree (`web/session-directory.ts`). This is what every current entry\n * point (`web serve`) passes; `publisher` only exists for the legacy path.\n */\n sessions?: SessionDirectoryHandle;\n port: number;\n host: string;\n /** Suggested UI polling interval, exposed via /api/health. */\n refreshSeconds?: number;\n /** Package version reported by /api/health. Default: read from package.json. */\n version?: string;\n /** Directory holding index.html/app.css/app.js. Default: auto-resolved. */\n publicDir?: string;\n /** Info logger. Default: printInfo. */\n info?: (message: string) => void;\n /** Warning logger. Default: printWarning. */\n warn?: (message: string) => void;\n /**\n * Whether to `unref()` the underlying socket so it never keeps the process\n * alive on its own. Default `true`, matching the historical contract for a\n * server bound inline in the pipeline process. The standalone `web serve`\n * process (the detached server itself) passes `false`: it has nothing else\n * to do, so staying alive for as long as the server is bound *is* the job.\n */\n unref?: boolean;\n}\n\nexport interface WebServerHandle {\n /**\n * Absent when this handle represents an existing instance reused through\n * `ensureSingleWebServer` (`web/lock.ts`) instead of one bound locally.\n */\n server?: Server;\n /** Host the server is bound to. */\n host: string;\n /** Actual bound port (relevant when options.port is 0). */\n port: number;\n /** Human-facing access URL. */\n url: string;\n /** Close the server and release signal handlers. Idempotent, never rejects. */\n close(): Promise<void>;\n}\n\ninterface StaticAsset {\n body: string;\n contentType: string;\n}\n\nconst JSON_TYPE = 'application/json; charset=utf-8';\n\n/**\n * Uniform view over \"whatever sessions this server knows about\", so the route\n * handlers below never care whether they are backed by a single in-memory\n * publisher (legacy mode) or by the global directory scan (US-003/US-004).\n */\ninterface SessionSource {\n /** Every session currently considered active, in no particular order. */\n list(): SessionSnapshot[];\n /** A specific session by id, or undefined when it is not currently active. */\n get(sessionId: string): SessionSnapshot | undefined;\n events(sessionId: string): Promise<JournalEntry[] | undefined>;\n}\n\nfunction publisherSessionSource(publisher: SessionPublisher): SessionSource {\n return {\n list: () => {\n const snapshot = publisher.snapshot();\n return snapshot.sessionId === null ? [] : [snapshot];\n },\n get: (sessionId) => {\n const snapshot = publisher.snapshot();\n return snapshot.sessionId === sessionId ? snapshot : undefined;\n },\n events: async (sessionId) => (publisher.snapshot().sessionId === sessionId ? [] : undefined),\n };\n}\n\nfunction directorySessionSource(handle: SessionDirectoryHandle): SessionSource {\n return {\n list: () => handle.sessions().map((entry) => entry.snapshot),\n get: (sessionId) => handle.getSession(sessionId)?.snapshot,\n events: (sessionId) => handle.events(sessionId),\n };\n}\n\nfunction resolveSessionSource(options: WebServerOptions): SessionSource {\n if (options.sessions) return directorySessionSource(options.sessions);\n return publisherSessionSource(options.publisher ?? new NullPublisher());\n}\n\nconst STATIC_ROUTES: Record<string, { file: string; contentType: string }> = {\n '/': { file: 'index.html', contentType: 'text/html; charset=utf-8' },\n '/app.css': { file: 'app.css', contentType: 'text/css; charset=utf-8' },\n '/app.js': { file: 'app.js', contentType: 'text/javascript; charset=utf-8' },\n};\n\n/** Assets are read once at startup; missing files simply 404. */\nasync function loadStaticAssets(publicDir: string | null): Promise<Map<string, StaticAsset>> {\n const assets = new Map<string, StaticAsset>();\n if (publicDir === null) return assets;\n for (const [route, { file, contentType }] of Object.entries(STATIC_ROUTES)) {\n try {\n const body = await readFile(join(publicDir, file), 'utf-8');\n assets.set(route, { body, contentType });\n } catch {\n // Asset not present (e.g. UI not built yet) — route answers 404.\n }\n }\n return assets;\n}\n\n/** Headers applied to every response, including 304s and errors. */\nfunction baseHeaders(res: ServerResponse): void {\n res.setHeader('Cache-Control', 'no-store');\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('Referrer-Policy', 'no-referrer');\n res.setHeader('X-Robots-Tag', 'noindex, nofollow');\n}\n\nfunction respond(res: ServerResponse, status: number, contentType: string, body: string): void {\n res.statusCode = status;\n res.setHeader('Content-Type', contentType);\n res.end(body);\n}\n\nfunction respondJson(res: ServerResponse, status: number, payload: unknown): void {\n respond(res, status, JSON_TYPE, JSON.stringify(payload));\n}\n\nfunction isLoopbackHost(host: string): boolean {\n return host === '127.0.0.1' || host === '::1' || host === 'localhost';\n}\n\nasync function readJsonBody(req: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n size += buffer.length;\n if (size > 64 * 1024) throw new Error('Request body too large.');\n chunks.push(buffer);\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf-8') || '{}');\n}\n\n/**\n * Start the monitoring HTTP server. Returns null when the server could not\n * listen (port in use, invalid host, ...) — the pipeline continues without\n * monitoring, it is never brought down by the server.\n */\nexport async function startWebServer(options: WebServerOptions): Promise<WebServerHandle | null> {\n const info = options.info ?? printInfo;\n const warn = options.warn ?? printWarning;\n const version = options.version ?? readPackageVersion();\n const startedAtMs = Date.now();\n\n // The UI ships at the package root as web/public/ (sibling of prompts/),\n // resolved the same way from src/ and from the published dist/ layout.\n const assets = await loadStaticAssets(\n options.publicDir ?? resolvePackageDir(join('web', 'public')),\n );\n\n const source = resolveSessionSource(options);\n\n // JSON serialization memoized per session id: an unchanged poll answers 304\n // with an empty body. Content-hashed rather than counter-based, unlike the\n // pre-multi-session version — a directory-backed session has no in-process\n // publisher to hand out a monotonic version(), and a hash works uniformly\n // for both sources.\n const statusCache = new Map<string, { body: string; etag: string }>();\n const statusPayload = (snapshot: SessionSnapshot): { body: string; etag: string } => {\n const key = snapshot.sessionId ?? '';\n const body = JSON.stringify(snapshot);\n const cached = statusCache.get(key);\n if (cached !== undefined && cached.body === body) return cached;\n const etag = `\"${createHash('sha1').update(body).digest('hex')}\"`;\n const entry = { body, etag };\n statusCache.set(key, entry);\n return entry;\n };\n\n const handleRequest = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n baseHeaders(res);\n\n const requestUrl = new URL(req.url ?? '/', 'http://localhost');\n const path = requestUrl.pathname;\n\n if (req.method === 'POST' && path === '/api/config/agent') {\n if (!isLoopbackHost(options.host)) {\n respondJson(res, 403, {\n error: 'Configuration writes are disabled when the monitor is not bound to loopback.',\n });\n return;\n }\n const body = await readJsonBody(req);\n if (body === null || typeof body !== 'object' || Array.isArray(body)) {\n respondJson(res, 400, { error: 'Expected a JSON object.' });\n return;\n }\n const input = body as { provider?: unknown; model?: unknown; phase?: unknown };\n if (typeof input.provider !== 'string' || !isAgentProviderId(input.provider)) {\n respondJson(res, 400, { error: 'Invalid provider.' });\n return;\n }\n if (\n input.phase !== undefined &&\n (typeof input.phase !== 'string' || !isAgentPhase(input.phase))\n ) {\n respondJson(res, 400, { error: 'Invalid phase.' });\n return;\n }\n if (input.model !== undefined && typeof input.model !== 'string') {\n respondJson(res, 400, { error: 'Invalid model.' });\n return;\n }\n const file = await writeAgentPreference({\n target: 'global',\n provider: input.provider,\n ...(input.model ? { model: input.model } : {}),\n ...(input.phase ? { phase: input.phase } : {}),\n });\n respondJson(res, 200, { ok: true, file, appliesTo: 'future executions' });\n return;\n }\n\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n respondJson(res, 404, { error: 'Not found' });\n return;\n }\n\n if (path === '/api/status' || path === '/status.json') {\n const sessionId = requestUrl.searchParams.get('session');\n let snapshot: SessionSnapshot | undefined;\n if (sessionId !== null) {\n snapshot = source.get(sessionId);\n if (snapshot === undefined) {\n respondJson(res, 404, { error: `No active session with id '${sessionId}'.` });\n return;\n }\n } else {\n // Back-compat shorthand (US-005): with exactly one active session,\n // GET /api/status with no query string still answers it directly, the\n // same behavior a single-session run always had. Zero or several\n // active sessions is genuinely ambiguous without an id and answers an\n // explicit error instead of guessing.\n const active = source.list();\n if (active.length === 0) {\n respondJson(res, 404, {\n error: 'No active session. Pass ?session=<id> — see GET /api/sessions.',\n });\n return;\n }\n if (active.length > 1) {\n respondJson(res, 409, {\n error: 'Multiple active sessions; specify ?session=<id>.',\n sessions: active.map((entry) => entry.sessionId),\n });\n return;\n }\n snapshot = active[0];\n }\n\n const { body, etag } = statusPayload(snapshot);\n res.setHeader('ETag', etag);\n if (req.headers['if-none-match'] === etag) {\n res.statusCode = 304;\n res.end();\n return;\n }\n respond(res, 200, JSON_TYPE, body);\n return;\n }\n\n if (path === '/api/sessions') {\n // Summary fields for the multi-session dashboard (issue #35): the full\n // SessionSnapshot is already in memory, so the client can render cards\n // from this single list without N× /api/status fetches per poll.\n // issueDescription is truncated — cards only need a short preview.\n respondJson(\n res,\n 200,\n source.list().map((snapshot) => ({\n sessionId: snapshot.sessionId,\n issueNumber: snapshot.issue.number,\n issueTitle: snapshot.issue.title,\n issueDescription: truncateSessionDescription(snapshot.issue.description),\n repositoryName: snapshot.repository.name,\n currentPhase: snapshot.currentPhase,\n progressPercent: snapshot.progress.percent,\n elapsedSeconds: snapshot.elapsedSeconds,\n status: snapshot.status,\n startedAt: snapshot.startedAt,\n updatedAt: snapshot.updatedAt,\n // Resilience fields, for a card that has to answer \"is this still\n // moving\" during a six-hour run. `updatedAt` is already the last\n // activity; these two say how hard the run has had to work for it.\n retries: snapshot.execution.retries,\n correctionCycle: snapshot.execution.correctionCycle,\n attempt: snapshot.resilience.attempt,\n provider: snapshot.resilience.provider,\n lastFailureKind: snapshot.resilience.lastFailureKind,\n cooldownUntil: snapshot.resilience.cooldownUntil,\n lastActivityAt: snapshot.resilience.lastActivityAt,\n statusUrl: `/api/status?session=${encodeURIComponent(snapshot.sessionId ?? '')}`,\n eventsUrl: `/api/events?session=${encodeURIComponent(snapshot.sessionId ?? '')}`,\n })),\n );\n return;\n }\n\n if (path === '/api/events') {\n const sessionId = requestUrl.searchParams.get('session');\n if (sessionId === null) {\n respondJson(res, 400, { error: 'Pass ?session=<id>.' });\n return;\n }\n const entries = await source.events(sessionId);\n if (entries === undefined) {\n respondJson(res, 404, { error: `No active session with id '${sessionId}'.` });\n return;\n }\n respondJson(res, 200, entries);\n return;\n }\n\n if (path === '/api/diagnostics') {\n const sessionId = requestUrl.searchParams.get('session') ?? undefined;\n respondJson(res, 200, await readDiagnostics({ sessionId, limit: 500 }));\n return;\n }\n\n if (path === '/api/config') {\n const sessionId = requestUrl.searchParams.get('session');\n const snapshot = sessionId === null ? undefined : source.get(sessionId);\n respondJson(res, 200, {\n effective: snapshot?.configuration ?? null,\n capturedForSession: snapshot?.sessionId ?? null,\n writable: isLoopbackHost(options.host),\n writeScope: 'global preferences for future executions',\n });\n return;\n }\n\n if (path === '/api/health') {\n respondJson(res, 200, {\n ok: true,\n uptime: Math.round((Date.now() - startedAtMs) / 1000),\n version,\n refreshSeconds: options.refreshSeconds ?? 5,\n capabilities: isLoopbackHost(options.host) ? ['config:agent:write'] : [],\n });\n return;\n }\n\n const asset = assets.get(path);\n if (asset) {\n respond(res, 200, asset.contentType, asset.body);\n return;\n }\n\n respondJson(res, 404, { error: 'Not found' });\n };\n\n const server = createServer((req, res) => {\n void handleRequest(req, res).catch((err) => {\n try {\n respondJson(res, 500, { error: err instanceof Error ? err.message : String(err) });\n } catch {\n // Response already destroyed — nothing to do, never crash the process.\n }\n });\n });\n\n const listening = await new Promise<boolean>((resolve) => {\n const onError = (err: NodeJS.ErrnoException): void => {\n if (err.code === 'EADDRINUSE') {\n warn(\n `Web monitor port ${options.port} is already in use. Continuing without the web server.`,\n );\n } else {\n warn(`Web monitor failed to start (${err.message}). Continuing without the web server.`);\n }\n resolve(false);\n };\n server.once('error', onError);\n server.listen(options.port, options.host, () => {\n server.removeListener('error', onError);\n resolve(true);\n });\n });\n\n if (!listening) return null;\n\n // Never keep the process alive on its own, unless explicitly told not to\n // unref: the pipeline ending must end the process. The one exception is the\n // detached `web serve` process (options.unref === false) — it has no other\n // work, so staying alive for as long as the server is bound is the point.\n if (options.unref !== false) {\n server.unref();\n }\n // Post-listen errors must never become uncaught exceptions.\n server.on('error', (err) => {\n warn(`Web monitor server error: ${err.message}`);\n });\n\n const address = server.address() as AddressInfo;\n const port = address.port;\n const displayHost = options.host === '0.0.0.0' ? 'localhost' : options.host;\n const url = `http://${displayHost}:${port}`;\n\n if (options.host === '0.0.0.0') {\n warn('Web monitor bound to 0.0.0.0: anyone on your local network can view the session state.');\n }\n info(`Web monitor running at ${chalk.bold.cyan(url)}`);\n\n let closed = false;\n let closePromise: Promise<void> | null = null;\n\n const doClose = (): Promise<void> =>\n new Promise<void>((resolve) => {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onSignal);\n server.close(() => resolve());\n // Drop idle keep-alive connections so close() never hangs.\n server.closeAllConnections();\n });\n\n const close = (): Promise<void> => {\n if (closed) return closePromise ?? Promise.resolve();\n closed = true;\n closePromise = doClose();\n return closePromise;\n };\n\n // `handle.close` is built here, but ensureSingleWebServer/ensureWebMonitor\n // and the `web serve` command each wrap it afterwards (to also remove the\n // lock file, stop the session-directory poller, ...). onSignal below calls\n // `handle.close()` — the *current* value of the property — rather than the\n // `close` closed over here, so a `kill -TERM <pid>` (including `issue-flow\n // web stop`) always runs the fully wrapped shutdown, not just this raw\n // socket close. Capturing `close` directly here was a real bug: the wrapped\n // behavior only ever ran for an *explicit* `handle.close()` call, leaving\n // the lock file (and the poller) behind on every signal-driven shutdown.\n const handle: WebServerHandle = { server, host: options.host, port, url, close };\n\n // Explicit close on SIGINT/SIGTERM, then re-raise so the default\n // termination behavior still applies.\n const onSignal = (signal: NodeJS.Signals): void => {\n void handle.close().finally(() => {\n process.kill(process.pid, signal);\n });\n };\n process.once('SIGINT', onSignal);\n process.once('SIGTERM', onSignal);\n\n return handle;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAA4B,SAAS,iBAAiB;AACtD,SAAS,YAAAA,WAAU,IAAI,iBAAiB;AACxC,SAAS,QAAAC,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AG,CAAC,EAAE;AAC3E,aAAO,aAAa,OAAO;AAAA,IAC7B;AACA,UAAM,MAAM,MAAM;AAAA,EACpB;AAEA;AAAA,IACE;AAAA,EACF;AACA,SAAO;AACT;","names":["readFile","join","chalk","require","join","readFile","chalk"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
getGlobalRoot
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-HAKDLR6N.js";
|
|
5
5
|
import {
|
|
6
6
|
getProjectRoot
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-BEZ5BA5U.js";
|
|
8
8
|
import {
|
|
9
9
|
writeFileAtomic
|
|
10
10
|
} from "./chunk-7Z4Y3VKM.js";
|
|
@@ -74,4 +74,4 @@ export {
|
|
|
74
74
|
ensureCursorStorageGrant,
|
|
75
75
|
cursorStorageGranted
|
|
76
76
|
};
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
77
|
+
//# sourceMappingURL=chunk-OOVG2KBY.js.map
|
|
@@ -7,10 +7,10 @@ import {
|
|
|
7
7
|
isoNow,
|
|
8
8
|
loadTaskPlan,
|
|
9
9
|
saveTaskPlan
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-J3SOTUVI.js";
|
|
11
11
|
import {
|
|
12
12
|
executionPlanSchema
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-LBGHI4S2.js";
|
|
14
14
|
import {
|
|
15
15
|
writeFileAtomic
|
|
16
16
|
} from "./chunk-7Z4Y3VKM.js";
|
|
@@ -655,4 +655,4 @@ export {
|
|
|
655
655
|
setQueueBranch,
|
|
656
656
|
setQueuePullRequest
|
|
657
657
|
};
|
|
658
|
-
//# sourceMappingURL=chunk-
|
|
658
|
+
//# sourceMappingURL=chunk-OR43364P.js.map
|
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
NullPublisher
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import {
|
|
6
|
-
isoNow
|
|
7
|
-
} from "./chunk-DIG5XKQQ.js";
|
|
4
|
+
} from "./chunk-6QYMSNVA.js";
|
|
8
5
|
import {
|
|
9
6
|
getBaseBranch,
|
|
10
7
|
getCommitsSince,
|
|
@@ -15,7 +12,10 @@ import {
|
|
|
15
12
|
normalizeRemoteUrl,
|
|
16
13
|
run,
|
|
17
14
|
stripRemoteUrlCredentials
|
|
18
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-BEZ5BA5U.js";
|
|
16
|
+
import {
|
|
17
|
+
isoNow
|
|
18
|
+
} from "./chunk-J3SOTUVI.js";
|
|
19
19
|
|
|
20
20
|
// src/core/session-git.ts
|
|
21
21
|
async function listPullRequests(branch, options = {}) {
|
|
@@ -80,8 +80,9 @@ async function publishGitState(publisher, sources = {}) {
|
|
|
80
80
|
try {
|
|
81
81
|
const branch = await src.currentBranch();
|
|
82
82
|
const baseBranch = await src.baseBranch();
|
|
83
|
+
const commitBaseline = publisher.snapshot().git.branchCreated === false ? publisher.snapshot().git.startCommit ?? baseBranch : baseBranch;
|
|
83
84
|
const [commits, pullRequests, remoteUrl, headCommit, repositoryRoot] = await Promise.all([
|
|
84
|
-
src.commitsSince(
|
|
85
|
+
src.commitsSince(commitBaseline),
|
|
85
86
|
src.pullRequests(branch),
|
|
86
87
|
collect(() => src.remoteUrl()),
|
|
87
88
|
collect(() => src.headCommit()),
|
|
@@ -111,4 +112,4 @@ export {
|
|
|
111
112
|
listPullRequests,
|
|
112
113
|
publishGitState
|
|
113
114
|
};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
115
|
+
//# sourceMappingURL=chunk-PBTA3QQX.js.map
|