issue-flow 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -97
- package/dist/agent-4DHRKZ2Z.js +32 -0
- package/dist/{analyze-Q4ONIWRZ.js → analyze-UEJ2R3H5.js} +42 -41
- package/dist/analyze-UEJ2R3H5.js.map +1 -0
- package/dist/{apply-EEFPY2W4.js → apply-QDYNQMUX.js} +22 -24
- package/dist/apply-QDYNQMUX.js.map +1 -0
- package/dist/artifacts-AMJQJFFV.js +82 -0
- package/dist/artifacts-AMJQJFFV.js.map +1 -0
- package/dist/{bench-WWWXLTFH.js → bench-RNRXVEFK.js} +42 -42
- package/dist/{chunk-RYOUZ6EK.js → chunk-23VHVVKW.js} +3 -3
- package/dist/chunk-2EYLOS5I.js +99 -0
- package/dist/chunk-2EYLOS5I.js.map +1 -0
- package/dist/{chunk-C5TL7T4V.js → chunk-2YM2VH6R.js} +2 -2
- package/dist/{chunk-XUEMATVY.js → chunk-37O2FMAN.js} +28 -25
- package/dist/chunk-37O2FMAN.js.map +1 -0
- package/dist/chunk-44RF3VFG.js +717 -0
- package/dist/chunk-44RF3VFG.js.map +1 -0
- package/dist/chunk-6AOZCWN2.js +21 -0
- package/dist/chunk-6AOZCWN2.js.map +1 -0
- package/dist/chunk-7MJGYPHF.js +1571 -0
- package/dist/chunk-7MJGYPHF.js.map +1 -0
- package/dist/{chunk-SA6HXL4Y.js → chunk-7WBUEBD5.js} +9 -9
- package/dist/chunk-7WBUEBD5.js.map +1 -0
- package/dist/chunk-7ZZUSMBJ.js +35 -0
- package/dist/chunk-7ZZUSMBJ.js.map +1 -0
- package/dist/{chunk-QJ44VG5G.js → chunk-ADH6RJNX.js} +3 -3
- package/dist/{chunk-34OCSKOB.js → chunk-AKL5UPR6.js} +159 -114
- package/dist/chunk-AKL5UPR6.js.map +1 -0
- package/dist/{chunk-7F7LGMVO.js → chunk-BTBJ5UOO.js} +12 -12
- package/dist/{chunk-7F7LGMVO.js.map → chunk-BTBJ5UOO.js.map} +1 -1
- package/dist/{chunk-HOAHMERN.js → chunk-CLZ6RRZL.js} +21 -21
- package/dist/chunk-DBLXLKGU.js +1201 -0
- package/dist/chunk-DBLXLKGU.js.map +1 -0
- package/dist/{chunk-DUS5ZNKL.js → chunk-DIMDAYZS.js} +7 -6
- package/dist/chunk-DZ3DZ3EN.js +278 -0
- package/dist/chunk-DZ3DZ3EN.js.map +1 -0
- package/dist/{chunk-CRGIQFUQ.js → chunk-E2H3JV2E.js} +3 -1
- package/dist/chunk-E2H3JV2E.js.map +1 -0
- package/dist/{chunk-45WZ6GMI.js → chunk-EORDSKWZ.js} +17 -17
- package/dist/chunk-EORDSKWZ.js.map +1 -0
- package/dist/{chunk-LTH6XYZ3.js → chunk-EYKPWHT7.js} +40 -30
- package/dist/chunk-EYKPWHT7.js.map +1 -0
- package/dist/{chunk-OODXFCQV.js → chunk-FU2FQ4JE.js} +14 -16
- package/dist/{chunk-OODXFCQV.js.map → chunk-FU2FQ4JE.js.map} +1 -1
- package/dist/{chunk-V7QOIQYC.js → chunk-G442RDFX.js} +9 -23
- package/dist/{chunk-V7QOIQYC.js.map → chunk-G442RDFX.js.map} +1 -1
- package/dist/{chunk-QPGEFLMY.js → chunk-I64N6RL6.js} +7 -7
- package/dist/{chunk-KRAGAUKD.js → chunk-JBYXJOJJ.js} +201 -64
- package/dist/chunk-JBYXJOJJ.js.map +1 -0
- package/dist/{chunk-SOM4QA6C.js → chunk-JCR5C5A7.js} +93 -18
- package/dist/chunk-JCR5C5A7.js.map +1 -0
- package/dist/{chunk-RNFUVKC3.js → chunk-K5NM26NV.js} +30 -13
- package/dist/chunk-K5NM26NV.js.map +1 -0
- package/dist/{chunk-YVPZUN6X.js → chunk-KUA6KBBD.js} +335 -38
- package/dist/chunk-KUA6KBBD.js.map +1 -0
- package/dist/{chunk-KMCS76ZW.js → chunk-KUL64XUF.js} +44 -12
- package/dist/chunk-KUL64XUF.js.map +1 -0
- package/dist/{chunk-HAKDLR6N.js → chunk-MAJ6QDRL.js} +65 -78
- package/dist/chunk-MAJ6QDRL.js.map +1 -0
- package/dist/{chunk-DGRTJD5R.js → chunk-MML2G7IC.js} +7 -7
- package/dist/chunk-NP47HRX2.js +136 -0
- package/dist/chunk-NP47HRX2.js.map +1 -0
- package/dist/{chunk-3R27MJ5R.js → chunk-PFWHHYEO.js} +3 -3
- package/dist/{chunk-ECU7YO7S.js → chunk-PM5YWJYO.js} +22 -6
- package/dist/chunk-PM5YWJYO.js.map +1 -0
- package/dist/{chunk-E4I6MMHD.js → chunk-PXPTIXJF.js} +154 -101
- package/dist/chunk-PXPTIXJF.js.map +1 -0
- package/dist/{chunk-CWSQVHVV.js → chunk-QJHZ3HYJ.js} +248 -102
- package/dist/chunk-QJHZ3HYJ.js.map +1 -0
- package/dist/{chunk-LI35PIIS.js → chunk-RDPK7LYK.js} +20 -117
- package/dist/chunk-RDPK7LYK.js.map +1 -0
- package/dist/{chunk-PMLE7KAQ.js → chunk-RMIBLFG3.js} +30 -14
- package/dist/chunk-RMIBLFG3.js.map +1 -0
- package/dist/{chunk-62GVVZQO.js → chunk-T736DSZI.js} +32 -316
- package/dist/chunk-T736DSZI.js.map +1 -0
- package/dist/{chunk-TZYINKCC.js → chunk-UDUUUFQF.js} +57 -29
- package/dist/chunk-UDUUUFQF.js.map +1 -0
- package/dist/{chunk-NEWNXZ65.js → chunk-V7GETODQ.js} +36 -28
- package/dist/{chunk-NEWNXZ65.js.map → chunk-V7GETODQ.js.map} +1 -1
- package/dist/{chunk-PPZ3K4YM.js → chunk-VHQMMY2D.js} +2 -2
- package/dist/{chunk-ZVZMWNCG.js → chunk-VJ3PF6B7.js} +50 -16
- package/dist/chunk-VJ3PF6B7.js.map +1 -0
- package/dist/{chunk-L6HSKTQE.js → chunk-W7LZLJAF.js} +4 -4
- package/dist/{chunk-6K2LCFG6.js → chunk-WB4FA2EH.js} +70 -81
- package/dist/chunk-WB4FA2EH.js.map +1 -0
- package/dist/{chunk-LGHND47K.js → chunk-WQSGL5LX.js} +22 -16
- package/dist/chunk-WQSGL5LX.js.map +1 -0
- package/dist/{chunk-ICM463EO.js → chunk-XNK5UN2D.js} +5 -649
- package/dist/chunk-XNK5UN2D.js.map +1 -0
- package/dist/{chunk-7UMMFOL2.js → chunk-Y2KOWABB.js} +39 -24
- package/dist/chunk-Y2KOWABB.js.map +1 -0
- package/dist/{chunk-QF7VEL3M.js → chunk-YC24E66P.js} +568 -158
- package/dist/chunk-YC24E66P.js.map +1 -0
- package/dist/{chunk-EG2MGDP5.js → chunk-Z6RCKCVB.js} +52 -46
- package/dist/chunk-Z6RCKCVB.js.map +1 -0
- package/dist/{chunk-YUNBOUQH.js → chunk-ZPGNVBWY.js} +8 -8
- package/dist/cli.js +132 -62
- package/dist/cli.js.map +1 -1
- package/dist/compat-OJG76J4I.js +24 -0
- package/dist/{config-LEBZZCJP.js → config-6YTWPDBK.js} +20 -17
- package/dist/{contract-JH2WBIO6.js → contract-HWLFFL3F.js} +2 -2
- package/dist/{conventions-XOT6YW5L.js → conventions-5UPOTU42.js} +20 -16
- package/dist/{conventions-XOT6YW5L.js.map → conventions-5UPOTU42.js.map} +1 -1
- package/dist/db-QAZG4LQD.js +264 -0
- package/dist/db-QAZG4LQD.js.map +1 -0
- package/dist/diagnostics-YEFB42E5.js +25 -0
- package/dist/execute-QCT64D37.js +38 -0
- package/dist/{generate-JGW5JSKB.js → generate-QATMDKOK.js} +46 -43
- package/dist/generate-QATMDKOK.js.map +1 -0
- package/dist/{git-A2IP32PQ.js → git-XGOECXWG.js} +2 -3
- package/dist/history-NBPUZVGQ.js +101 -0
- package/dist/history-NBPUZVGQ.js.map +1 -0
- package/dist/init-4LB2YKWP.js +28 -0
- package/dist/{operations-O4FORFIH.js → operations-RUQP2Y2F.js} +78 -52
- package/dist/operations-RUQP2Y2F.js.map +1 -0
- package/dist/{permissions-G4XCAESF.js → permissions-QZPUUBSO.js} +5 -6
- package/dist/plan-2NMSHTMD.js +38 -0
- package/dist/{policy-U5NBFAO5.js → policy-RKKFF5A2.js} +17 -15
- package/dist/{policy-U5NBFAO5.js.map → policy-RKKFF5A2.js.map} +1 -1
- package/dist/pr-QKFO5HI3.js +42 -0
- package/dist/pr-review-H2BFD6F2.js +33 -0
- package/dist/prd-ET6XKYRS.js +37 -0
- package/dist/{ps-76L6ZAZL.js → ps-UIKSOUAQ.js} +26 -15
- package/dist/ps-UIKSOUAQ.js.map +1 -0
- package/dist/{recorder-2BAKPBRA.js → recorder-LOU3PTIE.js} +11 -7
- package/dist/registry-HV7M6MAH.js +17 -0
- package/dist/repository-RCRR6RDE.js +80 -0
- package/dist/resume-BWJZGBLZ.js +278 -0
- package/dist/resume-BWJZGBLZ.js.map +1 -0
- package/dist/review-2MTZLNSS.js +38 -0
- package/dist/routing-RM5ABHHD.js +35 -0
- package/dist/run-XMACQBRJ.js +61 -0
- package/dist/{session-publisher-KAJQRHNZ.js → session-publisher-Q5TNEZPX.js} +3 -3
- package/dist/session-publisher-Q5TNEZPX.js.map +1 -0
- package/dist/{state-manager-UPHO2EA2.js → state-manager-SRN4VJSX.js} +9 -4
- package/dist/state-manager-SRN4VJSX.js.map +1 -0
- package/dist/{usage-KTMYXAPF.js → usage-JOODVE5O.js} +69 -63
- package/dist/usage-JOODVE5O.js.map +1 -0
- package/dist/web-TLMWJ2BM.js +205 -0
- package/dist/web-TLMWJ2BM.js.map +1 -0
- package/package.json +22 -8
- package/prompts/analyze.md +16 -19
- package/prompts/execute.md +73 -144
- package/prompts/generate.md +23 -10
- package/prompts/plan.md +32 -60
- package/prompts/pr-review.md +58 -40
- package/prompts/pr.md +50 -16
- package/prompts/prd.md +26 -19
- package/prompts/review.md +41 -18
- package/web/public/app.js +111 -112
- package/dist/agent-HMZTXCRT.js +0 -30
- package/dist/analyze-Q4ONIWRZ.js.map +0 -1
- package/dist/apply-EEFPY2W4.js.map +0 -1
- package/dist/chunk-34OCSKOB.js.map +0 -1
- package/dist/chunk-45WZ6GMI.js.map +0 -1
- package/dist/chunk-62GVVZQO.js.map +0 -1
- package/dist/chunk-6K2LCFG6.js.map +0 -1
- package/dist/chunk-7UMMFOL2.js.map +0 -1
- package/dist/chunk-CRGIQFUQ.js.map +0 -1
- package/dist/chunk-CWSQVHVV.js.map +0 -1
- package/dist/chunk-E4I6MMHD.js.map +0 -1
- package/dist/chunk-ECU7YO7S.js.map +0 -1
- package/dist/chunk-EG2MGDP5.js.map +0 -1
- package/dist/chunk-HAKDLR6N.js.map +0 -1
- package/dist/chunk-ICM463EO.js.map +0 -1
- package/dist/chunk-KMCS76ZW.js.map +0 -1
- package/dist/chunk-KRAGAUKD.js.map +0 -1
- package/dist/chunk-LGHND47K.js.map +0 -1
- package/dist/chunk-LI35PIIS.js.map +0 -1
- package/dist/chunk-LTH6XYZ3.js.map +0 -1
- package/dist/chunk-PMLE7KAQ.js.map +0 -1
- package/dist/chunk-QF7VEL3M.js.map +0 -1
- package/dist/chunk-RNFUVKC3.js.map +0 -1
- package/dist/chunk-SA6HXL4Y.js.map +0 -1
- package/dist/chunk-SOM4QA6C.js.map +0 -1
- package/dist/chunk-TZYINKCC.js.map +0 -1
- package/dist/chunk-WCCZJL7W.js +0 -141
- package/dist/chunk-WCCZJL7W.js.map +0 -1
- package/dist/chunk-XEYH6ZZI.js +0 -289
- package/dist/chunk-XEYH6ZZI.js.map +0 -1
- package/dist/chunk-XUEMATVY.js.map +0 -1
- package/dist/chunk-XZUEFTUP.js +0 -243
- package/dist/chunk-XZUEFTUP.js.map +0 -1
- package/dist/chunk-YVPZUN6X.js.map +0 -1
- package/dist/chunk-ZVZMWNCG.js.map +0 -1
- package/dist/diagnostics-HTCWF7F4.js +0 -23
- package/dist/execute-LELOSR5T.js +0 -37
- package/dist/generate-JGW5JSKB.js.map +0 -1
- package/dist/init-TO6MUXO4.js +0 -26
- package/dist/operations-O4FORFIH.js.map +0 -1
- package/dist/plan-OXAT344Q.js +0 -34
- package/dist/pr-UZHNKKZC.js +0 -39
- package/dist/pr-review-Q4ACAWDM.js +0 -32
- package/dist/prd-6CYEMLDY.js +0 -33
- package/dist/ps-76L6ZAZL.js.map +0 -1
- package/dist/registry-XLHHYLTR.js +0 -15
- package/dist/resume-URCU6CIJ.js +0 -244
- package/dist/resume-URCU6CIJ.js.map +0 -1
- package/dist/review-LVZT2TMW.js +0 -35
- package/dist/routing-EK6RBZM4.js +0 -33
- package/dist/run-2RXJCJKT.js +0 -56
- package/dist/usage-KTMYXAPF.js.map +0 -1
- package/dist/web-B5UPHHR5.js +0 -172
- package/dist/web-B5UPHHR5.js.map +0 -1
- /package/dist/{agent-HMZTXCRT.js.map → agent-4DHRKZ2Z.js.map} +0 -0
- /package/dist/{bench-WWWXLTFH.js.map → bench-RNRXVEFK.js.map} +0 -0
- /package/dist/{chunk-RYOUZ6EK.js.map → chunk-23VHVVKW.js.map} +0 -0
- /package/dist/{chunk-C5TL7T4V.js.map → chunk-2YM2VH6R.js.map} +0 -0
- /package/dist/{chunk-QJ44VG5G.js.map → chunk-ADH6RJNX.js.map} +0 -0
- /package/dist/{chunk-HOAHMERN.js.map → chunk-CLZ6RRZL.js.map} +0 -0
- /package/dist/{chunk-DUS5ZNKL.js.map → chunk-DIMDAYZS.js.map} +0 -0
- /package/dist/{chunk-QPGEFLMY.js.map → chunk-I64N6RL6.js.map} +0 -0
- /package/dist/{chunk-DGRTJD5R.js.map → chunk-MML2G7IC.js.map} +0 -0
- /package/dist/{chunk-3R27MJ5R.js.map → chunk-PFWHHYEO.js.map} +0 -0
- /package/dist/{chunk-PPZ3K4YM.js.map → chunk-VHQMMY2D.js.map} +0 -0
- /package/dist/{chunk-L6HSKTQE.js.map → chunk-W7LZLJAF.js.map} +0 -0
- /package/dist/{chunk-YUNBOUQH.js.map → chunk-ZPGNVBWY.js.map} +0 -0
- /package/dist/{config-LEBZZCJP.js.map → compat-OJG76J4I.js.map} +0 -0
- /package/dist/{contract-JH2WBIO6.js.map → config-6YTWPDBK.js.map} +0 -0
- /package/dist/{diagnostics-HTCWF7F4.js.map → contract-HWLFFL3F.js.map} +0 -0
- /package/dist/{execute-LELOSR5T.js.map → diagnostics-YEFB42E5.js.map} +0 -0
- /package/dist/{git-A2IP32PQ.js.map → execute-QCT64D37.js.map} +0 -0
- /package/dist/{init-TO6MUXO4.js.map → git-XGOECXWG.js.map} +0 -0
- /package/dist/{permissions-G4XCAESF.js.map → init-4LB2YKWP.js.map} +0 -0
- /package/dist/{plan-OXAT344Q.js.map → permissions-QZPUUBSO.js.map} +0 -0
- /package/dist/{pr-UZHNKKZC.js.map → plan-2NMSHTMD.js.map} +0 -0
- /package/dist/{pr-review-Q4ACAWDM.js.map → pr-QKFO5HI3.js.map} +0 -0
- /package/dist/{prd-6CYEMLDY.js.map → pr-review-H2BFD6F2.js.map} +0 -0
- /package/dist/{recorder-2BAKPBRA.js.map → prd-ET6XKYRS.js.map} +0 -0
- /package/dist/{registry-XLHHYLTR.js.map → recorder-LOU3PTIE.js.map} +0 -0
- /package/dist/{review-LVZT2TMW.js.map → registry-HV7M6MAH.js.map} +0 -0
- /package/dist/{routing-EK6RBZM4.js.map → repository-RCRR6RDE.js.map} +0 -0
- /package/dist/{run-2RXJCJKT.js.map → review-2MTZLNSS.js.map} +0 -0
- /package/dist/{session-publisher-KAJQRHNZ.js.map → routing-RM5ABHHD.js.map} +0 -0
- /package/dist/{state-manager-UPHO2EA2.js.map → run-XMACQBRJ.js.map} +0 -0
package/dist/agent-HMZTXCRT.js
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
AGENT_COMMAND_SCHEMA_VERSION,
|
|
4
|
-
persistFirstAgentChoice,
|
|
5
|
-
runAgent,
|
|
6
|
-
runAgentUse,
|
|
7
|
-
writeAgentPreference
|
|
8
|
-
} from "./chunk-45WZ6GMI.js";
|
|
9
|
-
import "./chunk-QF7VEL3M.js";
|
|
10
|
-
import "./chunk-LI35PIIS.js";
|
|
11
|
-
import "./chunk-XZUEFTUP.js";
|
|
12
|
-
import "./chunk-QPGEFLMY.js";
|
|
13
|
-
import "./chunk-HAKDLR6N.js";
|
|
14
|
-
import "./chunk-YVPZUN6X.js";
|
|
15
|
-
import "./chunk-DUS5ZNKL.js";
|
|
16
|
-
import "./chunk-6K2LCFG6.js";
|
|
17
|
-
import "./chunk-PPZ3K4YM.js";
|
|
18
|
-
import "./chunk-SOM4QA6C.js";
|
|
19
|
-
import "./chunk-ICM463EO.js";
|
|
20
|
-
import "./chunk-XEYH6ZZI.js";
|
|
21
|
-
import "./chunk-P3LRUNC6.js";
|
|
22
|
-
import "./chunk-3R27MJ5R.js";
|
|
23
|
-
export {
|
|
24
|
-
AGENT_COMMAND_SCHEMA_VERSION,
|
|
25
|
-
persistFirstAgentChoice,
|
|
26
|
-
runAgent,
|
|
27
|
-
runAgentUse,
|
|
28
|
-
writeAgentPreference
|
|
29
|
-
};
|
|
30
|
-
//# sourceMappingURL=agent-HMZTXCRT.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/analyze.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { DEFAULT_HEADLESS_TIMEOUT_MS, runHeadless } from '../core/headless.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { ResolvedIssue } from '../issues/types.js';\nimport { resolvePolicyPlaceholders } from '../policy/placeholders.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport { printError, printInfo, printSuccess } from '../ui/logger.js';\n\nexport async function runAnalyze(issue: string, resolvedIssue?: ResolvedIssue): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n const analysisPath = paths.analysisFile;\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n await mkdir(paths.issueDir, { recursive: true });\n\n const template = await loadPrompt('analyze');\n const prompt = applyPlaceholders(template, {\n // The repository's own conventions. Empty when it declares none, which is\n // what keeps the rendered prompt identical to the pre-policy one.\n ...(await resolvePolicyPlaceholders()),\n __ISSUE_NUMBER__: issueNumber,\n __ANALYSIS_PATH__: analysisPath,\n // Last: the Issue content is substituted in but never scanned again, so a\n // body that happens to contain a placeholder is left untouched.\n ...issuePlaceholders(resolution.resolved),\n });\n\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 30,\n timeout: getGlobalTimeout() ?? DEFAULT_HEADLESS_TIMEOUT_MS,\n // json (not text) so the CLI reports usage: the envelope's `result` field\n // carries the same assistant text this phase already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep', 'Write'],\n addDirs: [paths.issueDir],\n statusMessage: `Analyzing issue #${issueNumber}...`,\n phase: 'analyze',\n permission: 'read-only',\n });\n // Before the success check: the tokens were spent either way.\n publishPhaseMetrics('analyze', result.cost, startedAtMs, result.agent?.provider);\n\n if (!result.success) {\n printError(`Analysis failed: ${result.error}`);\n return 1;\n }\n\n // Verify the file was created\n try {\n const content = await readFile(analysisPath, 'utf-8');\n if (content.length < 10) {\n printError('Analysis file was created but appears empty');\n return 1;\n }\n } catch {\n // File wasn't created by headless — save the result as analysis\n printInfo('Headless did not create analysis file; saving output directly');\n await writeFile(analysisPath, result.result, 'utf-8');\n }\n\n // Update pipeline state\n const tasksPath = paths.tasksFile;\n try {\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.analyzeCompleted = true;\n await saveTaskPlan(tasksPath, plan);\n } catch {\n // tasks.json may not exist yet — that's OK for standalone analyze\n }\n\n printSuccess(`Analysis saved to ${analysisPath}`);\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;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AAQ;AAEN,cAAU,+DAA+D;AACzE,UAAM,UAAU,cAAc,OAAO,QAAQ,OAAO;AAAA,EACtD;AAGA,QAAM,YAAY,MAAM;AACxB,MAAI;AACF,UAAM,OAAO,MAAM,aAAa,SAAS;AACzC,SAAK,SAAS,mBAAmB;AACjC,UAAM,aAAa,WAAW,IAAI;AAAA,EACpC,QAAQ;AAAA,EAER;AAEA,eAAa,qBAAqB,YAAY,EAAE;AAChD,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/scaffold/apply.ts","../src/scaffold/plan.ts","../src/conventions/defaults.ts","../src/scaffold/assets.ts"],"sourcesContent":["import { access, mkdir, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { loadRepositoryPolicy } from '../policy/index.js';\nimport { getProjectRoot } from '../utils/git.js';\nimport { buildScaffoldPlan, type RepositoryState, type ScaffoldPlan } from './plan.js';\n\n/**\n * Turning a plan into files — and the one place that writes anything.\n *\n * Writing is deliberately dumber than planning: it creates what the plan marked\n * `create` and touches nothing else. Every judgement about whether a file should\n * exist was already made, from the resolved policy, in `plan.ts`.\n */\n\nexport interface ApplyResult {\n written: string[];\n /** Marked `create` but found on disk between planning and writing. */\n skipped: string[];\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Write the `create` actions of a plan.\n *\n * Re-checks existence immediately before each write. The plan is built from the\n * resolved policy, which is cached for the process, so a file created between\n * the two would otherwise be overwritten — and \"initialization is\n * non-destructive\" has to hold even against itself.\n */\nexport async function applyScaffoldPlan(plan: ScaffoldPlan): Promise<ApplyResult> {\n const written: string[] = [];\n const skipped: string[] = [];\n\n for (const item of plan.actions) {\n if (item.kind !== 'create' || item.content === undefined) continue;\n\n const absolute = join(plan.root, item.path);\n if (await exists(absolute)) {\n skipped.push(item.path);\n continue;\n }\n\n await mkdir(dirname(absolute), { recursive: true });\n await writeFile(absolute, item.content, 'utf-8');\n written.push(item.path);\n }\n\n return { written, skipped };\n}\n\nexport interface ResolveStateOptions {\n /** Repository root. Defaults to the git project root. */\n root?: string;\n /** Subdirectory the conventions apply to, for monorepos. */\n scope?: string | null;\n}\n\n/**\n * The repository state the planner reads, assembled from the policy layer.\n *\n * There is no second discovery here on purpose: initialization sees exactly the\n * repository every other flow sees, so it can never propose a convention that\n * discovery already found.\n */\nexport async function resolveRepositoryState(\n options: ResolveStateOptions = {},\n): Promise<RepositoryState> {\n const root = options.root ?? (await getProjectRoot());\n const policy = await loadRepositoryPolicy({ root, scope: options.scope ?? null });\n\n return {\n policy,\n projectName: basename(root),\n exists: (relPath: string) => exists(join(root, relPath)),\n };\n}\n\n/** Resolve the state and build the plan, without writing anything. */\nexport async function planRepositoryScaffold(\n options: ResolveStateOptions = {},\n): Promise<ScaffoldPlan> {\n return buildScaffoldPlan(await resolveRepositoryState(options));\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { DEFAULT_ISSUE_TYPES } from '../conventions/defaults.js';\nimport type { RepositoryPolicy } from '../policy/types.js';\nimport {\n renderAgentsMd,\n renderClaudeMd,\n renderConventionsDoc,\n renderIssueForm,\n renderIssueTemplateConfig,\n renderLabelsFile,\n renderPullRequestTemplate,\n type ScaffoldAsset,\n} from './assets.js';\n\n/**\n * Deciding what a repository is missing — the shared core behind both the CLI\n * and the initialization skill.\n *\n * The plan is produced from the **resolved policy**, never from a fresh scan:\n * initialization and every other flow therefore see the same repository, and a\n * convention that discovery already found can never be proposed a second time.\n *\n * Two properties matter more than the file list.\n *\n * **Non-destructive.** Nothing that exists is ever overwritten. A repository\n * that already declares a convention keeps it, even when it differs from the\n * default — the whole point of the tool is to adapt to the repository, and\n * \"initialize\" must not become a euphemism for \"replace\".\n *\n * **Idempotent.** Running it twice changes nothing the second time, because the\n * plan is computed from what is present rather than from what a previous run\n * did.\n */\n\n/** What initialization intends to do with one file. */\nexport type ScaffoldActionKind =\n /** The file does not exist and the repository has no equivalent. */\n | 'create'\n /** Something equivalent already exists; initialization stays out of the way. */\n | 'keep'\n /**\n * Present, but inconsistent with the convention it claims to follow. Reported,\n * never rewritten: the repository may be right and the tool wrong.\n */\n | 'review';\n\nexport interface ScaffoldAction {\n path: string;\n kind: ScaffoldActionKind;\n tier: ScaffoldAsset['tier'];\n /** Why this action was chosen, in one sentence, for the report. */\n reason: string;\n /** Content to write. Only present for `create`. */\n content?: string;\n}\n\nexport interface ScaffoldPlan {\n root: string;\n /** Every action, in a stable order. */\n actions: ScaffoldAction[];\n /** Notes that are not tied to a single file. */\n notes: string[];\n}\n\n/** Everything the plan needs to know about the repository's current state. */\nexport interface RepositoryState {\n policy: RepositoryPolicy;\n /** Whether a repository-relative path exists. */\n exists(relPath: string): Promise<boolean>;\n /** Name to head `AGENTS.md` with. */\n projectName: string;\n}\n\nfunction action(\n path: string,\n kind: ScaffoldActionKind,\n tier: ScaffoldAsset['tier'],\n reason: string,\n content?: string,\n): ScaffoldAction {\n return content === undefined\n ? { path, kind, tier, reason }\n : { path, kind, tier, reason, content };\n}\n\n/**\n * Whether a `CLAUDE.md` is already the one-line bridge the convention asks for.\n *\n * A file that merely *mentions* `AGENTS.md` in the middle of its own\n * instructions is not a bridge — it is a second source that happens to cite the\n * first. The test is therefore about size and shape, not about a substring.\n */\nexport function isClaudeBridge(content: string): boolean {\n const meaningful = content\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line !== '' && !line.startsWith('#'));\n\n if (meaningful.length === 0 || meaningful.length > 2) return false;\n return meaningful.every((line) => /agents\\.md/i.test(line));\n}\n\n/**\n * Build the plan.\n *\n * `write` is what the caller intends to do with it; the plan itself never\n * touches the filesystem, which is what lets the CLI show it and the skill\n * reason about it before anything happens.\n */\nexport async function buildScaffoldPlan(state: RepositoryState): Promise<ScaffoldPlan> {\n const { policy } = state;\n const actions: ScaffoldAction[] = [];\n const notes: string[] = [];\n\n // ── Issue Templates ───────────────────────────────────────────────────────\n const localTemplates = policy.issues.templates.filter((t) => t.origin === 'filesystem');\n const orgTemplates = policy.issues.templates.filter((t) => t.origin === 'organization');\n\n if (localTemplates.length > 0) {\n actions.push(\n action(\n '.github/ISSUE_TEMPLATE/',\n 'keep',\n 'required',\n `${localTemplates.length} Issue Template(s) already declared in this repository.`,\n ),\n );\n } else if (orgTemplates.length > 0) {\n // The organization already answered this, and a local copy would fork it:\n // the org file is then edited once and the repository silently stops\n // following it.\n actions.push(\n action(\n '.github/ISSUE_TEMPLATE/',\n 'keep',\n 'required',\n `The organization serves ${orgTemplates.length} Issue Template(s) to this repository; a local copy would fork them.`,\n ),\n );\n notes.push(\n 'Issue Templates come from the organization. Change them there, not here — a local copy stops tracking the original the moment either is edited.',\n );\n } else {\n for (const type of DEFAULT_ISSUE_TYPES) {\n const path = `.github/ISSUE_TEMPLATE/${type.order}-${type.slug}.yml`;\n actions.push(\n action(\n path,\n 'create',\n 'required',\n `Issue Form for the \"${type.name}\" type.`,\n renderIssueForm(type),\n ),\n );\n }\n const configPath = '.github/ISSUE_TEMPLATE/config.yml';\n actions.push(\n action(\n configPath,\n (await state.exists(configPath)) ? 'keep' : 'create',\n 'required',\n 'Template chooser: keeps blank issues enabled and links the conventions.',\n renderIssueTemplateConfig(),\n ),\n );\n }\n\n // ── Pull Request template ────────────────────────────────────────────────\n if (policy.pullRequests.templates.length > 0) {\n actions.push(\n action(\n policy.pullRequests.templates[0]?.path ?? '.github/PULL_REQUEST_TEMPLATE.md',\n 'keep',\n 'required',\n 'A Pull Request template already exists.',\n ),\n );\n } else {\n actions.push(\n action(\n '.github/PULL_REQUEST_TEMPLATE.md',\n 'create',\n 'required',\n 'Gives every Pull Request a body that review can rely on.',\n renderPullRequestTemplate(),\n ),\n );\n }\n\n // ── Agent entry points ───────────────────────────────────────────────────\n const agents = policy.docs.find((doc) => doc.kind === 'agents' && doc.scope === '');\n const claude = policy.docs.find((doc) => doc.kind === 'claude' && doc.scope === '');\n\n const referenced = policy.docs\n .filter((doc) => doc.kind === 'contributing' || doc.kind === 'referenced')\n .map((doc) => doc.path);\n\n if (agents === undefined) {\n actions.push(\n action(\n 'AGENTS.md',\n 'create',\n 'required',\n 'The canonical entry point for any coding agent, as an index of the real documentation.',\n renderAgentsMd(state.projectName, referenced),\n ),\n );\n } else {\n actions.push(action('AGENTS.md', 'keep', 'required', 'Already the canonical entry point.'));\n }\n\n if (claude === undefined) {\n actions.push(\n action(\n 'CLAUDE.md',\n 'create',\n 'recommended',\n 'One-line bridge to AGENTS.md, so Claude Code reads the canonical source.',\n renderClaudeMd(),\n ),\n );\n } else if (isClaudeBridge(claude.content)) {\n actions.push(action('CLAUDE.md', 'keep', 'recommended', 'Already a bridge to AGENTS.md.'));\n } else if (agents === undefined) {\n // The common migration: instructions live in CLAUDE.md and there is no\n // AGENTS.md. Promoting the content is the user's call — the tool says so\n // rather than moving text it did not write.\n notes.push(\n 'CLAUDE.md carries its own instructions and there is no AGENTS.md. Move that content into AGENTS.md and reduce CLAUDE.md to the one-line bridge; nothing here rewrites it for you.',\n );\n actions.push(\n action(\n 'CLAUDE.md',\n 'review',\n 'recommended',\n 'Holds instructions of its own; AGENTS.md should be the canonical source.',\n ),\n );\n } else {\n notes.push(\n 'AGENTS.md and CLAUDE.md both carry instructions. Two copies of the same rules diverge the first time only one is edited — keep AGENTS.md and reduce CLAUDE.md to the one-line bridge.',\n );\n actions.push(\n action(\n 'CLAUDE.md',\n 'review',\n 'recommended',\n 'Duplicates instructions that AGENTS.md already owns.',\n ),\n );\n }\n\n // ── Documented conventions ───────────────────────────────────────────────\n const hasContributing = policy.docs.some((doc) => doc.kind === 'contributing');\n const conventionsPath = 'docs/conventions.md';\n const conventionsExists = await state.exists(conventionsPath);\n\n if (conventionsExists) {\n actions.push(\n action(conventionsPath, 'keep', 'recommended', 'Conventions are already documented.'),\n );\n } else if (orgTemplates.length > 0) {\n // The conventions are the organization's, and they are documented wherever\n // the organization documents them. A per-repository copy would be a second\n // source that drifts from the one everybody else follows.\n actions.push(\n action(\n conventionsPath,\n 'keep',\n 'recommended',\n \"The conventions are the organization's; documenting them again here would fork them.\",\n ),\n );\n } else if (hasContributing && localTemplates.length > 0) {\n // The repository already says how it works, in its own words and its own\n // file. A second document would be a competing source, which is the exact\n // failure this tool exists to avoid.\n actions.push(\n action(\n conventionsPath,\n 'keep',\n 'recommended',\n 'CONTRIBUTING.md and the Issue Templates already document how this repository works.',\n ),\n );\n } else {\n actions.push(\n action(\n conventionsPath,\n 'create',\n 'recommended',\n 'The source of truth for issue types, labels, branches and commits.',\n renderConventionsDoc(policy.issues.types.length > 0),\n ),\n );\n }\n\n // ── Labels ───────────────────────────────────────────────────────────────\n const labelsPath = '.github/labels.json';\n if (policy.issues.labels.length > 0) {\n actions.push(\n action(\n labelsPath,\n 'keep',\n 'contextual',\n `This repository already has ${policy.issues.labels.length} label(s); Issue Flow never rewrites a taxonomy.`,\n ),\n );\n } else if (await state.exists(labelsPath)) {\n actions.push(action(labelsPath, 'keep', 'contextual', 'A labels file already exists.'));\n } else {\n const includeTypeLabels = policy.issues.types.length === 0;\n actions.push(\n action(\n labelsPath,\n 'create',\n 'contextual',\n includeTypeLabels\n ? 'A baseline label set, including type labels because this organization has no Issue Types.'\n : 'A baseline label set. Type labels are omitted: this organization has native Issue Types.',\n renderLabelsFile(includeTypeLabels),\n ),\n );\n }\n\n if (policy.issues.types.length === 0) {\n notes.push(\n 'No GitHub Issue Types were found. They are an organization-level setting and cannot be created from here; defining them there is better than the `type:*` labels this proposes as a fallback.',\n );\n }\n\n return { root: policy.root, actions, notes };\n}\n\n/** Load a repository file, or null. Used by the state adapter and by tests. */\nexport async function readIfPresent(root: string, relPath: string): Promise<string | null> {\n try {\n return await readFile(join(root, relPath), 'utf-8');\n } catch {\n return null;\n }\n}\n","/**\n * The default convention set — Issue Flow's fallback when a repository declares\n * nothing of its own.\n *\n * This is the **last** rung of the precedence ladder, and it only ever applies\n * where the repository, its organization and the user's configuration are all\n * silent. It exists so that a brand-new repository still gets a usable,\n * professional baseline instead of an empty one.\n *\n * Two rules shaped every choice here.\n *\n * **Native structure before textual convention.** The preference order is\n * `native feature > structured field > label > free text`. Anything GitHub\n * already models — the type of an issue, its priority, its state — is not\n * re-implemented as a title prefix or a label, because that creates a second\n * truth that ages on its own. GitHub's own defaults are `task`, `bug` and\n * `feature`, and an organization may define up to 25 Issue Types.\n *\n * **Do not fragment the backlog.** A type per flavour of work makes no query\n * better and every filter worse. Documentation, maintenance, refactoring and\n * technical debt are *characteristics*, not natures, and they belong on labels\n * over a real type.\n */\n\n/** A default Issue Type, with the reasoning a template and a report can quote. */\nexport interface DefaultIssueType {\n /** Display name, matching GitHub's Issue Type casing convention. */\n name: string;\n /** Slug used for the Issue Form file name, prefixed by `order`. */\n slug: string;\n /** Order in the template chooser: capture first, execution last. */\n order: number;\n /** One line: what this type is. */\n summary: string;\n /**\n * Whether an issue of this type is executable once it is ready.\n *\n * The distinction matters more than it looks: an open issue is not approved\n * work. `Idea`, `Research` and `Epic` record intent and never authorize an\n * agent to start implementing.\n */\n executable: boolean;\n /** GitHub's own default types, which exist in every organization. */\n native: boolean;\n}\n\n/**\n * Six types, not thirteen.\n *\n * `Bug`, `Feature` and `Task` are GitHub's native defaults and cover all\n * executable work. `Idea`, `Research` and `Epic` are added because each answers\n * a question the other three cannot: *is this even worth doing*, *what is the\n * answer*, and *what is the umbrella*. Everything else the user might expect —\n * documentation, maintenance, refactor, technical debt, security, spike — is\n * deliberately **not** a type; see {@link NON_TYPES}.\n */\nexport const DEFAULT_ISSUE_TYPES: readonly DefaultIssueType[] = [\n {\n name: 'Idea',\n slug: 'idea',\n order: 1,\n summary: 'A hypothesis, opportunity or perceived problem, not yet analysed.',\n executable: false,\n native: false,\n },\n {\n name: 'Research',\n slug: 'research',\n order: 2,\n summary: 'An investigation that produces knowledge: analysis, benchmark, feasibility.',\n executable: false,\n native: false,\n },\n {\n name: 'Epic',\n slug: 'epic',\n order: 3,\n summary: 'An umbrella objective delivered through sub-issues.',\n executable: false,\n native: false,\n },\n {\n name: 'Feature',\n slug: 'feature',\n order: 4,\n summary: 'A new capability or a change to what the product does.',\n executable: true,\n native: true,\n },\n {\n name: 'Bug',\n slug: 'bug',\n order: 5,\n summary: 'Existing behaviour that diverges from what is expected.',\n executable: true,\n native: true,\n },\n {\n name: 'Task',\n slug: 'task',\n order: 6,\n summary: 'Concrete work that is neither a feature nor a bug.',\n executable: true,\n native: true,\n },\n] as const;\n\n/** Something people often expect to be a type, and why it is not one here. */\nexport interface NonType {\n concept: string;\n /** How to represent it instead. */\n instead: string;\n why: string;\n}\n\n/**\n * The list is as much a part of the convention as the types themselves: without\n * it, every repository re-derives the same six arguments and reaches a different\n * answer.\n */\nexport const NON_TYPES: readonly NonType[] = [\n {\n concept: 'Documentation',\n instead: '`Task` + label `docs`',\n why: 'The work is a task; what varies is the area it touches.',\n },\n {\n concept: 'Maintenance, chore',\n instead: '`Task`',\n why: 'That is already what `Task` means.',\n },\n {\n concept: 'Refactor, technical debt',\n instead: '`Task` + label `tech-debt`',\n why: 'A cross-cutting characteristic, not a distinct nature of work.',\n },\n {\n concept: 'Security',\n instead: 'the real type (`Bug`/`Task`/`Feature`) + label `security`',\n why: 'It cuts across every type; as a type it would hide whether the item is a flaw or preventive work.',\n },\n {\n concept: 'Spike, investigation',\n instead: '`Research`',\n why: 'The same concept under a different name.',\n },\n {\n concept: 'Enhancement',\n instead: '`Feature`',\n why: 'A change to what the product does is a feature, whether it is new or an improvement.',\n },\n {\n concept: 'Proposal, RFC',\n instead: '`Research`, and an ADR for the decision it produces',\n why: 'The issue carries the investigation; the decision belongs in a document that outlives it.',\n },\n {\n concept: 'Question',\n instead: 'a Discussion, or `Research` when it needs work',\n why: 'A question that needs no work is not a backlog item.',\n },\n] as const;\n\n/** A default label, with the reason it exists. */\nexport interface DefaultLabel {\n name: string;\n description: string;\n /** Hex colour without `#`, matching GitHub's palette conventions. */\n color: string;\n}\n\n/**\n * A deliberately small vocabulary, for what has **no native representation**:\n * technical area, component and cross-cutting characteristic.\n *\n * Nothing here duplicates a field. There is no `priority`, no `status`, no\n * `type` and no size label: GitHub models all four, and a label alongside a\n * field is a second truth that drifts. The one exception is\n * {@link FALLBACK_TYPE_LABELS}, for repositories whose organization has no Issue\n * Types at all.\n */\nexport const DEFAULT_LABELS: readonly DefaultLabel[] = [\n { name: 'api', description: 'Public interfaces and contracts', color: '006b75' },\n { name: 'backend', description: 'Server-side code', color: '5319e7' },\n { name: 'frontend', description: 'User-facing code', color: 'bfd4f2' },\n { name: 'database', description: 'Schema, queries and migrations', color: 'c2e0c6' },\n { name: 'infra', description: 'Infrastructure, CI and deployment', color: 'f9d0c4' },\n { name: 'docs', description: 'Documentation', color: '0075ca' },\n { name: 'security', description: 'Security or privacy impact', color: 'd93f0b' },\n {\n name: 'tech-debt',\n description: 'Debt paid down rather than capability added',\n color: 'e4e669',\n },\n { name: 'blocked', description: 'Waiting on something outside this repository', color: 'b60205' },\n { name: 'good first issue', description: 'Good for newcomers', color: '7057ff' },\n] as const;\n\n/**\n * Type labels, used **only** where the organization has no Issue Types.\n *\n * A repository that cannot use the native field still needs the type to be\n * queryable, and a label is the next best representation. The moment Issue Types\n * exist, these become the second truth the convention warns about — which is why\n * scaffolding proposes them only after finding none.\n */\nexport const FALLBACK_TYPE_LABELS: readonly DefaultLabel[] = DEFAULT_ISSUE_TYPES.map((type) => ({\n name: `type:${type.slug}`,\n description: type.summary,\n color: type.executable ? '1d76db' : 'd4c5f9',\n}));\n\n/**\n * The sections an issue body is expected to carry, by default.\n *\n * Kept short on purpose. A twelve-section template is excellent for an\n * architectural proposal and hostile to capturing an idea, and a form nobody\n * fills in honestly is worse than no form. Each default Issue Form asks only\n * what its type actually needs; this list is what the *prose* fallback uses when\n * a repository has no forms at all.\n */\nexport const DEFAULT_BODY_SECTIONS: readonly string[] = [\n 'Context',\n 'Problem',\n 'Objective',\n 'Scope',\n 'Out of scope',\n 'Acceptance criteria',\n 'Dependencies',\n 'Risks',\n 'References',\n] as const;\n\nimport { DEFAULT_BRANCH_CONVENTION } from './git/index.js';\n\nexport { DEFAULT_BRANCH_CONVENTION };\n\n/**\n * Commit convention.\n *\n * Conventional Commits is the closest thing to a lingua franca, and it is what\n * makes a changelog and a semver bump derivable from the history — which is\n * exactly why the type must reflect the change instead of always being `feat`.\n */\nexport const DEFAULT_COMMIT_CONVENTION = 'Conventional Commits — type(scope): subject';\n\n/**\n * Issue title convention.\n *\n * `null` on purpose: with Issue Types, a `[Bug]` prefix restates in text what a\n * structured field already carries. A repository whose organization has no Issue\n * Types may want one, and declares it.\n */\nexport const DEFAULT_ISSUE_TITLE_CONVENTION: string | null = null;\n\n/** Everything above, as one object, for the report and the scaffolding plan. */\nexport const DEFAULT_CONVENTIONS = {\n issueTypes: DEFAULT_ISSUE_TYPES,\n nonTypes: NON_TYPES,\n labels: DEFAULT_LABELS,\n fallbackTypeLabels: FALLBACK_TYPE_LABELS,\n bodySections: DEFAULT_BODY_SECTIONS,\n branchConvention: DEFAULT_BRANCH_CONVENTION,\n commitConvention: DEFAULT_COMMIT_CONVENTION,\n issueTitleConvention: DEFAULT_ISSUE_TITLE_CONVENTION,\n} as const;\n","import {\n DEFAULT_COMMIT_CONVENTION,\n DEFAULT_ISSUE_TYPES,\n DEFAULT_LABELS,\n type DefaultIssueType,\n FALLBACK_TYPE_LABELS,\n NON_TYPES,\n} from '../conventions/defaults.js';\nimport { DEFAULT_BRANCH_CONVENTION } from '../conventions/git/index.js';\n\n/**\n * The files initialization can write, rendered from the default convention set.\n *\n * Nothing here is a literal copy of a template: every asset is generated from\n * `conventions/defaults.ts`, so the convention and the files that express it can\n * never disagree. Changing a type or a label changes the forms, the labels file\n * and the documentation in one edit.\n */\n\nexport interface ScaffoldAsset {\n /** Repository-relative path, POSIX separators. */\n path: string;\n content: string;\n /**\n * Why this file exists. Shown in the plan, so a user can decline a specific\n * one and understand what they are declining.\n */\n purpose: string;\n /**\n * `required` files are what makes a repository legible to an agent at all.\n * `recommended` ones are worth having; `contextual` ones are only proposed\n * when the repository's state calls for them.\n */\n tier: 'required' | 'recommended' | 'contextual';\n}\n\n/** Fields every executable type needs, and no type should be without. */\nfunction acceptanceCriteriaField(): string {\n return [\n ' - type: textarea',\n ' id: acceptance',\n ' attributes:',\n ' label: Acceptance criteria',\n ' description: How anyone can tell this is done. Checks that fail today and pass afterwards.',\n ' value: |',\n ' - [ ] ',\n ' validations:',\n ' required: true',\n ].join('\\n');\n}\n\nfunction referencesField(): string {\n return [\n ' - type: textarea',\n ' id: references',\n ' attributes:',\n ' label: References',\n ' description: Links, related issues, prior discussion, evidence.',\n ].join('\\n');\n}\n\n/**\n * One Issue Form per default type.\n *\n * `type:` is emitted so that an organization with Issue Types gets the native\n * field filled in; GitHub ignores the key when the type does not exist, so the\n * same file works either way.\n *\n * Required fields are rationed on purpose. `Idea` asks for exactly one, because\n * the cost of recording a thought has to stay near zero — a capture form with\n * eight mandatory fields is a form nobody uses, and the ideas then live in\n * someone's head instead.\n */\nexport function renderIssueForm(type: DefaultIssueType): string {\n const header = [\n `name: \"${emojiFor(type.slug)} ${type.name}\"`,\n `description: \"${type.summary}\"`,\n `type: \"${type.name}\"`,\n 'body:',\n ];\n\n const bodies: Record<string, string[]> = {\n idea: [\n ' - type: markdown',\n ' attributes:',\n ' value: |',\n ' Quick capture. Only the first field is required — triage fills in the rest.',\n ' An Idea is **not approved work**: no agent implements it.',\n ' - type: textarea',\n ' id: idea',\n ' attributes:',\n ' label: The idea',\n ' description: What it is, in a few lines. It does not have to be solved or complete.',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: problem',\n ' attributes:',\n ' label: Problem or opportunity',\n ' description: What pain or gain is behind it? Leave blank if you do not know yet.',\n referencesField(),\n ' - type: textarea',\n ' id: questions',\n ' attributes:',\n ' label: Open questions',\n ' description: What would have to be answered before deciding anything.',\n ],\n research: [\n ' - type: textarea',\n ' id: question',\n ' attributes:',\n ' label: Question to answer',\n ' description: The decision this investigation has to unblock.',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: context',\n ' attributes:',\n ' label: Context',\n ' description: What is already known, and why the question is open.',\n ' - type: textarea',\n ' id: deliverable',\n ' attributes:',\n ' label: Expected deliverable',\n ' description: A conclusion and a recommendation. Say where durable knowledge will be written down.',\n ' validations:',\n ' required: true',\n referencesField(),\n ],\n epic: [\n ' - type: markdown',\n ' attributes:',\n ' value: |',\n ' An Epic is never executed directly: it is delivered through its sub-issues.',\n ' - type: textarea',\n ' id: objective',\n ' attributes:',\n ' label: Objective',\n ' description: The state of the product this Epic describes.',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: scope',\n ' attributes:',\n ' label: Scope',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: out-of-scope',\n ' attributes:',\n ' label: Out of scope',\n ' description: What this Epic deliberately does not cover. Absence here is what makes scope creep arguable.',\n ' - type: textarea',\n ' id: children',\n ' attributes:',\n ' label: Known sub-issues',\n ' description: Add them as sub-issues once they exist; list what you already foresee.',\n ],\n feature: [\n ' - type: textarea',\n ' id: problem',\n ' attributes:',\n ' label: Problem',\n ' description: What is not possible today, and for whom.',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: objective',\n ' attributes:',\n ' label: Objective',\n ' description: What becomes true when this is done.',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: scope',\n ' attributes:',\n ' label: Scope and out of scope',\n ' description: What is included, and what is deliberately not.',\n acceptanceCriteriaField(),\n ' - type: textarea',\n ' id: dependencies',\n ' attributes:',\n ' label: Dependencies and risks',\n ' description: What has to exist first, and what could go wrong.',\n referencesField(),\n ],\n bug: [\n ' - type: textarea',\n ' id: current',\n ' attributes:',\n ' label: Current behaviour',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: expected',\n ' attributes:',\n ' label: Expected behaviour',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: steps',\n ' attributes:',\n ' label: Steps to reproduce',\n ' value: |',\n ' 1.',\n ' 2.',\n ' 3.',\n ' validations:',\n ' required: true',\n ' - type: input',\n ' id: environment',\n ' attributes:',\n ' label: Environment',\n ' description: Where it happens — environment, version, component, browser.',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: evidence',\n ' attributes:',\n ' label: Evidence',\n ' description: Logs, request and response, screenshot, trace id, affected URL.',\n ' - type: dropdown',\n ' id: impact',\n ' attributes:',\n ' label: Impact',\n ' options:',\n ' - \"Data loss or improper exposure\"',\n ' - \"Feature unavailable, no workaround\"',\n ' - \"Feature degraded, workaround exists\"',\n ' - \"Cosmetic or low consequence\"',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: done',\n ' attributes:',\n ' label: How to tell it is fixed',\n ' description: The check that fails today and passes afterwards.',\n ' validations:',\n ' required: true',\n ],\n task: [\n ' - type: textarea',\n ' id: what',\n ' attributes:',\n ' label: What has to be done',\n ' validations:',\n ' required: true',\n ' - type: textarea',\n ' id: why',\n ' attributes:',\n ' label: Why',\n ' description: The reason this is worth doing now.',\n ' validations:',\n ' required: true',\n acceptanceCriteriaField(),\n referencesField(),\n ],\n };\n\n const body = bodies[type.slug];\n if (body === undefined) {\n throw new Error(`No Issue Form body defined for type \"${type.slug}\"`);\n }\n\n return `${[...header, ...body].join('\\n')}\\n`;\n}\n\nfunction emojiFor(slug: string): string {\n const map: Record<string, string> = {\n idea: '💡',\n research: '🔬',\n epic: '🗺️',\n feature: '✨',\n bug: '🐛',\n task: '🔧',\n };\n return map[slug] ?? '📌';\n}\n\n/**\n * The template chooser configuration.\n *\n * `blank_issues_enabled: true` is deliberate: a contributor who does not fit any\n * form should open the issue anyway. A closed chooser turns a report into\n * silence, which costs more than an unstructured issue.\n */\nexport function renderIssueTemplateConfig(): string {\n return [\n 'blank_issues_enabled: true',\n 'contact_links:',\n ' - name: How this backlog works',\n ' url: https://github.com/fabioassuncao/issue-flow/blob/main/docs/conventions.md',\n ' about: Issue types, what each one authorizes, labels and the lifecycle.',\n '',\n ].join('\\n');\n}\n\n/** The Pull Request template. */\nexport function renderPullRequestTemplate(): string {\n return [\n '## What changed',\n '',\n '<!-- What this Pull Request does, and why. One paragraph is enough. -->',\n '',\n '## How it was tested',\n '',\n '<!-- The checks you ran, and what they proved. \"CI is green\" is not a test plan. -->',\n '',\n '## Related issues',\n '',\n '<!--',\n 'One `Closes #N` per issue this resolves, each on its own line and as plain body',\n 'text — GitHub only auto-closes when the line is not inside a code fence.',\n '-->',\n '',\n '## Notes for reviewers',\n '',\n '<!-- Where to start, and anything you are unsure about. Write \"N/A\" rather than deleting a section. -->',\n '',\n ].join('\\n');\n}\n\n/** `AGENTS.md`, generated as an index and nothing else. */\nexport function renderAgentsMd(projectName: string, referenced: string[]): string {\n const lines = [\n `# ${projectName}`,\n '',\n 'This file is an **index**. It holds no rule, command or convention of its own —',\n 'those live in the documents referenced below, which are the source of truth.',\n '',\n '> Document once. Reference everywhere it is needed.',\n '',\n '## Start here',\n '',\n ];\n\n for (const path of referenced) {\n lines.push(`- [\\`${path}\\`](${path})`);\n }\n if (referenced.length === 0) {\n lines.push('- [`README.md`](README.md) — what this project is, and how to run it');\n }\n\n lines.push(\n '',\n '## Working on an issue',\n '',\n '- [`docs/conventions.md`](docs/conventions.md) — issue types, labels, branches,',\n ' commits and Pull Requests: what this repository expects and what it does not',\n '',\n '## What does not belong in this file',\n '',\n 'Anything that can live in a document of its own: build and test commands, code',\n 'style, architecture rules, testing strategy, operational procedures. If it is a',\n 'rule, a standard or reusable knowledge, it belongs in its own document and this',\n 'file only points at it.',\n '',\n 'An instruction that today exists **only** here does not stay here: move it to the',\n 'right document and leave a reference behind. Duplicated instructions in an agent',\n 'file age out of sight and start contradicting the source without anyone noticing.',\n '',\n );\n\n return lines.join('\\n');\n}\n\n/**\n * `CLAUDE.md`, which is one line by design.\n *\n * Claude Code reads `CLAUDE.md` as its memory file, and the temptation is to\n * put the instructions there too. That produces two copies of the same rules\n * which diverge the first time only one of them is edited — so this file is a\n * bridge, never a second source.\n */\nexport function renderClaudeMd(): string {\n return 'Read and follow the instructions in AGENTS.md.\\n';\n}\n\n/** The conventions document: the source of truth this scaffolding creates. */\nexport function renderConventionsDoc(hasIssueTypes: boolean): string {\n const typeRows = DEFAULT_ISSUE_TYPES.map(\n (t) =>\n `| **${t.name}** | ${t.summary} | ${t.executable ? 'Yes, once it is ready' : '**No**'} |`,\n ).join('\\n');\n\n const nonTypeRows = NON_TYPES.map((n) => `| ${n.concept} | ${n.instead} | ${n.why} |`).join('\\n');\n\n const labelRows = DEFAULT_LABELS.map((l) => `| \\`${l.name}\\` | ${l.description} |`).join('\\n');\n\n const typeMechanism = hasIssueTypes\n ? 'This organization has GitHub Issue Types, so the type lives in the **native field**.'\n : [\n 'This organization has no GitHub Issue Types, so the type is carried by a',\n '`type:*` label. If Issue Types are enabled later, move to them and drop these',\n 'labels — keeping both would create a second truth that drifts.',\n ].join('\\n');\n\n return `# Conventions\n\nHow work is recorded, classified and executed in this repository.\n\n## Principles\n\n1. **An open issue is not approved work.** Recording is cheap; executing requires\n explicit authorization.\n2. **Native structure before textual convention.** The order of preference is\n native feature > structured field > label > free text. Nothing GitHub already\n models is re-implemented as a title prefix or a label.\n3. **Each piece of information in one place.** If something has a field, it does\n not also have a label.\n4. **Capturing an idea is not bureaucratic.** The Idea form has one required\n field. The cost of recording a thought has to stay near zero.\n\n## Issue types\n\n${typeMechanism}\n\n| Type | What it is | Authorizes execution? |\n|---|---|---|\n${typeRows}\n\n### Choosing the type\n\nIn order — the first \"yes\" decides:\n\n1. **Is something broken?** → \\`Bug\\`, even if the expected behaviour never worked.\n2. **Is the question still unanswered?** → \\`Research\\`.\n3. **Is it just a record, with no analysis yet?** → \\`Idea\\`.\n4. **Is it large and delivered in parts?** → \\`Epic\\`, with sub-issues.\n5. **Does it change what the product does?** → \\`Feature\\`.\n6. **None of the above** → \\`Task\\`.\n\n### What is deliberately not a type\n\nA type per flavour of work fragments the backlog without improving a single\nquery.\n\n| Concept | Represent it as | Why |\n|---|---|---|\n${nonTypeRows}\n\n## Labels\n\nLabels are the last resort, for what has no native representation: technical\narea, component and cross-cutting characteristic.\n\n| Label | Meaning |\n|---|---|\n${labelRows}\n\n**Never use a label for** priority, type, state or size when a field exists for\nit: the label becomes a second truth that ages on its own.\n\n## Branches and commits\n\n- Branch: \\`${DEFAULT_BRANCH_CONVENTION}\\`\n- Commit: ${DEFAULT_COMMIT_CONVENTION}\n\nThe commit type must match the nature of the change. A bug fix committed as\n\\`feat:\\` corrupts the changelog and any version bump derived from the history.\n\n## Pull Requests\n\nFollow \\`.github/PULL_REQUEST_TEMPLATE.md\\`. Keep every section it defines and\nanswer the ones that do not apply with one line saying why — a deleted section\nreads as an unanswered one to automated review.\n\nLink the issues with one \\`Closes #N\\` per issue, as plain body text.\n\n## Agent entry points\n\n\\`AGENTS.md\\` is the canonical entry point for any coding agent, of any vendor.\nIt is an index: it says which documents to read, and holds no rule of its own.\n\n\\`CLAUDE.md\\` exists only as the Claude Code integration and contains a single\nline pointing at \\`AGENTS.md\\`. Any other agent adapter follows the same rule.\n\n\\`\\`\\`text\nCLAUDE.md → AGENTS.md → specialized documentation → single source of truth\n\\`\\`\\`\n`;\n}\n\n/** The labels file, consumed by the label sync step and readable by a human. */\nexport function renderLabelsFile(includeTypeLabels: boolean): string {\n const labels = includeTypeLabels ? [...FALLBACK_TYPE_LABELS, ...DEFAULT_LABELS] : DEFAULT_LABELS;\n\n return `${JSON.stringify(\n labels.map((label) => ({\n name: label.name,\n description: label.description,\n color: label.color,\n })),\n null,\n 2,\n )}\\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAQ,OAAO,iBAAiB;AACzC,SAAS,UAAU,SAAS,QAAAA,aAAY;;;ACDxC,SAAS,gBAAgB;AACzB,SAAS,YAAY;;;ACuDd,IAAM,sBAAmD;AAAA,EAC9D;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,OAAO;AAAA,IACP,SAAS;AAAA,IACT,YAAY;AAAA,IACZ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,CAAC,YAAoB,OAAOA,MAAK,MAAM,OAAO,CAAC;AAAA,EACzD;AACF;AAGA,eAAsB,uBACpB,UAA+B,CAAC,GACT;AACvB,SAAO,kBAAkB,MAAM,uBAAuB,OAAO,CAAC;AAChE;","names":["join","join"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/plan.ts","../src/storage/user-story-numbering.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport {\n branchName,\n DEFAULT_BRANCH_CONVENTION,\n resolveChangeType,\n} from '../conventions/git/index.js';\nimport { DEFAULT_HEADLESS_TIMEOUT_MS, runHeadless } from '../core/headless.js';\nimport { readFileWithGrace, runPhaseWithRetry } from '../core/phase-runner.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { ResolvedIssue } from '../issues/types.js';\nimport { loadRepositoryPolicy } from '../policy/index.js';\nimport { resolvePolicyPlaceholders } from '../policy/placeholders.js';\nimport { taskPlanSchema } from '../schemas.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport {\n determineUserStoryNumbering,\n formatUserStoryId,\n parseUserStoryNumber,\n} from '../storage/user-story-numbering.js';\nimport { printError, printInfo, printSuccess, printWarning } from '../ui/logger.js';\nimport { isTransientFailure } from '../utils/retry.js';\n\n/** `--continue` / `--start-us <n>` override of the numbering cascade (issue #36). */\nexport interface PlanUserStoryNumberingOptions {\n continueFlag?: boolean;\n startUs?: number;\n /** Current checkout in --no-branch mode; prevents the plan from inventing a branch. */\n branchName?: string;\n}\n\nexport async function runPlan(\n issue: string,\n resolvedIssue?: ResolvedIssue,\n numbering?: PlanUserStoryNumberingOptions,\n): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n // Read the PRD\n const prdPath = paths.prdFile;\n let prdContent: string;\n try {\n prdContent = await readFile(prdPath, 'utf-8');\n } catch {\n printError(`PRD not found at ${prdPath}. Run 'issue-flow prd ${issueNumber}' first.`);\n return 1;\n }\n\n const tasksPath = paths.tasksFile;\n\n // Resolve the User Story numbering continuity (issue #36), log where the\n // decision came from — never silently — and persist it into the project's\n // metadata.json for audit before the prompt is even built, so the record on\n // disk always matches what the prompt was told.\n const {\n message: numberingMessage,\n nextUserStoryId,\n decision: { nextNumber },\n } = await determineUserStoryNumbering({\n issueNumber,\n continueFlag: numbering?.continueFlag,\n startUs: numbering?.startUs,\n });\n printInfo(numberingMessage);\n\n let persistedBranch: string | null = null;\n try {\n persistedBranch = (await loadTaskPlan(tasksPath)).branchName ?? null;\n } catch {\n persistedBranch = null;\n }\n\n const policy = await loadRepositoryPolicy();\n const change = resolveChangeType({\n labels: resolution.resolved.issue.labels,\n title: resolution.resolved.issue.title,\n titleConvention: policy.issues.titleConvention,\n typeMap: policy.git.typeMap,\n });\n const numericIssue = /^\\d+$/.test(issueNumber) ? Number(issueNumber) : null;\n const computedBranch = branchName({\n type: change.type,\n issueNumber: numericIssue,\n title: resolution.resolved.issue.title,\n convention: policy.git.branchConvention ?? DEFAULT_BRANCH_CONVENTION,\n });\n const resolvedBranch =\n persistedBranch !== null && persistedBranch !== ''\n ? persistedBranch\n : (numbering?.branchName ?? computedBranch);\n printInfo(\n `Branch: ${resolvedBranch} (type ${change.type} from ${change.source}${\n persistedBranch !== null && persistedBranch !== '' ? ', persisted' : ''\n })`,\n );\n\n const template = await loadPrompt('plan');\n const prompt = applyPlaceholders(template, {\n // The repository's own conventions. Empty when it declares none, which is\n // what keeps the rendered prompt identical to the pre-policy one.\n ...(await resolvePolicyPlaceholders()),\n __ISSUE_NUMBER__: issueNumber,\n __PRD_CONTENT__: prdContent,\n __TASKS_PATH__: tasksPath,\n __NEXT_US_NUMBER__: nextUserStoryId,\n __BRANCH_NAME__: resolvedBranch,\n ...issuePlaceholders(resolution.resolved),\n });\n\n await mkdir(paths.issueDir, { recursive: true });\n\n const outcome = await runPhaseWithRetry({\n phase: 'plan',\n attempt: async () => {\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 25,\n timeout: getGlobalTimeout() ?? DEFAULT_HEADLESS_TIMEOUT_MS,\n timeoutHistory: {\n phase: 'plan',\n journalFiles: [paths.rotatedEventsFile, paths.eventsFile],\n },\n // json (not text) so the CLI reports usage: the envelope's `result`\n // field carries the same assistant text this phase already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep', 'Write'],\n addDirs: [paths.issueDir],\n statusMessage: `Converting PRD to task plan for issue #${issueNumber}...`,\n phase: 'plan',\n permission: 'workspace',\n });\n // One event per attempt; the reducer sums them into the phase total.\n publishPhaseMetrics('plan', result.cost, startedAtMs, result.agent?.provider);\n\n if (!result.success) {\n return {\n ok: false,\n transient: result.retryExhausted !== true && isTransientFailure(1, result.error ?? ''),\n error: `Task plan generation failed: ${result.error}`,\n };\n }\n\n // Verify the file was created, tolerating a brief FS-visibility lag.\n let rawContent: string;\n try {\n rawContent = await readFileWithGrace(tasksPath);\n } catch {\n return { ok: false, transient: true, error: `tasks.json was not created at ${tasksPath}` };\n }\n\n // Validate JSON structure — a content defect, not a timing issue, but\n // still worth a bounded retry since it's a fresh Claude invocation.\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawContent);\n } catch {\n return { ok: false, transient: true, error: 'tasks.json contains invalid JSON' };\n }\n\n // Validate with zod schema\n const validation = taskPlanSchema.safeParse(parsed);\n if (!validation.success) {\n const issues = validation.error.issues\n .map((i) => ` - ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n return {\n ok: false,\n transient: true,\n error: `tasks.json does not match expected schema:\\n${issues}`,\n };\n }\n\n return { ok: true };\n },\n });\n\n if (!outcome.ok) {\n printError(outcome.error ?? `Task plan generation failed for issue #${issueNumber}`);\n return 1;\n }\n\n // Ensure pipeline state reflects completion of this phase.\n // The branch is a CLI calculation: a persisted name is never recalculated,\n // and a fresh plan is overwritten if the agent drifted from __BRANCH_NAME__.\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.jsonCompleted = true;\n plan.branchName =\n persistedBranch !== null && persistedBranch !== ''\n ? persistedBranch\n : (numbering?.branchName ?? computedBranch);\n await saveTaskPlan(tasksPath, plan);\n\n // The numbering is a prompt instruction, not a programmatic rewrite, so the\n // generated plan can still ignore it. Say so out loud instead of leaving the\n // log and metadata.json claiming a numbering the file on disk contradicts.\n const generatedLowest = plan.userStories\n .map((story) => parseUserStoryNumber(story.id))\n .filter((value): value is number => value !== null)\n .reduce<number | null>(\n (lowest, value) => (lowest === null ? value : Math.min(lowest, value)),\n null,\n );\n if (generatedLowest !== null && generatedLowest < nextNumber) {\n printWarning(\n `The generated plan starts at ${formatUserStoryId(generatedLowest)}, not the requested ` +\n `${nextUserStoryId}. User Story ids may collide with earlier issues of this project — ` +\n `re-run 'issue-flow plan ${issueNumber} --start-us ${nextNumber}' if that matters.`,\n );\n }\n\n printSuccess(`Task plan saved to ${tasksPath} (${plan.userStories.length} stories)`);\n return 0;\n}\n","import { readdir, readFile } from 'node:fs/promises';\nimport { isoNow } from '../core/state-manager.js';\nimport { getProjectRoot } from '../utils/git.js';\nimport { recordUserStoryNumbering } from './compat.js';\nimport { getIssuePaths } from './paths.js';\nimport { type ResolveIssuePathsOptions, resolveProjectPaths } from './resolve.js';\nimport type { UserStoryNumberingDecision } from './schemas.js';\n\n/**\n * Continuity of `US-NNN` numbering across `plan` executions of the same\n * project (issue #36).\n *\n * The User Story `id` field is free-form — `userStorySchema` in\n * `src/schemas.ts` only requires a non-empty string, no `US-NNN` regex is\n * enforced — so every reader here tolerates an id that does not carry a\n * trailing number instead of throwing on it.\n */\n\nconst USER_STORY_ID_PAD = 3;\n\n/** `16` -> `'US-016'`. Numbers past 999 are not padded further. */\nexport function formatUserStoryId(n: number): string {\n return `US-${String(n).padStart(USER_STORY_ID_PAD, '0')}`;\n}\n\n/**\n * Extract the last run of digits from a User Story id, or `null` when none is\n * found. Tolerant by design: an id like `US-001` yields `1`, but so does a\n * free-form one such as `story-1` or `v2-US-007` (the last digit run, `007`,\n * wins over the `2` version prefix) — only an id with no digits at all (e.g.\n * `add-auth`) is ignored.\n */\nexport function parseUserStoryNumber(id: string): number | null {\n const matches = id.match(/\\d+/g);\n if (!matches || matches.length === 0) return null;\n\n const value = Number.parseInt(matches[matches.length - 1], 10);\n return Number.isNaN(value) ? null : value;\n}\n\nexport interface HighestUserStoryNumberResult {\n number: number;\n /** Issue directory name the winning story came from. */\n issueId: string;\n /** Verbatim id of the winning story. */\n storyId: string;\n}\n\n/**\n * Loose read of one `tasks.json`: only cares about `userStories[].id` and\n * tolerates every failure (missing file, invalid JSON, unexpected shape) by\n * returning `null` — a sibling issue mid-migration, or with a corrupt plan,\n * must not abort the whole project scan.\n */\nasync function readUserStoryIds(tasksPath: string): Promise<string[] | null> {\n let raw: string;\n try {\n raw = await readFile(tasksPath, 'utf-8');\n } catch {\n return null;\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !Array.isArray((parsed as { userStories?: unknown }).userStories)\n ) {\n return null;\n }\n\n return (parsed as { userStories: unknown[] }).userStories\n .map((story) =>\n typeof story === 'object' &&\n story !== null &&\n typeof (story as { id?: unknown }).id === 'string'\n ? (story as { id: string }).id\n : null,\n )\n .filter((id): id is string => id !== null);\n } catch {\n return null;\n }\n}\n\nexport interface FindHighestUserStoryNumberOptions extends ResolveIssuePathsOptions {\n /**\n * Issue directory to leave out of the scan — the issue the numbering is\n * being resolved for. Re-planning an issue overwrites its own `tasks.json`,\n * so counting the plan about to be replaced would push the numbering forward\n * on every `plan` re-run of the same issue.\n */\n excludeIssueId?: string;\n}\n\n/**\n * Highest User Story number already used anywhere in the project, scanning\n * every `<issuesDir>/<id>/tasks.json` regardless of which issue produced it —\n * that project-wide scope is what makes `US-NNN` unambiguous across issues.\n * The issue named by `excludeIssueId` is skipped, so re-planning is idempotent.\n *\n * `null` means no readable `tasks.json` was found (the project's first `plan`\n * run ever, or a brand-new project directory). A storage directory that exists\n * but cannot be read throws instead: silently restarting at `US-001` because\n * `~/.issue-flow` was momentarily unreadable is the worst outcome this feature\n * can produce.\n */\nexport async function findHighestUserStoryNumber(\n options: FindHighestUserStoryNumberOptions = {},\n): Promise<HighestUserStoryNumberResult | null> {\n const { excludeIssueId, ...rootOptions } = options;\n const { projectId, issuesDir } = await resolveProjectPaths(rootOptions);\n\n let entries: string[];\n try {\n entries = (await readdir(issuesDir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n } catch (error) {\n // ENOENT is the legitimate \"no history yet\" case. Any other failure\n // (EACCES, EIO, an unavailable mount) must not be reported as an empty\n // history, or the numbering would restart silently.\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return null;\n throw new Error(\n `Could not scan the project's User Story history at ${issuesDir}: ` +\n `${(error as Error).message}. Fix the storage directory, or pass --start-us <n> ` +\n 'to set the numbering explicitly.',\n { cause: error },\n );\n }\n\n let best: HighestUserStoryNumberResult | null = null;\n\n for (const issueId of entries) {\n if (excludeIssueId !== undefined && issueId === excludeIssueId) continue;\n // Never hand-build an artifact path (see src/storage/AGENTS.md): asking\n // getIssuePaths() keeps a rename of `tasks.json` a one-file change instead\n // of silently making this scan find nothing.\n const { tasksFile } = getIssuePaths(projectId, issueId, { env: options.env });\n const ids = await readUserStoryIds(tasksFile);\n if (!ids) continue;\n\n for (const id of ids) {\n const value = parseUserStoryNumber(id);\n if (value === null) continue;\n if (best === null || value > best.number) {\n best = { number: value, issueId, storyId: id };\n }\n }\n }\n\n return best;\n}\n\nexport interface ResolveUserStoryNumberingOptions extends ResolveIssuePathsOptions {\n /** Issue the decision is being made for — carried into the audit record. */\n issueNumber: string;\n /** `--continue` was passed explicitly. Purely cosmetic on the log message:\n * the resolved number is identical to the automatic default. */\n continueFlag?: boolean;\n /** `--start-us <n>` was passed. Wins outright over any history. */\n startUs?: number;\n /** Timestamp source, injectable for tests. */\n now?: () => string;\n}\n\nexport interface UserStoryNumberingOutcome {\n decision: UserStoryNumberingDecision;\n /** Ready-to-print explanation of where the decision came from — the CLI\n * must never resolve this silently (issue #36). */\n message: string;\n}\n\n/**\n * Resolve the numbering cascade of #36:\n *\n * 1. `--start-us <n>` wins outright — history is not even scanned, since the\n * whole point is to ignore it.\n * 2. Otherwise the project's history is scanned for the highest number used\n * so far. This is what running with no flag at all does automatically,\n * and what `--continue` names explicitly (the two produce the same\n * number; the flag only changes the log message).\n * 3. No history found (the project's first `plan` ever) starts at `US-001`.\n *\n * Pure with respect to `metadata.json` — this only reads `tasks.json` files,\n * never writes. Persisting the decision is {@link determineUserStoryNumbering}\n * below, via `recordUserStoryNumbering()` in `compat.ts`.\n */\nexport async function resolveUserStoryNumbering(\n options: ResolveUserStoryNumberingOptions,\n): Promise<UserStoryNumberingOutcome> {\n const { issueNumber, continueFlag, startUs, now, ...rootOptions } = options;\n const decidedAt = (now ?? isoNow)();\n\n if (startUs !== undefined) {\n const decision: UserStoryNumberingDecision = {\n nextNumber: startUs,\n source: 'start-us',\n issueNumber,\n decidedAt,\n };\n return {\n decision,\n message: `User Story numbering forced to ${formatUserStoryId(startUs)} via --start-us.`,\n };\n }\n\n // The issue being planned is excluded from the scan: `plan` overwrites its\n // own `tasks.json`, so counting the plan it is about to replace would push\n // the numbering forward on every re-run of `plan` for the same issue.\n const highest = await findHighestUserStoryNumber({ ...rootOptions, excludeIssueId: issueNumber });\n\n if (highest === null) {\n const decision: UserStoryNumberingDecision = {\n nextNumber: 1,\n source: 'none',\n issueNumber,\n decidedAt,\n };\n return {\n decision,\n message: `Starting User Story numbering at ${formatUserStoryId(1)} (no previous history found for this project).`,\n };\n }\n\n const nextNumber = highest.number + 1;\n const decision: UserStoryNumberingDecision = {\n nextNumber,\n source: 'history',\n issueNumber,\n decidedAt,\n detail: `${highest.storyId} (issue #${highest.issueId})`,\n };\n const via = continueFlag ? ' via --continue' : '';\n return {\n decision,\n message:\n `Continuing User Story numbering from ${formatUserStoryId(nextNumber)}${via} ` +\n `— last used was ${highest.storyId} (issue #${highest.issueId}).`,\n };\n}\n\nexport interface DetermineUserStoryNumberingOptions extends ResolveUserStoryNumberingOptions {\n /** Repository root. Defaults to the git toplevel of the current directory. */\n projectRoot?: string;\n}\n\nexport interface UserStoryNumberingResult extends UserStoryNumberingOutcome {\n /** `decision.nextNumber` formatted as `US-NNN`, ready for the prompt. */\n nextUserStoryId: string;\n}\n\n/**\n * The entry point commands use: resolve the cascade and persist the decision\n * into `metadata.json` in one call, so no call site can log/prompt with one\n * decision and audit a different one.\n */\nexport async function determineUserStoryNumbering(\n options: DetermineUserStoryNumberingOptions,\n): Promise<UserStoryNumberingResult> {\n const { projectRoot: projectRootOption, ...rest } = options;\n const projectRoot = projectRootOption ?? (await getProjectRoot());\n\n const outcome = await resolveUserStoryNumbering({ ...rest, projectRoot });\n await recordUserStoryNumbering(projectRoot, outcome.decision, {\n env: options.env,\n now: options.now,\n });\n\n return { ...outcome, nextUserStoryId: formatUserStoryId(outcome.decision.nextNumber) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,YAAAA,iBAAgB;;;ACAhC,SAAS,SAAS,gBAAgB;AAkBlC,IAAM,oBAAoB;AAGnB,SAAS,kBAAkB,GAAmB;AACnD,SAAO,MAAM,OAAO,CAAC,EAAE,SAAS,mBAAmB,GAAG,CAAC;AACzD;AASO,SAAS,qBAAqB,IAA2B;AAC9D,QAAM,UAAU,GAAG,MAAM,MAAM;AAC/B,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG,QAAO;AAE7C,QAAM,QA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aACH,oBAAoB,QAAQ,oBAAoB,KAC5C,kBACC,WAAW,cAAc;AAChC,QAAM,aAAa,WAAW,IAAI;AAKlC,QAAM,kBAAkB,KAAK,YAC1B,IAAI,CAAC,UAAU,qBAAqB,MAAM,EAAE,CAAC,EAC7C,OAAO,CAAC,UAA2B,UAAU,IAAI,EACjD;AAAA,IACC,CAAC,QAAQ,UAAW,WAAW,OAAO,QAAQ,KAAK,IAAI,QAAQ,KAAK;AAAA,IACpE;AAAA,EACF;AACF,MAAI,oBAAoB,QAAQ,kBAAkB,YAAY;AAC5D;AAAA,MACE,gCAAgC,kBAAkB,eAAe,CAAC,uBAC7D,eAAe,mGACS,WAAW,eAAe,UAAU;AAAA,IACnE;AAAA,EACF;AAEA,eAAa,sBAAsB,SAAS,KAAK,KAAK,YAAY,MAAM,WAAW;AACnF,SAAO;AACT;","names":["readFile","decision","readFile"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/agent.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { probeReadinessInventory } from '../agents/availability.js';\nimport { describeRunAgents } from '../agents/resolve.js';\nimport {\n AGENT_PHASES,\n AGENT_SCHEMA_VERSION,\n type AgentPhase,\n type AgentProviderId,\n isAgentPhase,\n isAgentProviderId,\n} from '../agents/types.js';\nimport { GLOBAL_CONFIG_FILENAME, loadAgentConfig, PROJECT_CONFIG_FILENAME } from '../config.js';\nimport { getGlobalRoot } from '../storage/paths.js';\nimport { printError, printSuccess } from '../ui/logger.js';\nimport { writeFileAtomic } from '../utils/fs.js';\nimport { getProjectRoot } from '../utils/git.js';\n\nexport const AGENT_COMMAND_SCHEMA_VERSION = AGENT_SCHEMA_VERSION;\n\nexport interface AgentCommandOptions {\n json?: boolean;\n}\n\nexport interface AgentUseOptions {\n model?: string;\n global?: boolean;\n project?: boolean;\n phase?: string;\n}\n\nfunction originLabel(origin: string): string {\n switch (origin) {\n case 'default':\n return 'default';\n case 'global':\n return '~/.issue-flow/config.json';\n case 'project':\n return '.issue-flow.json';\n case 'env':\n return 'ISSUE_FLOW_*';\n case 'cli':\n return 'CLI';\n default:\n return origin;\n }\n}\n\nfunction formatPhaseLine(\n phase: AgentPhase,\n provider: string,\n model: string | null,\n origin: string,\n inherited: boolean,\n): string {\n const modelBit = model ? ` · ${model}` : '';\n const source = inherited ? 'herdado do padrão' : originLabel(origin);\n return `${` ${phase.padEnd(12)} ${provider}${modelBit}`.padEnd(40)}(${source})`;\n}\n\nexport async function runAgent(options: AgentCommandOptions = {}): Promise<number> {\n const config = await loadAgentConfig();\n const summary = await describeRunAgents();\n const inventory = await probeReadinessInventory();\n const providers = Object.values(inventory.providers);\n\n if (options.json === true) {\n const phases: Record<string, unknown> = {};\n for (const phase of AGENT_PHASES) {\n const resolved = summary.byPhase[phase];\n const inherited = config.phases[phase] === undefined;\n phases[phase] = {\n provider: resolved.provider,\n model: resolved.model,\n origin: resolved.origin,\n inherited,\n };\n }\n console.log(\n JSON.stringify(\n {\n schemaVersion: AGENT_COMMAND_SCHEMA_VERSION,\n default: {\n provider: summary.defaultProvider,\n model: summary.defaultModel,\n origin: summary.defaultOrigin,\n },\n phases,\n inventory,\n availability: providers.map((entry) => ({\n id: entry.provider,\n harness: entry.harness,\n installed: entry.installed,\n version: entry.version,\n authenticated: entry.authentication !== 'failed' && entry.installed,\n authentication: entry.authentication,\n state: entry.state,\n source: entry.source,\n observedAt: entry.observedAt,\n expiresAt: entry.expiresAt,\n detail: entry.detail,\n ...(entry.provider === 'antigravity' || entry.provider === 'claude'\n ? { authProbe: 'none' as const }\n : {}),\n })),\n },\n null,\n 2,\n ),\n );\n return 0;\n }\n\n const modelLabel = summary.defaultModel ?? '(default do provider)';\n console.log(\n `Agente padrão ${summary.defaultProvider.padEnd(22)} (${originLabel(summary.defaultOrigin.provider)})`,\n );\n console.log(`Modelo ${modelLabel} (${originLabel(summary.defaultOrigin.model)})`);\n console.log('');\n console.log('Por fase');\n for (const phase of AGENT_PHASES) {\n const resolved = summary.byPhase[phase];\n const inherited = config.phases[phase] === undefined;\n console.log(\n formatPhaseLine(\n phase,\n resolved.provider,\n resolved.model,\n resolved.origin.provider,\n inherited,\n ),\n );\n }\n console.log('');\n console.log('Disponibilidade');\n for (const entry of providers) {\n const authNote = entry.authentication === 'unverified' ? ' (auth unverified)' : '';\n console.log(\n ` ${entry.provider.padEnd(12)} ${(entry.version ?? '—').padEnd(16)} ${entry.state.padEnd(12)} ${entry.detail}${authNote}`,\n );\n }\n if (inventory.providers.antigravity?.installed) {\n console.log(\n ' Warning: every Antigravity invocation passes --dangerously-skip-permissions. --mode plan is the write containment.',\n );\n }\n return 0;\n}\n\nexport async function runAgentUse(\n providerRaw: string,\n options: AgentUseOptions = {},\n): Promise<number> {\n if (!isAgentProviderId(providerRaw)) {\n printError(\n `Unknown agent provider '${providerRaw}'. Valid providers: claude, codex, cursor, antigravity.`,\n );\n return 1;\n }\n const provider = providerRaw as AgentProviderId;\n\n let phase: AgentPhase | undefined;\n if (options.phase !== undefined) {\n if (!isAgentPhase(options.phase)) {\n printError(\n `Unknown agent phase '${options.phase}'. Valid phases: ${AGENT_PHASES.join(', ')}.`,\n );\n return 1;\n }\n phase = options.phase;\n }\n\n const target: 'global' | 'project' = options.project === true ? 'project' : 'global';\n try {\n const path = await writeAgentPreference({\n target,\n provider,\n model: options.model,\n phase,\n });\n printSuccess(`Wrote agent preference to ${path}`);\n return 0;\n } catch (err) {\n printError(err instanceof Error ? err.message : String(err));\n return 1;\n }\n}\n\nexport async function writeAgentPreference(input: {\n target: 'global' | 'project';\n provider: AgentProviderId;\n model?: string;\n phase?: AgentPhase;\n projectRoot?: string;\n}): Promise<string> {\n const path =\n input.target === 'global'\n ? join(getGlobalRoot(), GLOBAL_CONFIG_FILENAME)\n : join(input.projectRoot ?? (await getProjectRoot()), PROJECT_CONFIG_FILENAME);\n\n let existing: Record<string, unknown> = {};\n try {\n const raw = await readFile(path, 'utf-8');\n const parsed: unknown = JSON.parse(raw);\n if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n existing = parsed as Record<string, unknown>;\n }\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw new Error(`Could not read ${path}: ${(err as Error).message}`);\n }\n }\n\n const currentAgent =\n existing.agent !== null && typeof existing.agent === 'object' && !Array.isArray(existing.agent)\n ? { ...(existing.agent as Record<string, unknown>) }\n : {};\n\n if (input.phase) {\n const phases =\n currentAgent.phases !== null &&\n typeof currentAgent.phases === 'object' &&\n !Array.isArray(currentAgent.phases)\n ? { ...(currentAgent.phases as Record<string, unknown>) }\n : {};\n phases[input.phase] = {\n provider: input.provider,\n ...(input.model ? { model: input.model } : {}),\n };\n currentAgent.phases = phases;\n } else {\n currentAgent.provider = input.provider;\n if (input.model) currentAgent.model = input.model;\n else delete currentAgent.model;\n }\n\n existing.agent = currentAgent;\n await mkdir(dirname(path), { recursive: true });\n await writeFileAtomic(path, `${JSON.stringify(existing, null, 2)}\\n`);\n if (input.provider === 'cursor') {\n const { ensureCursorStorageGrant } = await import('../agents/permissions.js');\n await ensureCursorStorageGrant({\n mode: input.target === 'project' ? 'project' : 'global',\n ...(input.projectRoot === undefined ? {} : { projectRoot: input.projectRoot }),\n });\n }\n return path;\n}\n\n/** Used by init to persist a first-run choice without touching other keys. */\nexport async function persistFirstAgentChoice(provider: AgentProviderId): Promise<string> {\n return writeAgentPreference({ target: 'global', provider });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,gBAAgB;AAChC,SAAS,SAAS,YAAY;AAiBvB,IAAM,+BAA+B;AAa5C,SAAS,YAAY,QAAwB;AAC3C,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,I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AkC,IACjD,CAAC;AAEP,MAAI,MAAM,OAAO;AACf,UAAM,SACJ,aAAa,WAAW,QACxB,OAAO,aAAa,WAAW,YAC/B,CAAC,MAAM,QAAQ,aAAa,MAAM,IAC9B,EAAE,GAAI,aAAa,OAAmC,IACtD,CAAC;AACP,WAAO,MAAM,KAAK,IAAI;AAAA,MACpB,UAAU,MAAM;AAAA,MAChB,GAAI,MAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;AAAA,IAC9C;AACA,iBAAa,SAAS;AAAA,EACxB,OAAO;AACL,iBAAa,WAAW,MAAM;AAC9B,QAAI,MAAM,MAAO,cAAa,QAAQ,MAAM;AAAA,QACvC,QAAO,aAAa;AAAA,EAC3B;AAEA,WAAS,QAAQ;AACjB,QAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC9C,QAAM,gBAAgB,MAAM,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,CAAC;AAAA,CAAI;AACpE,MAAI,MAAM,aAAa,UAAU;AAC/B,UAAM,EAAE,yBAAyB,IAAI,MAAM,OAAO,2BAA0B;AAC5E,UAAM,yBAAyB;AAAA,MAC7B,MAAM,MAAM,WAAW,YAAY,YAAY;AAAA,MAC/C,GAAI,MAAM,gBAAgB,SAAY,CAAC,IAAI,EAAE,aAAa,MAAM,YAAY;AAAA,IAC9E,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAGA,eAAsB,wBAAwB,UAA4C;AACxF,SAAO,qBAAqB,EAAE,QAAQ,UAAU,SAAS,CAAC;AAC5D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/issues/registry.ts","../src/issues/hash.ts","../src/issues/providers/github.ts","../src/issues/providers/local.ts","../src/issues/bootstrap.ts","../src/issues/resolver.ts"],"sourcesContent":["import type { IssueProvider } from './provider.js';\nimport type { IssueSource } from './types.js';\n\n/**\n * Registry of Issue providers.\n *\n * Adding an origin is creating a provider file and registering one line here\n * (or from the caller's side), so nothing in src/commands/ needs to know the\n * list of sources.\n */\nconst providers = new Map<IssueSource, IssueProvider>();\n\n/**\n * Register a provider under its own `name`.\n *\n * Registering the same source twice replaces the previous entry, which is what\n * lets tests substitute a real provider with a fake one.\n */\nexport function registerProvider(provider: IssueProvider): void {\n providers.set(provider.name, provider);\n}\n\n/** Sources currently registered, in registration order. */\nexport function getRegisteredSources(): IssueSource[] {\n return [...providers.keys()];\n}\n\n/**\n * Look up a provider by origin.\n *\n * @throws when the origin is not registered, listing what is available so the\n * caller knows which sources they can pick instead.\n */\nexport function getProvider(source: IssueSource): IssueProvider {\n const provider = providers.get(source);\n if (provider === undefined) {\n const available = getRegisteredSources();\n const hint =\n available.length > 0\n ? `Available sources: ${available.join(', ')}.`\n : 'No Issue providers are registered.';\n throw new Error(`Unknown Issue source: '${source}'. ${hint}`);\n }\n return provider;\n}\n\n/** Drop every registration. Intended for test isolation. */\nexport function clearProviders(): void {\n providers.clear();\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Content hashing shared by every Issue provider.\n *\n * The hash is what lets the resolver tell \"the local and the remote Issue are\n * the same demand\" from \"they diverged\", so it has to be stable across\n * platforms: Windows checkouts store CRLF, editors add or drop trailing\n * newlines, and neither should count as a content change.\n */\n\n/** Normalizes line endings (CRLF/CR to LF) and trims the edges. */\nfunction normalizeText(value: string): string {\n return value.replace(/\\r\\n?/g, '\\n').trim();\n}\n\n/**\n * Returns `sha256:<hex>` for the given title and body.\n *\n * The payload is a canonical JSON object rather than a concatenation, so text\n * moved from the title into the body always changes the hash.\n */\nexport function hashIssueContent(title: string, body: string): string {\n const payload = JSON.stringify({\n title: normalizeText(title),\n body: normalizeText(body),\n });\n const digest = createHash('sha256').update(payload, 'utf8').digest('hex');\n return `sha256:${digest}`;\n}\n","import { getActiveResilienceConfig } from '../../config.js';\nimport type { ClassifiedFailure } from '../../resilience/errors.js';\nimport { ClassifiedError, requiresHumanAction } from '../../resilience/errors.js';\nimport { type PolicyConfig, resolvePolicy } from '../../resilience/policy.js';\nimport type { RetryPolicyFor } from '../../resilience/retry.js';\nimport { type ExecResult, run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider, ProviderAvailability } from '../provider.js';\nimport { emptyRelations, mergeRelations, parseTextualRelations, uniqueIds } from '../relations.js';\nimport type { Issue, IssueDraft, IssueRelations, IssueState } from '../types.js';\n\n/** Fields requested from `gh issue view`, in the order the PRD specifies. */\nconst VIEW_FIELDS = 'number,title,body,labels,state,url,createdAt,updatedAt,issueType';\n\n/** Timeout for the availability probes, matching the `init` prerequisite checks. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * Every `gh` invocation carries the resilience policy of the failure it hits:\n * the `network` budget for a DNS blip, the `rate_limit` budget (and the\n * server's `Retry-After`) for a rate limit, and — because `resolvePolicy()`\n * clamps them — **no** attempt at all for an authentication or configuration\n * failure. This is the one place `gh` failures stop being fatal on sight.\n */\nfunction ghPolicy(): RetryPolicyFor {\n return (failure: ClassifiedFailure) =>\n resolvePolicy(failure.kind, getActiveResilienceConfig() as PolicyConfig);\n}\n\n/**\n * The budget of the availability probes, capped well below the full one.\n *\n * A probe answers a question about liveness; the answer must not take minutes.\n * The real read (`get`, `create`, `close`) keeps the full policy, so a blip\n * during the work is still absorbed at its documented budget — what is capped\n * here is only how long an *unreachable* GitHub delays a `local` Issue that\n * would have resolved instantly.\n */\nconst PROBE_MAX_ATTEMPTS = 3;\nconst PROBE_MAX_DELAY_MS = 5_000;\n\nfunction ghProbePolicy(): RetryPolicyFor {\n const policyFor = ghPolicy();\n return (failure) => {\n const policy = policyFor(failure);\n return {\n ...policy,\n maxAttempts: Math.min(policy.maxAttempts, PROBE_MAX_ATTEMPTS),\n maxDelayMs: Math.min(policy.maxDelayMs, PROBE_MAX_DELAY_MS),\n retryForever: false,\n };\n };\n}\n\n/** `gh <args>` under the full resilience policy. */\nfunction gh(args: string[], options: { timeout?: number } = {}): Promise<ExecResult> {\n return run('gh', args, {\n retry: ghPolicy(),\n ...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n });\n}\n\n/**\n * gh reports a missing Issue on stderr with one of these phrasings. The match\n * must stay issue-specific: a bare /not found/ would also swallow\n * `gh: command not found`, turning a broken environment into \"issue absent\".\n * Anything else on a non-zero exit is a real failure (network, auth, gh not\n * installed) and must surface as a thrown error.\n */\nconst NOT_FOUND_PATTERN =\n /could not resolve to an issue|no issues? found|issue not found|could not find any issue/i;\n\ninterface GhLabel {\n name?: unknown;\n}\n\ninterface GhIssuePayload {\n number?: unknown;\n title?: unknown;\n body?: unknown;\n labels?: unknown;\n state?: unknown;\n url?: unknown;\n createdAt?: unknown;\n updatedAt?: unknown;\n issueType?: unknown;\n}\n\nfunction normalizeState(state: unknown): IssueState {\n return String(state ?? '').toUpperCase() === 'CLOSED' ? 'closed' : 'open';\n}\n\nfunction normalizeLabels(labels: unknown): string[] {\n if (!Array.isArray(labels)) return [];\n return labels\n .map((label: GhLabel | string) => (typeof label === 'string' ? label : label?.name))\n .filter((name): name is string => typeof name === 'string' && name.length > 0);\n}\n\nfunction normalizeIssueType(value: unknown): string | undefined {\n if (typeof value === 'string' && value.length > 0) return value;\n if (value !== null && typeof value === 'object' && 'name' in value) {\n const name = (value as { name: unknown }).name;\n return typeof name === 'string' && name.length > 0 ? name : undefined;\n }\n return undefined;\n}\n\nfunction toIssue(payload: GhIssuePayload): Issue {\n const title = typeof payload.title === 'string' ? payload.title : '';\n const body = typeof payload.body === 'string' ? payload.body : '';\n const number = typeof payload.number === 'number' ? payload.number : null;\n const url = typeof payload.url === 'string' && payload.url.length > 0 ? payload.url : null;\n const type = normalizeIssueType(payload.issueType);\n\n return {\n id: number === null ? '' : String(number),\n number,\n title,\n body,\n labels: normalizeLabels(payload.labels),\n ...(type === undefined ? {} : { type }),\n state: normalizeState(payload.state),\n source: 'github',\n remoteRef: url,\n createdAt: typeof payload.createdAt === 'string' ? payload.createdAt : '',\n updatedAt: typeof payload.updatedAt === 'string' ? payload.updatedAt : '',\n contentHash: hashIssueContent(title, body),\n raw: payload,\n };\n}\n\n/** Strip a leading `#` so both `23` and `#23` are accepted. */\nfunction normalizeId(id: string): string {\n return id.trim().replace(/^#/, '');\n}\n\n/** Page size for the relation endpoints — one page is enough in practice. */\nconst API_PAGE_SIZE = 100;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * `gh api <path>`, parsed as JSON.\n *\n * Answers `null` for every failure — a disabled feature (404), a plan without\n * Issue Dependencies (403), a network hiccup or unparseable output. That is the\n * whole graceful-degradation contract of `fetchRelations`: a source that cannot\n * answer contributes nothing instead of failing the discovery.\n */\nasync function ghApiJson(path: string): Promise<unknown> {\n try {\n const result = await gh(['api', path]);\n if (result.exitCode !== 0) return null;\n return JSON.parse(result.stdout) as unknown;\n } catch {\n return null;\n }\n}\n\n/** `number` of an Issue-shaped payload, as a string id. */\nfunction issueNumberOf(value: unknown): string | null {\n if (!isRecord(value)) return null;\n const number = value.number;\n return typeof number === 'number' && Number.isInteger(number) ? String(number) : null;\n}\n\n/** Ids of an array of Issue-shaped payloads, skipping anything unusable. */\nfunction issueNumbersOf(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return uniqueIds(\n value.map((entry) => issueNumberOf(entry) ?? '').filter((entry) => entry !== ''),\n );\n}\n\n/**\n * Issues that cited this one, from the timeline's `cross-referenced` events.\n *\n * Pull Requests are filtered out: they reference the Issue as *work on it*, not\n * as another demand to schedule.\n */\nfunction crossReferences(timeline: unknown, self: string): string[] {\n if (!Array.isArray(timeline)) return [];\n\n const ids: string[] = [];\n for (const event of timeline) {\n if (!isRecord(event) || event.event !== 'cross-referenced') continue;\n const source = isRecord(event.source) ? event.source : null;\n const issue = isRecord(source?.issue) ? source.issue : null;\n if (issue === null || issue.pull_request !== undefined) continue;\n const number = issueNumberOf(issue);\n if (number !== null) ids.push(number);\n }\n\n return uniqueIds(ids, self);\n}\n\nfunction extractIssueNumber(output: string): string | null {\n return output.match(/\\/issues\\/(\\d+)/)?.[1] ?? null;\n}\n\n/**\n * A failed `gh` result turned into an error that still carries its verdict.\n *\n * `run()` already classified it — every `gh` call here goes through the retry\n * chokepoint — so the kind, and with it the \"retry or escalate\" decision, must\n * not be flattened back into a message by the throw.\n */\nfunction ghError(message: string, result: ExecResult): Error {\n const failure = result.failure;\n if (failure === undefined) return new Error(message);\n return new ClassifiedError(message, failure, ghAction(failure));\n}\n\n/** The action a human has to take, for the kinds that need one. */\nfunction ghAction(failure: ClassifiedFailure): string | undefined {\n if (!requiresHumanAction(failure.kind)) return undefined;\n if (failure.kind === 'authentication') {\n return 'Run `gh auth login` to authenticate the GitHub CLI';\n }\n return undefined;\n}\n\n/**\n * A failed probe as an availability answer, keeping the classification.\n *\n * `action` is only attached when the failure actually needs a human: telling\n * someone to run `gh auth login` because their Wi-Fi dropped is worse than\n * saying nothing, and the caller uses the presence of an action to decide that\n * waiting will not help.\n */\nfunction unavailable(result: ExecResult, action: string): ProviderAvailability {\n const failure = result.failure;\n const needsHuman = failure === undefined || requiresHumanAction(failure.kind);\n return {\n available: false,\n ...(failure === undefined ? {} : { failure }),\n ...(needsHuman ? { action } : {}),\n };\n}\n\n/**\n * Issue provider backed by the GitHub CLI.\n *\n * Every call goes through `run` (execa, no shell) so tests can mock the shell\n * layer instead of the network, and so the Issue content is identical across\n * every pipeline phase.\n */\nexport class GitHubIssueProvider implements IssueProvider {\n readonly name = 'github' as const;\n\n /** True when gh is installed and authenticated. Never throws. */\n async isAvailable(): Promise<boolean> {\n return (await this.checkAvailability()).available;\n }\n\n /**\n * Whether gh is installed and authenticated, with the reason when it is not.\n *\n * Both probes retry on the capped probe budget, so a DNS blip during a long\n * run no longer reports GitHub as unavailable and takes the whole run down\n * with it — while an authentication failure is clamped to zero attempts by\n * `resolvePolicy()` and comes back immediately, with the action to take.\n */\n async checkAvailability(): Promise<ProviderAvailability> {\n try {\n const retry = ghProbePolicy();\n\n const version = await run('gh', ['--version'], { retry, timeout: PROBE_TIMEOUT_MS });\n if (version.exitCode !== 0) {\n return unavailable(version, 'Install the GitHub CLI: https://cli.github.com');\n }\n\n const auth = await run('gh', ['auth', 'status'], { retry, timeout: PROBE_TIMEOUT_MS });\n if (auth.exitCode !== 0) {\n return unavailable(auth, 'Run `gh auth login` to authenticate the GitHub CLI');\n }\n\n return { available: true };\n } catch {\n return { available: false };\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const result = await gh(['issue', 'view', issueId, '--json', VIEW_FIELDS]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n if (NOT_FOUND_PATTERN.test(detail)) return null;\n throw ghError(\n `Failed to fetch GitHub issue #${issueId}: ${detail || 'gh issue view failed'}`,\n result,\n );\n }\n\n let payload: GhIssuePayload;\n try {\n payload = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Failed to parse gh output for issue #${issueId}: ${result.stdout.slice(0, 200)}`,\n );\n }\n\n return toIssue(payload);\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n const args = ['issue', 'create', '--title', draft.title, '--body', draft.body];\n for (const label of draft.labels) {\n args.push('--label', label);\n }\n // Only when the draft actually chose one. An organization without Issue\n // Types rejects the flag outright, so it must never be sent speculatively.\n if (draft.type !== undefined && draft.type !== '') {\n args.push('--type', draft.type);\n }\n\n const result = await gh(args);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw ghError(`Failed to create GitHub issue: ${detail || 'gh issue create failed'}`, result);\n }\n\n const number = extractIssueNumber(result.stdout);\n if (!number) {\n throw new Error(\n `GitHub issue creation did not report an issue URL: ${result.stdout.trim() || '(no output)'}`,\n );\n }\n\n const created = await this.get(number);\n if (!created) {\n throw new Error(`GitHub issue #${number} was created but could not be read back`);\n }\n return created;\n }\n\n /**\n * Hierarchy and dependencies of an Issue, reconciled from three GitHub\n * mechanisms that only partially overlap:\n *\n * 1. **Sub-issues** (`/sub_issues` plus the `parent` field of the Issue\n * payload) — the native hierarchy;\n * 2. **Issue Dependencies** (`/dependencies/blocked_by` and `/blocking`);\n * 3. the **textual heuristic** over the body, for repositories that adopted\n * neither and write `Depends on #12` or `- [ ] #13` instead.\n *\n * Cross-references (`referencedBy`) come from the issue timeline, which is\n * the only place GitHub reports \"who cited me\" without a search query.\n *\n * Every source is queried independently and is allowed to fail on its own: an\n * organization without Issue Dependencies enabled answers 404 for two of the\n * five calls, and that has to cost the caller those two fields, never the\n * whole discovery. Only what could be read is reported — nothing here throws.\n */\n async fetchRelations(id: string): Promise<IssueRelations> {\n const issueId = normalizeId(id);\n if (!/^\\d+$/.test(issueId)) {\n // A non-numeric identifier cannot address a GitHub REST endpoint; the\n // Issue simply has no relations we can discover.\n return emptyRelations(issueId);\n }\n\n const base = `repos/{owner}/{repo}/issues/${issueId}`;\n const [payload, subIssues, blockedBy, blocking, timeline] = await Promise.all([\n ghApiJson(base),\n ghApiJson(`${base}/sub_issues?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/dependencies/blocked_by?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/dependencies/blocking?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/timeline?per_page=${API_PAGE_SIZE}`),\n ]);\n\n const issue = isRecord(payload) ? payload : null;\n // Without the REST payload the body still comes from `gh issue view`, so a\n // repository where only the REST API is blocked keeps the textual fallback.\n const body = typeof issue?.body === 'string' ? issue.body : await this.bodyFallback(issueId);\n\n const structured = {\n id: issueId,\n parent: issueNumberOf(issue?.parent),\n children: issueNumbersOf(subIssues),\n blockedBy: issueNumbersOf(blockedBy),\n blocking: issueNumbersOf(blocking),\n references: [],\n referencedBy: crossReferences(timeline, issueId),\n };\n\n return mergeRelations(structured, parseTextualRelations(body, issueId));\n }\n\n /** Body of an Issue when the REST payload could not be read. Never throws. */\n private async bodyFallback(issueId: string): Promise<string> {\n try {\n return (await this.get(issueId))?.body ?? '';\n } catch {\n return '';\n }\n }\n\n async close(id: string): Promise<void> {\n const issueId = normalizeId(id);\n const result = await gh(['issue', 'close', issueId]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw ghError(\n `Failed to close GitHub issue #${issueId}: ${detail || 'gh issue close failed'}`,\n result,\n );\n }\n }\n}\n\n/** Shared instance; providers are stateless, so a singleton is enough. */\nexport const githubIssueProvider = new GitHubIssueProvider();\n","import { constants } from 'node:fs';\nimport { access, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { ZodError } from 'zod';\nimport { isoNow } from '../../core/state-manager.js';\nimport { issueMetadataSchema } from '../../schemas.js';\nimport type { IssuePaths } from '../../storage/paths.js';\nimport { resolveIssuePaths, resolveProjectPaths } from '../../storage/resolve.js';\nimport { writeFileAtomic } from '../../utils/fs.js';\nimport { getProjectRoot } from '../../utils/git.js';\nimport { run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider } from '../provider.js';\nimport type { Issue, IssueDraft, IssueMetadata } from '../types.js';\n\n/** Timeout for the optional remote probes done while allocating an identifier. */\nconst REMOTE_PROBE_TIMEOUT_MS = 10_000;\n\nfunction isNotFound(err: unknown): boolean {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR';\n}\n\n/**\n * True when `dir` already is a writable directory, or does not exist yet but\n * would be created successfully by `mkdir(dir, { recursive: true })` — i.e.\n * its nearest existing ancestor is a writable directory.\n *\n * Never mutates the filesystem: `isAvailable()` only needs to answer \"could\n * this work\", which must not leave a `~/.issue-flow/projects/<id>/` directory\n * behind for a project that ends up never using local issues (every other\n * source is queried on every resolution, so this runs far more often than the\n * provider is actually chosen).\n */\nasync function isWritableDirectory(dir: string): Promise<boolean> {\n let current = dir;\n for (;;) {\n let stats: Awaited<ReturnType<typeof stat>>;\n try {\n stats = await stat(current);\n } catch (err: unknown) {\n if (!isNotFound(err)) return false;\n const parent = dirname(current);\n if (parent === current) return false; // reached the filesystem root\n current = parent;\n continue;\n }\n if (!stats.isDirectory()) return false;\n try {\n await access(current, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Identifiers become path segments, so anything that could escape the issues\n * directory is rejected before it reaches `join`.\n */\nfunction normalizeId(id: string): string {\n const normalized = id.trim().replace(/^#/, '');\n if (normalized.length === 0) {\n throw new Error('Local issue identifier cannot be empty');\n }\n if (/[/\\\\]/.test(normalized) || normalized === '.' || normalized === '..') {\n throw new Error(`Invalid local issue identifier: '${id}'`);\n }\n return normalized;\n}\n\nfunction toNumber(id: string): number | null {\n return /^\\d+$/.test(id) ? Number.parseInt(id, 10) : null;\n}\n\n/**\n * Title lives in the leading H1, body is everything after it.\n *\n * Only the first non-empty line is considered: an H1 further down belongs to\n * the body (issue descriptions routinely use headings), so promoting it would\n * silently retitle the Issue.\n */\nexport function parseIssueMarkdown(content: string): { title: string; body: string } {\n const lines = content.replace(/\\r\\n?/g, '\\n').split('\\n');\n const headingIndex = lines.findIndex((line) => line.trim().length > 0);\n const heading = headingIndex === -1 ? undefined : lines[headingIndex].match(/^#[ \\t]+(.*)$/);\n\n if (!heading) {\n return { title: '', body: lines.join('\\n').trim() };\n }\n\n return {\n title: heading[1].trim(),\n body: lines\n .slice(headingIndex + 1)\n .join('\\n')\n .trim(),\n };\n}\n\nfunction renderIssueMarkdown(title: string, body: string): string {\n return `# ${title}\\n\\n${body.trim()}\\n`;\n}\n\n/**\n * Issue provider backed by plain files in the project's global storage\n * directory (`~/.issue-flow/projects/<project-id>/issues/<id>/`).\n *\n * Enables the whole pipeline without any network access: no gh, no remote, no\n * authentication. `issue.md` is the source of truth for the content and\n * `metadata.json` for everything else; the content hash is always recomputed\n * from the file so a hand-edited issue.md is never reported as unchanged.\n *\n * Every path goes through `resolveIssuePaths()`, exactly like the pipeline\n * commands, so an issue that still only exists under the legacy\n * `<projectRoot>/issues/` tree is migrated on first read instead of coming back\n * as \"not found\".\n */\nexport class LocalFileIssueProvider implements IssueProvider {\n readonly name = 'local' as const;\n\n private readonly configuredRoot?: string;\n private cachedRoot?: string;\n\n /**\n * @param projectRoot Repository the issues belong to. It is no longer the\n * literal parent of an `issues/` directory: it is the root the project id —\n * and therefore the global storage directory — is derived from.\n */\n constructor(projectRoot?: string) {\n this.configuredRoot = projectRoot;\n }\n\n /**\n * True whenever the project's global storage directory already is — or\n * could be — a writable directory. Never mutates the filesystem, never\n * throws.\n *\n * A brand new project has no directory of its own until something writes, so\n * \"does it already exist\" would report the provider as unavailable exactly\n * when it is about to create the very first issue — `isWritableDirectory`\n * walks up to the nearest existing ancestor instead of requiring the leaf to\n * be there already.\n */\n async isAvailable(): Promise<boolean> {\n try {\n const { projectDir } = await resolveProjectPaths({ projectRoot: await this.root() });\n return await isWritableDirectory(projectDir);\n } catch {\n return false;\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const markdownPath = await this.issueFile(issueId);\n\n let raw: string;\n try {\n raw = await readFile(markdownPath, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n const { title: headingTitle, body } = parseIssueMarkdown(raw);\n const metadata = await this.readMetadata(issueId);\n const title = headingTitle || metadata?.title || '';\n\n if (metadata) {\n return {\n id: metadata.id,\n number: metadata.number,\n title,\n body,\n labels: metadata.labels,\n state: metadata.state,\n source: 'local',\n remoteRef: metadata.remote?.ref ?? null,\n createdAt: metadata.createdAt,\n updatedAt: metadata.updatedAt,\n contentHash: hashIssueContent(title, body),\n raw: metadata,\n };\n }\n\n // metadata.json is optional: an issue.md dropped in by hand still works,\n // with timestamps taken from the file itself.\n const stats = await stat(markdownPath);\n return {\n id: issueId,\n number: toNumber(issueId),\n title,\n body,\n labels: [],\n state: 'open',\n source: 'local',\n remoteRef: null,\n createdAt: stats.birthtime.toISOString(),\n updatedAt: stats.mtime.toISOString(),\n contentHash: hashIssueContent(title, body),\n };\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n // An explicit id is how a mirror keeps the identifier of the Issue it\n // mirrors: allocating a fresh one would make `issue-flow run <n>` see two\n // unrelated Issues instead of one demand in two places.\n const id = draft.id === undefined ? String(await this.allocateNumber()) : normalizeId(draft.id);\n const paths = await this.paths(id);\n\n await mkdir(paths.issueDir, { recursive: true });\n\n // Exclusive create (the 'wx' flag, O_EXCL under the hood) instead of a\n // check-then-write: two concurrent `create()` calls racing the same id\n // would both pass a plain existence check before either writes, and the\n // second would then silently overwrite the first through the atomic\n // temp+rename writer. The OS now rejects the loser instead.\n try {\n await writeFile(paths.issueFile, renderIssueMarkdown(draft.title, draft.body), {\n encoding: 'utf-8',\n flag: 'wx',\n });\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(\n `Local issue '${id}' already exists at ${paths.issueFile}. ` +\n 'Remove it or pick another identifier before creating a new Issue.',\n );\n }\n throw err;\n }\n\n const timestamp = isoNow();\n const metadata: IssueMetadata = {\n schemaVersion: 1,\n id,\n number: toNumber(id),\n source: 'local',\n title: draft.title,\n labels: draft.labels,\n state: 'open',\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: hashIssueContent(draft.title, draft.body),\n ...(draft.remote ? { remote: draft.remote } : {}),\n };\n\n await this.writeMetadata(id, metadata);\n\n return {\n id,\n number: metadata.number,\n title: draft.title,\n body: draft.body.trim(),\n labels: draft.labels,\n state: 'open',\n source: 'local',\n remoteRef: draft.remote?.ref ?? null,\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: metadata.contentHash,\n raw: metadata,\n };\n }\n\n async close(id: string): Promise<void> {\n const issue = await this.get(id);\n if (!issue) {\n const issueDir = (await this.paths(normalizeId(id))).issueDir;\n throw new Error(`Local issue '${normalizeId(id)}' not found at ${issueDir}`);\n }\n\n const issueId = normalizeId(id);\n const existing = await this.readMetadata(issueId);\n\n await this.writeMetadata(issueId, {\n schemaVersion: 1,\n id: issue.id,\n number: issue.number,\n source: existing?.source ?? 'local',\n title: issue.title,\n labels: issue.labels,\n state: 'closed',\n createdAt: issue.createdAt,\n updatedAt: isoNow(),\n contentHash: issue.contentHash,\n ...(existing?.remote ? { remote: existing.remote } : {}),\n });\n }\n\n /**\n * Next free identifier: above every local number and, when GitHub answers,\n * above every remote one too. Sharing a numbering space with the remote is\n * what makes a naive `localMax + 1` collide the moment someone opens an Issue\n * on GitHub.\n */\n async allocateNumber(): Promise<number> {\n const [local, remote] = await Promise.all([this.highestLocalNumber(), highestRemoteNumber()]);\n return Math.max(local, remote) + 1;\n }\n\n private async root(): Promise<string> {\n if (this.configuredRoot !== undefined) return this.configuredRoot;\n this.cachedRoot ??= await getProjectRoot();\n return this.cachedRoot;\n }\n\n /**\n * Every artifact of one issue, from the same resolver the pipeline commands\n * use — which is also what triggers the migration of a legacy-only issue.\n */\n private async paths(id: string): Promise<IssuePaths> {\n return resolveIssuePaths(id, { projectRoot: await this.root() });\n }\n\n private async issueFile(id: string): Promise<string> {\n return (await this.paths(id)).issueFile;\n }\n\n private async metadataFile(id: string): Promise<string> {\n return (await this.paths(id)).metadataFile;\n }\n\n /** Parsed metadata.json, or `null` when the file is absent. */\n private async readMetadata(id: string): Promise<IssueMetadata | null> {\n const path = await this.metadataFile(id);\n\n let raw: string;\n try {\n raw = await readFile(path, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err: unknown) {\n throw new Error(`Invalid JSON in ${path}: ${(err as Error).message}`);\n }\n\n try {\n return issueMetadataSchema.parse(parsed);\n } catch (err: unknown) {\n if (err instanceof ZodError) {\n const details = err.issues\n .map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('\\n');\n throw new Error(`Invalid issue metadata at ${path}:\\n${details}`);\n }\n throw err;\n }\n }\n\n private async writeMetadata(id: string, metadata: IssueMetadata): Promise<void> {\n await writeFileAtomic(await this.metadataFile(id), `${JSON.stringify(metadata, null, 2)}\\n`);\n }\n\n /**\n * Highest number across every `<issuesDir>/<id>/metadata.json` and numeric\n * directory name.\n *\n * Resolving `issuesDir` also migrates the legacy tree when it is the only one\n * that exists, which is what keeps an already-taken number from being handed\n * out a second time after adopting the global storage.\n */\n private async highestLocalNumber(): Promise<number> {\n const { issuesDir: dir } = await resolveProjectPaths({ projectRoot: await this.root() });\n\n let entries: string[];\n try {\n entries = (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n } catch (err: unknown) {\n if (isNotFound(err)) return 0;\n throw err;\n }\n\n const numbers = await Promise.all(\n entries.map(async (name) => {\n const fromName = toNumber(name) ?? 0;\n // A directory whose metadata is unreadable still occupies its number.\n const fromMetadata = await this.readMetadata(name)\n .then((metadata) => metadata?.number ?? 0)\n .catch(() => 0);\n return Math.max(fromName, fromMetadata);\n }),\n );\n\n return numbers.reduce((max, value) => Math.max(max, value), 0);\n }\n}\n\n/** How many of the most-recently-created issues/PRs to inspect per probe. */\nconst REMOTE_PROBE_SAMPLE_SIZE = 20;\n\n/**\n * Highest number already taken on GitHub, or 0 when the remote is unreachable.\n *\n * Issues and pull requests share one counter, so both are probed: allocating\n * above the newest Issue alone would still collide with an open PR. Every\n * failure degrades to 0 — being offline must not block local creation.\n *\n * `gh ... list` defaults to sorting by creation date descending, which lines\n * up with number order in the overwhelming majority of repos — but that sort\n * is an implementation detail, not a contract. Rather than trust that the\n * single most-recent entry is also the highest-numbered one, a small sample\n * is fetched and the max is taken across it, which also tolerates the rare\n * case of a transferred issue whose creation date and number disagree.\n */\nasync function highestRemoteNumber(): Promise<number> {\n const probes = [\n ['issue', 'list'],\n ['pr', 'list'],\n ];\n\n const results = await Promise.all(\n probes.map(async (args) => {\n try {\n const result = await run(\n 'gh',\n [\n ...args,\n '--state',\n 'all',\n '--limit',\n String(REMOTE_PROBE_SAMPLE_SIZE),\n '--json',\n 'number',\n ],\n { timeout: REMOTE_PROBE_TIMEOUT_MS },\n );\n if (result.exitCode !== 0) return 0;\n\n const parsed = JSON.parse(result.stdout);\n if (!Array.isArray(parsed)) return 0;\n return parsed.reduce((max: number, entry: unknown) => {\n const n = (entry as { number?: unknown } | null)?.number;\n return typeof n === 'number' ? Math.max(max, n) : max;\n }, 0);\n } catch {\n return 0;\n }\n }),\n );\n\n return results.reduce((max, value) => Math.max(max, value), 0);\n}\n\n/** Shared instance resolving the project root lazily via git. */\nexport const localFileIssueProvider = new LocalFileIssueProvider();\n","import { githubIssueProvider } from './providers/github.js';\nimport { localFileIssueProvider } from './providers/local.js';\nimport { getRegisteredSources, registerProvider } from './registry.js';\n\n/**\n * Register the providers that ship with issue-flow.\n *\n * Idempotent and non-destructive: an origin that is already registered is left\n * untouched, so a test (or a future plugin) can install its own provider before\n * the first `resolveIssue` call without having it replaced by the built-in one.\n */\nexport function ensureProvidersRegistered(): void {\n const registered = new Set(getRegisteredSources());\n\n if (!registered.has('github')) {\n registerProvider(githubIssueProvider);\n }\n if (!registered.has('local')) {\n registerProvider(localFileIssueProvider);\n }\n}\n","import { createInterface, type Interface as ReadlineInterface } from 'node:readline';\nimport { loadIssuesConfig } from '../config.js';\nimport { actionOf, type ClassifiedFailure, failureOf } from '../resilience/errors.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport { ensureProvidersRegistered } from './bootstrap.js';\nimport type { ProviderAvailability } from './provider.js';\nimport { getProvider, getRegisteredSources } from './registry.js';\nimport type { Issue, IssueSource, IssuesConfig, ResolvedIssue } from './types.js';\n\n/**\n * Failure to settle on an Issue. Carries the exit code the CLI should return,\n * so callers propagate it instead of inventing their own.\n */\nexport class IssueResolutionError extends Error {\n readonly exitCode: number;\n /**\n * The verdict of the origin that failed, when one origin failed for a reason\n * worth naming. It is what tells \"this Issue does not exist\" apart from\n * \"GitHub could not be reached\", which are the same message today.\n */\n readonly failure: ClassifiedFailure | undefined;\n /** What a human has to do, for a failure that waiting cannot fix. */\n readonly action: string | undefined;\n\n constructor(\n message: string,\n exitCode = 1,\n details: { failure?: ClassifiedFailure; action?: string } = {},\n ) {\n super(message);\n this.name = 'IssueResolutionError';\n this.exitCode = exitCode;\n this.failure = details.failure;\n this.action = details.action;\n }\n}\n\nexport interface ResolveIssueOptions {\n /** Already-resolved provider configuration. Defaults to loadIssuesConfig(). */\n config?: IssuesConfig;\n /** Origins to query. Defaults to every registered source. */\n sources?: IssueSource[];\n /**\n * Whether a prompt may be shown. Defaults to a real TTY outside CI, which is\n * what keeps `ask` from ever blocking a headless run.\n */\n interactive?: boolean;\n /** Input stream for the conflict prompt. Defaults to process.stdin. */\n stdin?: NodeJS.ReadableStream;\n /** Output stream for the conflict prompt. Defaults to process.stdout. */\n stdout?: NodeJS.WritableStream;\n /** Informational sink. Defaults to printInfo. */\n info?: (message: string) => void;\n /** Warning sink. Defaults to printWarning. */\n warn?: (message: string) => void;\n}\n\n/** How many invalid answers are tolerated before the prompt gives up. */\nconst MAX_PROMPT_ATTEMPTS = 3;\n\n/**\n * Labels shown to users for the built-in origins. An origin registered from\n * outside this package is displayed under its own name, so a new provider needs\n * no entry here.\n */\nconst SOURCE_LABELS: Record<string, string> = {\n github: 'GitHub',\n local: 'local',\n};\n\nfunction sourceLabel(source: IssueSource): string {\n return SOURCE_LABELS[source] ?? source;\n}\n\n/** Same label, capitalized for the numbered prompt ('local' -> 'Local'). */\nfunction promptLabel(source: IssueSource): string {\n const label = sourceLabel(source);\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\n\ninterface Candidate {\n source: IssueSource;\n issue: Issue | null;\n /** Why the origin produced nothing, used only to explain a total miss. */\n reason: string | null;\n /** The classified verdict behind `reason`, when the origin could give one. */\n failure?: ClassifiedFailure;\n /** What a human has to do about it (`gh auth login`), when that applies. */\n action?: string;\n}\n\n/** A candidate that actually produced an Issue. */\ninterface FoundCandidate extends Candidate {\n issue: Issue;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Read one origin without letting it break the others.\n *\n * An unavailable provider or a failed read degrades to \"no candidate\" plus a\n * reason: as long as another origin has the Issue the pipeline keeps going, and\n * when nothing is found the reasons are surfaced in the final error so a broken\n * environment is never reported as a missing Issue.\n */\nasync function fetchCandidate(\n source: IssueSource,\n id: string,\n warn: (message: string) => void,\n): Promise<Candidate> {\n let provider: ReturnType<typeof getProvider>;\n try {\n provider = getProvider(source);\n } catch (err) {\n return { source, issue: null, reason: errorMessage(err) };\n }\n\n let availability: ProviderAvailability;\n try {\n availability = (await provider.checkAvailability?.()) ?? {\n available: await provider.isAvailable(),\n };\n } catch (err) {\n return { source, issue: null, reason: `provider unavailable (${errorMessage(err)})` };\n }\n if (!availability.available) {\n // The classified reason replaces the flat \"provider unavailable\": a\n // credential that expired and a network that blipped were indistinguishable\n // before, and only one of them is worth telling a human about.\n const reason = availability.failure?.message ?? 'provider unavailable';\n return {\n source,\n issue: null,\n reason,\n ...(availability.failure === undefined ? {} : { failure: availability.failure }),\n ...(availability.action === undefined ? {} : { action: availability.action }),\n };\n }\n\n try {\n const issue = await provider.get(id);\n return { source, issue, reason: issue === null ? 'not found' : null };\n } catch (err) {\n const reason = errorMessage(err);\n // A real failure (network, auth, corrupted metadata) must be visible even\n // when the other origin answers.\n warn(`Could not read issue '${id}' from ${sourceLabel(source)}: ${reason}`);\n const failure = failureOf(err);\n const action = actionOf(err);\n return {\n source,\n issue: null,\n reason,\n ...(failure === null ? {} : { failure }),\n ...(action === null ? {} : { action }),\n };\n }\n}\n\nfunction shortHash(hash: string): string {\n const hex = hash.startsWith('sha256:') ? hash.slice('sha256:'.length) : hash;\n return hex.slice(0, 12);\n}\n\n/** One line per origin describing what differs, without dumping every body. */\nfunction describeCandidate(source: IssueSource, issue: Issue): string {\n const lines = issue.body.length === 0 ? 0 : issue.body.split('\\n').length;\n return (\n ` ${sourceLabel(source).padEnd(6)} title: \"${issue.title}\" | body: ${lines} line(s), ` +\n `${issue.body.length} char(s) | updated: ${issue.updatedAt} | hash: ${shortHash(issue.contentHash)}`\n );\n}\n\n/** 'local and GitHub', 'local, GitHub and memory' — origins in query order. */\nfunction listSources(candidates: FoundCandidate[]): string {\n const labels = candidates.map((candidate) => sourceLabel(candidate.source));\n if (labels.length <= 1) {\n return labels.join('');\n }\n return `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`;\n}\n\n/**\n * Turn a readline interface into an awaitable line reader.\n *\n * Lines are queued instead of read on demand: `rl.question` drops whatever\n * arrives between two questions, which silently loses a piped answer typed\n * ahead of the prompt. Resolves `null` once the input is exhausted, so EOF ends\n * the prompt instead of hanging the process.\n */\nfunction createLineReader(\n rl: ReadlineInterface,\n output: NodeJS.WritableStream,\n): (query: string) => Promise<string | null> {\n const queued: string[] = [];\n let pending: ((line: string | null) => void) | null = null;\n let closed = false;\n\n rl.on('line', (line: string) => {\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(line);\n return;\n }\n queued.push(line);\n });\n rl.on('close', () => {\n closed = true;\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(null);\n }\n });\n\n return (query: string) =>\n new Promise<string | null>((resolve) => {\n const buffered = queued.shift();\n if (buffered !== undefined) {\n resolve(buffered);\n return;\n }\n if (closed) {\n resolve(null);\n return;\n }\n output.write(query);\n pending = resolve;\n });\n}\n\n/**\n * Interactive choice between the divergent versions.\n *\n * The options are numbered from the origins that actually answered, so a third\n * provider simply shows up as `[3] Memory` without this function knowing which\n * origins exist. Cancel is always the last option.\n */\nasync function promptChoice(\n sources: IssueSource[],\n stdin: NodeJS.ReadableStream,\n stdout: NodeJS.WritableStream,\n warn: (message: string) => void,\n): Promise<IssueSource | 'cancel'> {\n const options = sources.map((source, index) => `[${index + 1}] ${promptLabel(source)}`);\n const cancelOption = sources.length + 1;\n const query = `Which version should be used? ${options.join(' ')} [${cancelOption}] Cancel: `;\n const numbers = Array.from({ length: cancelOption }, (_, index) => String(index + 1));\n const accepted = `${numbers.slice(0, -1).join(', ')} or ${numbers[numbers.length - 1]}`;\n\n const rl = createInterface({ input: stdin, output: stdout });\n const ask = createLineReader(rl, stdout);\n try {\n for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt++) {\n const answer = await ask(query);\n if (answer === null) {\n return 'cancel';\n }\n const choice = answer.trim();\n const picked = sources[Number(choice) - 1];\n if (choice.length > 0 && picked !== undefined) {\n return picked;\n }\n if (choice === String(cancelOption)) {\n return 'cancel';\n }\n warn(`Invalid choice: '${choice}'. Enter ${accepted}.`);\n }\n return 'cancel';\n } finally {\n rl.close();\n }\n}\n\nfunction isInteractiveByDefault(): boolean {\n const ci = process.env.CI;\n const inCi = ci !== undefined && ci !== '' && ci !== '0' && ci.toLowerCase() !== 'false';\n return Boolean(process.stdin.isTTY) && !inCi;\n}\n\nfunction buildResolved(\n issue: Issue,\n source: IssueSource,\n local: Issue | null,\n github: Issue | null,\n divergent: boolean,\n): ResolvedIssue {\n return { issue, source, local, github, divergent };\n}\n\n/** Origin `conflictPolicy` points at, or `null` for 'ask'. */\nfunction policyTarget(policy: IssuesConfig['conflictPolicy']): IssueSource | null {\n if (policy === 'prefer-local') {\n return 'local';\n }\n if (policy === 'prefer-github') {\n return 'github';\n }\n return null;\n}\n\n/**\n * Single entry point every command uses to decide which Issue the pipeline\n * works on.\n *\n * The logic is written against the origins that answered, never against a fixed\n * list of sources: registering a new provider is enough for it to take part in\n * the resolution, be reported in a divergence and appear in the prompt.\n *\n * Scenarios:\n * - only one origin has it -> that one, no questions asked;\n * - several, same contentHash -> equivalence is reported and the preferred\n * origin wins, without a prompt;\n * - several, different content -> the divergence is reported and\n * `conflictPolicy` decides (`ask` prompts on a TTY, falls back to\n * `preferredProvider` with a warning anywhere else);\n * - none -> IssueResolutionError, which carries the CLI exit code.\n */\nexport async function resolveIssue(\n id: string,\n opts: ResolveIssueOptions = {},\n): Promise<ResolvedIssue> {\n const info = opts.info ?? printInfo;\n const warn = opts.warn ?? printWarning;\n const config = opts.config ?? (await loadIssuesConfig({ warn }));\n\n ensureProvidersRegistered();\n const sources = opts.sources ?? getRegisteredSources();\n\n // Each origin is an independent I/O call (network for GitHub, disk for\n // local); querying them concurrently instead of one-by-one keeps the total\n // latency at the slowest origin instead of the sum of all of them, without\n // changing which candidate wins (order is preserved by Promise.all).\n const candidates: Candidate[] = await Promise.all(\n sources.map((source) => fetchCandidate(source, id, warn)),\n );\n\n const issueOf = (source: IssueSource): Issue | null =>\n candidates.find((candidate) => candidate.source === source)?.issue ?? null;\n const local = issueOf('local');\n const github = issueOf('github');\n\n const found = candidates.filter(\n (candidate): candidate is FoundCandidate => candidate.issue !== null,\n );\n\n if (found.length === 0) {\n const details = candidates\n .map((candidate) => `${sourceLabel(candidate.source)}: ${candidate.reason ?? 'not found'}`)\n .join('; ');\n const where = details.length > 0 ? ` (${details})` : '';\n\n // An origin that needs a human is the answer, not a footnote: reporting\n // \"Issue not found\" for an expired credential sends the user looking for\n // the wrong problem, and no amount of retrying would have helped.\n const blocking = candidates.find((candidate) => candidate.action !== undefined);\n if (blocking !== undefined) {\n throw new IssueResolutionError(\n `Cannot read issue '${id}' from ${sourceLabel(blocking.source)}: ${blocking.reason}`,\n 1,\n {\n ...(blocking.failure === undefined ? {} : { failure: blocking.failure }),\n ...(blocking.action === undefined ? {} : { action: blocking.action }),\n },\n );\n }\n\n throw new IssueResolutionError(`Issue '${id}' not found in any registered origin${where}`);\n }\n\n const build = (candidate: FoundCandidate, divergent: boolean): ResolvedIssue =>\n buildResolved(candidate.issue, candidate.source, local, github, divergent);\n\n const firstFound = found[0] as FoundCandidate;\n if (found.length === 1) {\n return build(firstFound, false);\n }\n\n // Several origins have it. The preferred one wins whenever it is among them;\n // otherwise the first origin queried does, so an unrelated preference never\n // leaves the pipeline without an Issue.\n const preferred =\n found.find((candidate) => candidate.source === config.preferredProvider) ?? firstFound;\n\n const distinct = new Set(found.map((candidate) => candidate.issue.contentHash));\n if (distinct.size === 1) {\n info(\n `Issue '${id}' has identical content in ${listSources(found)}; using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, false);\n }\n\n info(`Issue '${id}' differs between origins:`);\n for (const candidate of found) {\n info(describeCandidate(candidate.source, candidate.issue));\n }\n\n const target = policyTarget(config.conflictPolicy);\n if (target !== null) {\n const chosen = found.find((candidate) => candidate.source === target);\n if (chosen !== undefined) {\n info(`Conflict policy '${config.conflictPolicy}': using the ${sourceLabel(target)} version.`);\n return build(chosen, true);\n }\n // The policy names an origin that has no version of this Issue: say so\n // instead of silently picking for the user under its name.\n warn(\n `Conflict policy '${config.conflictPolicy}' does not apply to Issue '${id}' ` +\n `(${sourceLabel(target)} has no version of it); using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, true);\n }\n\n const interactive = opts.interactive ?? isInteractiveByDefault();\n if (!interactive) {\n warn(\n `Divergent Issue '${id}' and conflict policy 'ask' in a non-interactive environment; ` +\n `using the preferred provider (${sourceLabel(preferred.source)}).`,\n );\n return build(preferred, true);\n }\n\n const choice = await promptChoice(\n found.map((candidate) => candidate.source),\n opts.stdin ?? process.stdin,\n opts.stdout ?? process.stdout,\n warn,\n );\n if (choice === 'cancel') {\n throw new IssueResolutionError(\n `Cancelled: Issue '${id}' diverges between ${listSources(found)}.`,\n );\n }\n const picked = found.find((candidate) => candidate.source === choice) as FoundCandidate;\n return build(picked, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAM,YAAY,oBAAI,IAAgC;AAQ/C,SAAS,iBAAiB,UAA+B;AAC9D,YAAU,IAAI,SAAS,MAAM,QAAQ;AACvC;AAGO,SAAS,uBAAsC;AACpD,SAAO,CAAC,GAAG,UAAU,KAAK,CAAC;AAC7B;AAQO,SAAS,YAAY,QAAoC;AAC9D,QAAM,WAAW,UAAU,IAAI,MAAM;AACrC,MAAI,aAAa,QAAW;AAC1B,UAAM,YAAY,qBAAqB;AACvC,UAAM,OACJ,UAAU,SAAS,IACf,sBAAsB,UAAU,KAAK,IAAI,CAAC,MAC1C;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,MAAM,WAAW,IAAI;AAAA,EAC9B;AAEA,QAAM,SAAS,MAAM;AAAA,IACnB,MAAM,IAAI,CAAC,cAAc,UAAU,MAAM;AAAA,IACzC,KAAK,SAAS,QAAQ;AAAA,IACtB,KAAK,UAAU,QAAQ;AAAA,IACvB;AAAA,EACF;AACA,MAAI,WAAW,UAAU;AACvB,UAAM,IAAI;AAAA,MACR,qBAAqB,EAAE,sBAAsB,YAAY,KAAK,CAAC;AAAA,IACjE;AAAA,EACF;AACA,QAAM,SAAS,MAAM,KAAK,CAAC,cAAc,UAAU,WAAW,MAAM;AACpE,SAAO,MAAM,QAAQ,IAAI;AAC3B;","names":["normalizeId"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/telemetry/recorder.ts","../src/telemetry/pricing.ts","../src/telemetry/types.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport type { ClaudeUsage } from '../core/metrics.js';\nimport { isoNow, loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { classify } from '../resilience/errors.js';\nimport type { TaskPlan } from '../types.js';\nimport { resolveCost } from './pricing.js';\nimport { redactFailureMessage } from './redact.js';\nimport { getTelemetrySessionId, setTelemetrySessionId } from './session-id.js';\nimport {\n DEFAULT_TELEMETRY_CONFIG,\n type ExecutionPurpose,\n type ExecutionRecord,\n type ExecutionStatus,\n type ExecutionTrigger,\n type NormalizedUsage,\n type StopReason,\n type TelemetryConfig,\n} from './types.js';\n\nexport interface TelemetryContext {\n tasksPath: string;\n sessionId?: string | null;\n config?: TelemetryConfig;\n}\n\nlet context: TelemetryContext | null = null;\nlet discardedCount = 0;\n\nexport function bindTelemetry(next: TelemetryContext | null): void {\n context = next;\n}\n\nexport function getTelemetryContext(): TelemetryContext | null {\n return context;\n}\n\nexport function discardedExecutionCount(): number {\n return discardedCount;\n}\n\nexport function resetTelemetryState(): void {\n context = null;\n discardedCount = 0;\n setTelemetrySessionId(null);\n}\n\nasync function resolveConfig(ctx: TelemetryContext): Promise<TelemetryConfig> {\n if (ctx.config !== undefined) return ctx.config;\n try {\n const { loadTelemetryConfig } = await import('../config.js');\n ctx.config = await loadTelemetryConfig();\n return ctx.config;\n } catch {\n return DEFAULT_TELEMETRY_CONFIG;\n }\n}\n\nfunction cap(records: ExecutionRecord[], max: number): ExecutionRecord[] {\n if (records.length <= max) return records;\n discardedCount += records.length - max;\n return records.slice(records.length - max);\n}\n\nasync function mutate(tasksPath: string, update: (plan: TaskPlan) => TaskPlan): Promise<void> {\n const plan = await loadTaskPlan(tasksPath);\n await saveTaskPlan(tasksPath, update(plan));\n}\n\nexport function usageFromClaude(usage: ClaudeUsage | null | undefined): NormalizedUsage | null {\n if (usage === undefined || usage === null) return null;\n const next: NormalizedUsage = { source: 'provider' };\n if (usage.inputTokens !== undefined) next.inputTokens = usage.inputTokens;\n if (usage.outputTokens !== undefined) next.outputTokens = usage.outputTokens;\n if (usage.cacheReadTokens !== undefined) next.cacheReadTokens = usage.cacheReadTokens;\n if (usage.cacheCreationTokens !== undefined) next.cacheCreationTokens = usage.cacheCreationTokens;\n return next;\n}\n\nexport interface BeginExecutionInput {\n purpose: ExecutionPurpose;\n attempt?: number;\n trigger?: ExecutionTrigger;\n triggerReason?: ExecutionRecord['triggerReason'];\n harness: string;\n provider?: string | null;\n harnessVersion?: string | null;\n modelRequested?: string | null;\n modelResolved?: string | null;\n modelSource?: ExecutionRecord['agent']['model']['source'];\n iteration?: number;\n correctionCycle?: number;\n storyIds?: string[];\n routingDecision?: ExecutionRecord['routingDecision'];\n}\n\nexport async function beginExecution(input: BeginExecutionInput): Promise<string | null> {\n const ctx = context;\n if (ctx === null) return null;\n const cfg = await resolveConfig(ctx);\n if (!cfg.enabled) return null;\n\n const id = randomUUID();\n const record: ExecutionRecord = {\n id,\n sessionId: ctx.sessionId ?? getTelemetrySessionId(),\n purpose: input.purpose,\n attempt: input.attempt ?? 1,\n trigger: input.trigger ?? 'initial',\n triggerReason: input.triggerReason ?? null,\n agent: {\n harness: input.harness,\n provider: input.provider ?? null,\n harnessVersion: input.harnessVersion ?? null,\n model: {\n requested: input.modelRequested ?? null,\n resolved: input.modelResolved ?? null,\n source: input.modelSource ?? (input.modelResolved ? 'provider' : 'unavailable'),\n },\n providerSessionId: null,\n },\n startedAt: isoNow(),\n finishedAt: null,\n durationMs: null,\n usage: null,\n cost: { status: 'unknown', reason: 'not_reported' },\n status: 'running',\n failure: null,\n owner: { pid: process.pid, host: hostname() },\n ...(input.iteration === undefined ? {} : { iteration: input.iteration }),\n ...(input.correctionCycle === undefined ? {} : { correctionCycle: input.correctionCycle }),\n ...(input.storyIds === undefined ? {} : { storyIds: input.storyIds }),\n ...(input.routingDecision === undefined || input.routingDecision === null\n ? {}\n : { routingDecision: input.routingDecision }),\n };\n\n try {\n await mutate(ctx.tasksPath, (plan) => ({\n ...plan,\n executions: cap([...(plan.executions ?? []), record], cfg.maxExecutions),\n }));\n const { getSessionPublisher } = await import('../core/session-publisher.js');\n getSessionPublisher().publish({\n type: 'execution:update',\n at: record.startedAt,\n execution: record,\n });\n return id;\n } catch {\n return null;\n }\n}\n\n/** Wall clock vs CLI envelope: startup the harness does not report. */\nexport function timingFromUsage(\n wallClockMs: number | null,\n usage: ClaudeUsage | null | undefined,\n): Pick<\n ExecutionRecord,\n 'cliDurationMs' | 'harnessStartupMs' | 'apiDurationMs' | 'ttftMs' | 'numTurns'\n> {\n const cli = usage?.cliDurationMs;\n const cliDurationMs = cli === undefined ? null : cli;\n const harnessStartupMs =\n wallClockMs !== null && cli !== undefined ? Math.max(0, wallClockMs - cli) : null;\n return {\n cliDurationMs,\n harnessStartupMs,\n apiDurationMs: usage?.apiDurationMs ?? null,\n ttftMs: usage?.ttftMs ?? null,\n numTurns: usage?.numTurns ?? null,\n };\n}\n\nexport async function attachVerdict(verdict: ExecutionRecord['verdict']): Promise<void> {\n const ctx = context;\n if (ctx === null || verdict == null) return;\n try {\n await mutate(ctx.tasksPath, (plan) => {\n const records = [...(plan.executions ?? [])];\n if (records.length === 0) return plan;\n const index = records.length - 1;\n const current = records[index];\n if (current === undefined) return plan;\n records[index] = { ...current, verdict };\n return { ...plan, executions: records };\n });\n } catch {\n // Observational: a failed write must never change the invocation outcome.\n }\n}\n\nexport interface EndExecutionInput {\n id: string;\n status?: ExecutionStatus;\n usage?: ClaudeUsage | null;\n reportedUsd?: number | null;\n error?: string | null;\n exitCode?: number | null;\n storyIds?: string[];\n cancelled?: boolean;\n timedOut?: boolean;\n modelResolved?: string | null;\n modelSource?: ExecutionRecord['agent']['model']['source'];\n harnessVersion?: string | null;\n providerSessionId?: string | null;\n stopReason?: StopReason | null;\n}\n\nexport async function endExecution(input: EndExecutionInput): Promise<void> {\n const ctx = context;\n if (ctx === null) return;\n const cfg = await resolveConfig(ctx);\n if (!cfg.enabled) return;\n\n const usage = usageFromClaude(input.usage);\n const timedOut = input.timedOut === true || /\\btimed out\\b/i.test(input.error ?? '');\n const cancelled = input.cancelled === true;\n let status: ExecutionStatus = input.status ?? 'completed';\n if (input.status === undefined) {\n if (cancelled) status = 'cancelled';\n else if (timedOut) status = 'timeout';\n else if (input.error) status = 'failed';\n }\n\n const failure =\n status === 'completed'\n ? null\n : {\n kind: classify({\n source: 'agent',\n stdout: input.error ?? '',\n exitCode: input.exitCode,\n timedOut,\n }).kind,\n message: redactFailureMessage(input.error ?? status),\n exitCode: input.exitCode ?? null,\n };\n\n const completed: { value: ExecutionRecord | null } = { value: null };\n try {\n await mutate(ctx.tasksPath, (plan) => {\n const records = [...(plan.executions ?? [])];\n const index = records.findIndex((record) => record.id === input.id);\n if (index === -1) return plan;\n const current = records[index];\n if (current === undefined) return plan;\n const started = Date.parse(current.startedAt);\n const finishedAt = isoNow();\n const modelResolved = input.modelResolved ?? current.agent.model.resolved;\n const modelKey = modelResolved ?? current.agent.model.requested;\n records[index] = {\n ...current,\n agent: {\n ...current.agent,\n harnessVersion: input.harnessVersion ?? current.agent.harnessVersion,\n providerSessionId: input.providerSessionId ?? current.agent.providerSessionId,\n model: {\n ...current.agent.model,\n resolved: modelResolved,\n source:\n input.modelSource ??\n (modelResolved\n ? current.agent.model.source === 'unavailable'\n ? 'provider'\n : current.agent.model.source\n : current.agent.model.source),\n },\n },\n finishedAt,\n durationMs: Number.isFinite(started) ? Math.max(0, Date.now() - started) : null,\n ...timingFromUsage(\n Number.isFinite(started) ? Math.max(0, Date.now() - started) : null,\n input.usage,\n ),\n usage,\n cost: resolveCost({\n reportedUsd: input.reportedUsd ?? input.usage?.costUsd,\n usage,\n modelKey,\n estimate: cfg.pricing.estimate,\n overrides: cfg.pricing.overrides,\n }),\n status,\n failure,\n owner: null,\n ...(input.storyIds === undefined ? {} : { storyIds: input.storyIds }),\n ...(input.stopReason === undefined ? {} : { stopReason: input.stopReason }),\n };\n completed.value = records[index] ?? null;\n return { ...plan, executions: records };\n });\n if (completed.value !== null) {\n const { getSessionPublisher } = await import('../core/session-publisher.js');\n getSessionPublisher().publish({\n type: 'execution:update',\n at: completed.value.finishedAt ?? isoNow(),\n execution: completed.value,\n });\n }\n } catch {\n // Observational: a failed write must never change the invocation outcome.\n }\n}\n\nexport async function recordInvocation<T>(\n input: BeginExecutionInput,\n invoke: () => Promise<T>,\n finish: (result: T) => EndExecutionInput,\n): Promise<T> {\n const id = await beginExecution(input);\n try {\n const result = await invoke();\n if (id !== null) {\n await endExecution({ ...finish(result), id });\n }\n return result;\n } catch (err) {\n if (id !== null) {\n await endExecution({\n id,\n status: 'failed',\n error: err instanceof Error ? err.message : String(err),\n });\n }\n throw err;\n }\n}\n","import { isoNow } from '../core/state-manager.js';\nimport type { CostRecord, NormalizedUsage, PricingSnapshot, TelemetryConfig } from './types.js';\n\nexport const PRICING_TABLE_VERSION = '2026-08-30';\n\ninterface PricingRow {\n inputPerMillion: number;\n outputPerMillion: number;\n cacheReadPerMillion?: number;\n cacheWritePerMillion?: number;\n}\n\n/** Microdollars-per-million would be more precise; dollars keep the snapshot readable. */\nconst TABLE: Record<string, PricingRow> = {\n 'claude-sonnet-4': {\n inputPerMillion: 3,\n outputPerMillion: 15,\n cacheReadPerMillion: 0.3,\n cacheWritePerMillion: 3.75,\n },\n 'claude-sonnet-4-5': {\n inputPerMillion: 3,\n outputPerMillion: 15,\n cacheReadPerMillion: 0.3,\n cacheWritePerMillion: 3.75,\n },\n 'claude-opus-4': {\n inputPerMillion: 15,\n outputPerMillion: 75,\n cacheReadPerMillion: 1.5,\n cacheWritePerMillion: 18.75,\n },\n 'gpt-5': { inputPerMillion: 1.25, outputPerMillion: 10 },\n 'gpt-5.1': { inputPerMillion: 1.25, outputPerMillion: 10 },\n};\n\n/** Aliases a harness accepts in place of a model id. */\nconst ALIASES: Record<string, string> = {\n sonnet: 'claude-sonnet-4-5',\n opus: 'claude-opus-4',\n};\n\n/**\n * Map a resolved model id onto a table key.\n *\n * What reaches here is whatever the harness reported: a dated snapshot\n * (`claude-sonnet-4-5-20250929`), a vendor-prefixed id\n * (`anthropic/claude-sonnet-4-5`) or a configured alias (`sonnet`). An exact\n * lookup misses all three, and the estimate silently degrades to `unknown`.\n * An override is always honoured under the key the user wrote.\n */\nexport function normalizeModelKey(modelKey: string): string {\n const lower = modelKey.trim().toLowerCase();\n const withoutVendor = lower.slice(lower.lastIndexOf('/') + 1);\n const withoutSnapshot = withoutVendor.replace(/-\\d{8}$/, '').replace(/-latest$/, '');\n return ALIASES[withoutSnapshot] ?? withoutSnapshot;\n}\n\nfunction rowFor(\n modelKey: string,\n overrides: TelemetryConfig['pricing']['overrides'],\n): PricingRow | null {\n const normalized = normalizeModelKey(modelKey);\n const override = overrides[modelKey] ?? overrides[normalized];\n const base = TABLE[modelKey] ?? TABLE[normalized];\n if (override === undefined && base === undefined) return null;\n return {\n inputPerMillion: override?.inputPerMillion ?? base?.inputPerMillion ?? 0,\n outputPerMillion: override?.outputPerMillion ?? base?.outputPerMillion ?? 0,\n cacheReadPerMillion: override?.cacheReadPerMillion ?? base?.cacheReadPerMillion,\n cacheWritePerMillion: override?.cacheWritePerMillion ?? base?.cacheWritePerMillion,\n };\n}\n\nfunction dollars(tokens: number | undefined, perMillion: number | undefined): number {\n if (tokens === undefined || perMillion === undefined) return 0;\n return (tokens * perMillion) / 1_000_000;\n}\n\nexport function resolveCost(options: {\n reportedUsd?: number | null;\n usage: NormalizedUsage | null;\n modelKey: string | null;\n estimate: boolean;\n overrides?: TelemetryConfig['pricing']['overrides'];\n}): CostRecord {\n if (options.reportedUsd !== undefined && options.reportedUsd !== null) {\n return { status: 'reported', amount: options.reportedUsd, currency: 'USD' };\n }\n if (!options.estimate) {\n return { status: 'unknown', reason: 'not_reported' };\n }\n if (options.modelKey === null || options.modelKey === '') {\n return { status: 'unknown', reason: 'unknown_model' };\n }\n const row = rowFor(options.modelKey, options.overrides ?? {});\n if (row === null) {\n return { status: 'unknown', reason: 'unknown_model' };\n }\n if (options.usage === null || options.usage.source === 'unavailable') {\n return { status: 'unknown', reason: 'not_reported' };\n }\n const amount =\n dollars(options.usage.inputTokens, row.inputPerMillion) +\n dollars(options.usage.outputTokens, row.outputPerMillion) +\n dollars(options.usage.cacheReadTokens, row.cacheReadPerMillion) +\n dollars(options.usage.cacheCreationTokens, row.cacheWritePerMillion);\n const pricing: PricingSnapshot = {\n tableVersion: PRICING_TABLE_VERSION,\n modelKey: options.modelKey,\n inputPerMillion: row.inputPerMillion,\n outputPerMillion: row.outputPerMillion,\n capturedAt: isoNow(),\n ...(row.cacheReadPerMillion === undefined\n ? {}\n : { cacheReadPerMillion: row.cacheReadPerMillion }),\n ...(row.cacheWritePerMillion === undefined\n ? {}\n : { cacheWritePerMillion: row.cacheWritePerMillion }),\n };\n return { status: 'estimated', amount, currency: 'USD', pricing };\n}\n\nexport function estimateCost(\n usage: NormalizedUsage,\n modelKey: string,\n overrides: TelemetryConfig['pricing']['overrides'] = {},\n): CostRecord {\n return resolveCost({ usage, modelKey, estimate: true, overrides });\n}\n","import type { FailureKind } from '../resilience/errors.js';\n\nexport const EXECUTION_PURPOSES = [\n 'analyze',\n 'generate',\n 'prd',\n 'plan',\n 'execute',\n 'review',\n 'pr',\n 'pr-review',\n 'verify',\n] as const;\n\nexport type ExecutionPurpose = (typeof EXECUTION_PURPOSES)[number];\n\nexport type ExecutionTrigger = 'initial' | 'retry' | 'fallback' | 'correction' | 'escalation';\n\nexport type ExecutionStatus =\n | 'running'\n | 'completed'\n | 'failed'\n | 'timeout'\n | 'cancelled'\n | 'interrupted';\n\nexport type StopReason =\n | 'completed'\n | 'failed'\n | 'timeout'\n | 'cancelled'\n | 'max_attempts'\n | 'max_cost'\n | 'max_duration';\n\nexport type VerdictStatus = 'passed' | 'failed' | 'unverified';\n\nexport interface NormalizedUsage {\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheCreationTokens?: number;\n reasoningTokens?: number;\n details?: Record<string, number>;\n source: 'provider' | 'unavailable';\n}\n\nexport interface PricingSnapshot {\n tableVersion: string;\n modelKey: string;\n inputPerMillion: number;\n outputPerMillion: number;\n cacheReadPerMillion?: number;\n cacheWritePerMillion?: number;\n capturedAt: string;\n}\n\nexport type CostRecord =\n | { status: 'reported'; amount: number; currency: 'USD' }\n | { status: 'estimated'; amount: number; currency: 'USD'; pricing: PricingSnapshot }\n | {\n status: 'unknown';\n reason: 'not_reported' | 'no_pricing' | 'unknown_model' | 'subscription' | 'zero_rated';\n };\n\nexport interface ExecutionAgent {\n harness: string;\n provider: string | null;\n harnessVersion?: string | null;\n model: {\n requested: string | null;\n resolved: string | null;\n source: 'provider' | 'config' | 'routing' | 'unavailable';\n };\n providerSessionId: string | null;\n}\n\nexport interface ExecutionOwner {\n pid: number;\n host: string;\n}\n\nexport interface ExecutionVerdict {\n status: VerdictStatus;\n level?: string | null;\n independence?: string | null;\n}\n\nexport interface RoutingDecision {\n selected: string | { harness: string; provider: string; model?: string | null; tier?: string };\n actual?: string | { harness: string; provider: string; model?: string | null; tier?: string };\n candidates?: unknown[];\n reasonCodes?: string[];\n [key: string]: unknown;\n}\n\nexport interface ExecutionRecord {\n id: string;\n sessionId: string | null;\n purpose: ExecutionPurpose;\n attempt: number;\n trigger: ExecutionTrigger;\n triggerReason: FailureKind | null;\n agent: ExecutionAgent;\n startedAt: string;\n finishedAt: string | null;\n durationMs: number | null;\n /** Envelope duration when the CLI reports it. */\n cliDurationMs?: number | null;\n /** wallClock − cliDuration: startup the CLI does not see. */\n harnessStartupMs?: number | null;\n /** Envelope `duration_api_ms` when reported. */\n apiDurationMs?: number | null;\n /** Time to first output, when reported. */\n ttftMs?: number | null;\n numTurns?: number | null;\n usage: NormalizedUsage | null;\n cost: CostRecord;\n status: ExecutionStatus;\n failure: {\n kind: FailureKind;\n message: string;\n exitCode: number | null;\n } | null;\n stopReason?: StopReason | null;\n iteration?: number;\n /** Correction cycle active when this invocation started; 0 is the initial pass. */\n correctionCycle?: number;\n storyIds?: string[];\n owner?: ExecutionOwner | null;\n routingDecision?: RoutingDecision | null;\n verdict?: ExecutionVerdict | null;\n}\n\nexport interface CostTotals {\n reported: number;\n estimated: number;\n unknownExecutions: number;\n}\n\nexport interface ExecutionSummary {\n count: number;\n discarded: number;\n byStatus: Partial<Record<ExecutionStatus, number>>;\n usage: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheCreationTokens: number;\n reasoningTokens: number;\n };\n totalCost: CostTotals;\n}\n\nexport interface TelemetryConfig {\n enabled: boolean;\n maxExecutions: number;\n pricing: {\n estimate: boolean;\n overrides: Record<string, Partial<PricingSnapshot>>;\n };\n}\n\nexport const DEFAULT_TELEMETRY_CONFIG: TelemetryConfig = {\n enabled: true,\n maxExecutions: 500,\n pricing: { estimate: false, overrides: {} },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;;;ACElB,IAAM,wBAAwB;AAUrC,IAAM,QAAoC;AAAA,EACxC,mBAAmB;AAAA,IACjB,iBAAiB;AAAA,IACjB,kBAAkB;AAAA,IAClB,qBAAqB;AAAA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