issue-flow 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +1 -1
  2. package/dist/{analyze-UZYJAWAP.js → analyze-XV3K25K3.js} +15 -9
  3. package/dist/analyze-XV3K25K3.js.map +1 -0
  4. package/dist/apply-WUJHDD7A.js +788 -0
  5. package/dist/apply-WUJHDD7A.js.map +1 -0
  6. package/dist/{chunk-2Z7OEZZT.js → chunk-34WNTK3K.js} +14 -9
  7. package/dist/chunk-34WNTK3K.js.map +1 -0
  8. package/dist/{chunk-UUY4PCWW.js → chunk-3BOHTH4V.js} +2 -2
  9. package/dist/chunk-3D4A4B46.js +2 -0
  10. package/dist/{policy-NP4ZAVF6.js → chunk-47VIN33V.js} +82 -112
  11. package/dist/chunk-47VIN33V.js.map +1 -0
  12. package/dist/{chunk-67ZO5ROQ.js → chunk-6N7LZZ5U.js} +19 -13
  13. package/dist/chunk-6N7LZZ5U.js.map +1 -0
  14. package/dist/{chunk-S67Q4I2O.js → chunk-AAY6KM7N.js} +6 -3
  15. package/dist/chunk-AAY6KM7N.js.map +1 -0
  16. package/dist/{chunk-2LNQL4XH.js → chunk-BXCPXRBR.js} +17 -12
  17. package/dist/chunk-BXCPXRBR.js.map +1 -0
  18. package/dist/{chunk-MXTGCD5C.js → chunk-EWDJENFW.js} +30 -9
  19. package/dist/chunk-EWDJENFW.js.map +1 -0
  20. package/dist/{chunk-SP7DD4ID.js → chunk-EY6WMHV2.js} +17 -12
  21. package/dist/chunk-EY6WMHV2.js.map +1 -0
  22. package/dist/{chunk-652DJBCN.js → chunk-GANSDJV7.js} +4 -4
  23. package/dist/{chunk-V5OHFSW4.js → chunk-HC2MT7BX.js} +23 -3
  24. package/dist/chunk-HC2MT7BX.js.map +1 -0
  25. package/dist/chunk-HQYXVIH6.js +110 -0
  26. package/dist/chunk-HQYXVIH6.js.map +1 -0
  27. package/dist/{chunk-UH4KAJBJ.js → chunk-IVHZEYAX.js} +17 -12
  28. package/dist/chunk-IVHZEYAX.js.map +1 -0
  29. package/dist/{chunk-EWA3OGCM.js → chunk-KQ4JQN7T.js} +14 -9
  30. package/dist/chunk-KQ4JQN7T.js.map +1 -0
  31. package/dist/{chunk-VOKNTBOO.js → chunk-LVKQ2AKT.js} +3 -3
  32. package/dist/chunk-OBLVLIUS.js +285 -0
  33. package/dist/chunk-OBLVLIUS.js.map +1 -0
  34. package/dist/chunk-RKTEV6EG.js +246 -0
  35. package/dist/chunk-RKTEV6EG.js.map +1 -0
  36. package/dist/{chunk-VYFKOUUR.js → chunk-VQ5VN7DF.js} +9 -5
  37. package/dist/chunk-VQ5VN7DF.js.map +1 -0
  38. package/dist/cli.js +26 -22
  39. package/dist/cli.js.map +1 -1
  40. package/dist/{config-YCF3HIKR.js → config-4THHOXNN.js} +3 -3
  41. package/dist/execute-5OEKLM5X.js +15 -0
  42. package/dist/{generate-TW6QKSW5.js → generate-TBVTLMOP.js} +101 -13
  43. package/dist/generate-TBVTLMOP.js.map +1 -0
  44. package/dist/init-PRMOTQ7N.js +9 -0
  45. package/dist/plan-Y2BYZD24.js +17 -0
  46. package/dist/policy-XQW5NUIE.js +117 -0
  47. package/dist/policy-XQW5NUIE.js.map +1 -0
  48. package/dist/pr-H6GLOSXF.js +21 -0
  49. package/dist/pr-review-CK5FR6WX.js +17 -0
  50. package/dist/prd-4PWLCGH5.js +17 -0
  51. package/dist/review-QGVAHEZF.js +15 -0
  52. package/dist/review-QGVAHEZF.js.map +1 -0
  53. package/dist/{run-DIBC3YKX.js → run-DBF2VWUN.js} +26 -25
  54. package/dist/{run-DIBC3YKX.js.map → run-DBF2VWUN.js.map} +1 -1
  55. package/dist/{web-O2FVOYZW.js → web-ANQQTTRD.js} +5 -5
  56. package/package.json +1 -1
  57. package/prompts/analyze.md +24 -0
  58. package/prompts/execute.md +29 -1
  59. package/prompts/generate.md +61 -7
  60. package/prompts/plan.md +24 -1
  61. package/prompts/pr-review.md +65 -4
  62. package/prompts/pr.md +37 -3
  63. package/prompts/prd.md +17 -0
  64. package/prompts/review.md +40 -0
  65. package/dist/analyze-UZYJAWAP.js.map +0 -1
  66. package/dist/chunk-2LNQL4XH.js.map +0 -1
  67. package/dist/chunk-2Z7OEZZT.js.map +0 -1
  68. package/dist/chunk-67ZO5ROQ.js.map +0 -1
  69. package/dist/chunk-EWA3OGCM.js.map +0 -1
  70. package/dist/chunk-EZMOEBLU.js +0 -135
  71. package/dist/chunk-EZMOEBLU.js.map +0 -1
  72. package/dist/chunk-MXTGCD5C.js.map +0 -1
  73. package/dist/chunk-PPLIXZI5.js +0 -101
  74. package/dist/chunk-PPLIXZI5.js.map +0 -1
  75. package/dist/chunk-S67Q4I2O.js.map +0 -1
  76. package/dist/chunk-SLHZPB3C.js +0 -50
  77. package/dist/chunk-SLHZPB3C.js.map +0 -1
  78. package/dist/chunk-SP7DD4ID.js.map +0 -1
  79. package/dist/chunk-UH4KAJBJ.js.map +0 -1
  80. package/dist/chunk-V5OHFSW4.js.map +0 -1
  81. package/dist/chunk-VYFKOUUR.js.map +0 -1
  82. package/dist/execute-QYXA225W.js +0 -14
  83. package/dist/generate-TW6QKSW5.js.map +0 -1
  84. package/dist/init-G57UXKDG.js +0 -9
  85. package/dist/plan-YJLGBYBQ.js +0 -16
  86. package/dist/policy-NP4ZAVF6.js.map +0 -1
  87. package/dist/pr-V5H65MRW.js +0 -20
  88. package/dist/pr-review-RCMXKXVP.js +0 -16
  89. package/dist/prd-3XR5KYJS.js +0 -16
  90. package/dist/review-ZZG3CSUO.js +0 -14
  91. /package/dist/{chunk-UUY4PCWW.js.map → chunk-3BOHTH4V.js.map} +0 -0
  92. /package/dist/{config-YCF3HIKR.js.map → chunk-3D4A4B46.js.map} +0 -0
  93. /package/dist/{chunk-652DJBCN.js.map → chunk-GANSDJV7.js.map} +0 -0
  94. /package/dist/{chunk-VOKNTBOO.js.map → chunk-LVKQ2AKT.js.map} +0 -0
  95. /package/dist/{execute-QYXA225W.js.map → config-4THHOXNN.js.map} +0 -0
  96. /package/dist/{init-G57UXKDG.js.map → execute-5OEKLM5X.js.map} +0 -0
  97. /package/dist/{plan-YJLGBYBQ.js.map → init-PRMOTQ7N.js.map} +0 -0
  98. /package/dist/{pr-V5H65MRW.js.map → plan-Y2BYZD24.js.map} +0 -0
  99. /package/dist/{pr-review-RCMXKXVP.js.map → pr-H6GLOSXF.js.map} +0 -0
  100. /package/dist/{prd-3XR5KYJS.js.map → pr-review-CK5FR6WX.js.map} +0 -0
  101. /package/dist/{review-ZZG3CSUO.js.map → prd-4PWLCGH5.js.map} +0 -0
  102. /package/dist/{web-O2FVOYZW.js.map → web-ANQQTTRD.js.map} +0 -0
  103. /package/web/{CLAUDE.md → AGENTS.md} +0 -0
@@ -4,20 +4,20 @@ import {
4
4
  getWebLockFile,
5
5
  readWebLock,
6
6
  removeWebLock
7
- } from "./chunk-652DJBCN.js";
8
- import "./chunk-SLHZPB3C.js";
7
+ } from "./chunk-GANSDJV7.js";
8
+ import "./chunk-HQYXVIH6.js";
9
9
  import {
10
10
  ISSUES_DIR_NAME,
11
11
  PROJECTS_DIR_NAME,
12
12
  getGlobalRoot,
13
13
  loadWebConfig
14
- } from "./chunk-VYFKOUUR.js";
14
+ } from "./chunk-VQ5VN7DF.js";
15
15
  import {
16
16
  printError,
17
17
  printInfo,
18
18
  printWarning,
19
19
  sessionSnapshotSchema
20
- } from "./chunk-V5OHFSW4.js";
20
+ } from "./chunk-HC2MT7BX.js";
21
21
 
22
22
  // src/web/session-directory.ts
23
23
  import { readdir, readFile, stat as statFile } from "fs/promises";
@@ -185,4 +185,4 @@ export {
185
185
  runWebServe,
186
186
  runWebStop
187
187
  };
188
- //# sourceMappingURL=web-O2FVOYZW.js.map
188
+ //# sourceMappingURL=web-ANQQTTRD.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "issue-flow",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "Unified CLI for orchestrating the full issue-flow pipeline via Claude Code Headless",
5
5
  "type": "module",
6
6
  "bin": {
@@ -39,3 +39,27 @@ Save your analysis to __ANALYSIS_PATH__ with this structure:
39
39
  [Key considerations, risks, dependencies]
40
40
 
41
41
  IMPORTANT: You MUST write the analysis to the file path above. Do not just output it.
42
+
43
+ <!-- if:__REPO_POLICY__ -->
44
+ ## Repository policy
45
+
46
+ The repository this runs in declares the conventions below. They were discovered
47
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
48
+ `CODEOWNERS`) and from its configuration.
49
+
50
+ __REPO_POLICY__
51
+
52
+ **This section takes precedence over any convention stated earlier in this
53
+ prompt.** Where the two disagree, follow the repository. Where the repository is
54
+ silent, the defaults above still apply.
55
+
56
+ Paths listed under "Policy documents" are pointers, not content: read them when
57
+ a decision depends on what they say.
58
+
59
+ ### Judging completeness against this repository
60
+
61
+ When the section above lists Issue Templates, the applicable one defines what a
62
+ well-formed issue of this kind is expected to carry. Judge the issue's
63
+ completeness against **its** required fields, not against a generic checklist,
64
+ and name the field that is missing rather than asking for more detail in general.
65
+ <!-- /if -->
@@ -6,7 +6,7 @@ You are an autonomous coding agent working on a software project.
6
6
 
7
7
  1. Read the PRD at `__PRD_FILE__`
8
8
  2. Read the progress log at `__PROGRESS_FILE__` (check Codebase Patterns section first)
9
- 3. Check you're on the correct branch from PRD `branchName`. If not, check it out or create from main.
9
+ 3. Check you're on the correct branch from PRD `branchName`. If not, check it out or create it from `__BASE_BRANCH__`.
10
10
  4. Treat the issue as unresolved if **any** `userStories[].passes` is `false`, **or** if the PRD's top-level `lastReviewFindings` is non-null — that second condition holds even when every story already passes (see "Correction Findings from a Failed Review" below).
11
11
  5. If `lastReviewFindings` is non-null, address it first (see below); otherwise pick the **highest priority** user story where `passes: false`
12
12
  6. Implement that single user story
@@ -134,3 +134,31 @@ If you need to stop for user guidance or another non-transient blocker, record i
134
134
  - Commit frequently
135
135
  - Keep CI green
136
136
  - Read the Codebase Patterns section in `__PROGRESS_FILE__` before starting
137
+
138
+ <!-- if:__REPO_POLICY__ -->
139
+ ## Repository policy
140
+
141
+ The repository this runs in declares the conventions below. They were discovered
142
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
143
+ `CODEOWNERS`) and from its configuration.
144
+
145
+ __REPO_POLICY__
146
+
147
+ **This section takes precedence over any convention stated earlier in this
148
+ prompt.** Where the two disagree, follow the repository. Where the repository is
149
+ silent, the defaults above still apply.
150
+
151
+ Paths listed under "Policy documents" are pointers, not content: read them when
152
+ a decision depends on what they say.
153
+ <!-- /if -->
154
+
155
+ <!-- if:__COMMIT_CONVENTION__ -->
156
+ ## Commit convention
157
+
158
+ This repository declares: __COMMIT_CONVENTION__
159
+
160
+ `<type>` in the commit message above is for you to choose, and it must match the
161
+ **nature of the change** — `fix` for a bug fix, `docs` for documentation, `test`,
162
+ `refactor`, `chore`, `feat` for a new capability. Committing a bug fix as `feat`
163
+ corrupts the changelog and any version bump computed from the history.
164
+ <!-- /if -->
@@ -5,13 +5,27 @@ __USER_PROMPT__
5
5
 
6
6
  Steps:
7
7
  1. Analyze the project's tech stack, architecture, and codebase
8
- 2. Check for duplicates before drafting:
8
+ 2. Decide the **human language** to write in, in this order of priority:
9
+ 1. the language the user's request is written in;
10
+ 2. the predominant language of the repository's existing issue titles
11
+ (`gh issue list --limit 10 --state all --json title --jq '.[].title'`);
12
+ 3. the language of the README;
13
+ 4. the language the user wrote in.
14
+
15
+ Use it for the title and the whole body. A backlog written in two languages
16
+ is harder to search than one written in the "wrong" one.
17
+ 3. Check for duplicates before drafting. This is a **multi-strategy search** —
18
+ one query finds only issues worded the way you happened to word yours:
9
19
  - Local issues: read `__LOCAL_ISSUES_DIR__/*/metadata.json` (the directory may not exist)
10
20
  - Remote issues, only if `gh` is installed and authenticated:
11
- `gh issue list --state open --search "<keywords>"`
12
- If an existing issue already covers the request, still emit the draft, but
13
- say so in the body under a "Possible duplicates" section.
14
- 3. Emit the issue draft in the exact format below
21
+ - 2-3 different keyword combinations drawn from the title and the core problem:
22
+ `gh issue list --search "<keyword1> <keyword2>" --state all --limit 30 --json number,title,state,url`
23
+ - the affected area, when the request names one (auth, database, API…)
24
+ - a label the request maps to, when the repository has a matching one
25
+ Judge a candidate on whether it describes the **same problem**, not on textual
26
+ overlap. If an existing issue already covers the request, still emit the draft,
27
+ but say so in the body under a "Possible duplicates" section, citing the issue.
28
+ 4. Emit the issue draft in the exact format below
15
29
 
16
30
  The issue should:
17
31
  - Have a clear, descriptive title
@@ -27,6 +41,8 @@ with no surrounding commentary:
27
41
  <issue-draft>
28
42
  <title>Concise, descriptive title</title>
29
43
  <labels>label-one, label-two</labels>
44
+ <type>Issue Type, when the repository has them</type>
45
+ <template>path of the Issue Template followed, when there is one</template>
30
46
  <body>
31
47
  Full issue body in markdown, including context and acceptance criteria.
32
48
  </body>
@@ -35,6 +51,44 @@ Full issue body in markdown, including context and acceptance criteria.
35
51
  Rules for the block:
36
52
  - `<title>` and `<body>` are required; an empty one aborts the command
37
53
  - `<labels>` is a comma-separated list; leave it empty when no label applies
38
- - Only suggest labels that already exist in the repository, or that are
39
- conventional (`bug`, `enhancement`, `documentation`)
54
+ - **Only suggest labels that already exist in this repository.** Never invent
55
+ one, and never create one. A label that does not exist is dropped before the
56
+ issue is created, so inventing one silently loses the classification. When the
57
+ section below lists the repository's labels, that list is exhaustive.
58
+ - `<type>` and `<template>` are optional: omit them entirely unless the section
59
+ below shows that this repository has Issue Types or Issue Templates
40
60
  - Write the body as plain markdown — do not wrap it in a code fence
61
+
62
+ <!-- if:__REPO_POLICY__ -->
63
+ ## Repository policy
64
+
65
+ The repository this runs in declares the conventions below. They were discovered
66
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
67
+ `CODEOWNERS`) and from its configuration.
68
+
69
+ __REPO_POLICY__
70
+
71
+ **This section takes precedence over any convention stated earlier in this
72
+ prompt.** Where the two disagree, follow the repository. Where the repository is
73
+ silent, the defaults above still apply.
74
+
75
+ Paths listed under "Policy documents" are pointers, not content: read them when
76
+ a decision depends on what they say.
77
+
78
+ ### Drafting against this repository's conventions
79
+
80
+ - **Issue Templates.** When the section above lists them, pick the one that fits
81
+ the request — by its name and description — and write the body to *its*
82
+ structure, filling every field it marks as required. Report the one you chose
83
+ in `<template>`. The default structure described earlier in this prompt is the
84
+ fallback for a repository with no template, not a floor to add on top of one.
85
+ If two templates fit equally well, say so in the body and pick the more
86
+ specific: choosing a type is the author's call, and a wrong guess is easier to
87
+ correct when it is stated.
88
+ - **Issue Types.** When the section above lists them, choose one and put it in
89
+ `<type>`. A repository with Issue Types has usually *removed* the equivalent
90
+ textual prefix from titles (`[Bug]`, `[Enhancement]`) precisely because the
91
+ information moved into a structured field — do not reintroduce it.
92
+ - **Labels.** Use only the ones listed. Anything else is dropped.
93
+ - **Title.** Follow the convention shown above when there is one.
94
+ <!-- /if -->
package/prompts/plan.md CHANGED
@@ -30,7 +30,7 @@ Create a tasks.json file at __TASKS_PATH__ with this exact structure:
30
30
  "project": "<repo-name>",
31
31
  "issueNumber": __ISSUE_NUMBER__,
32
32
  "issueUrl": "__ISSUE_URL__",
33
- "branchName": "issue/__ISSUE_NUMBER__-<slug>",
33
+ "branchName": "<branch, following __BRANCH_CONVENTION__ with N=__ISSUE_NUMBER__>",
34
34
  "description": "<brief description>",
35
35
  "issueStatus": "pending",
36
36
  "completedAt": null,
@@ -74,3 +74,26 @@ Rules:
74
74
  - The branchName should use a short kebab-case slug derived from the issue title
75
75
 
76
76
  IMPORTANT: You MUST write the tasks.json to the file path above. Do not just output it.
77
+
78
+ <!-- if:__REPO_POLICY__ -->
79
+ ## Repository policy
80
+
81
+ The repository this runs in declares the conventions below. They were discovered
82
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
83
+ `CODEOWNERS`) and from its configuration.
84
+
85
+ __REPO_POLICY__
86
+
87
+ **This section takes precedence over any convention stated earlier in this
88
+ prompt.** Where the two disagree, follow the repository. Where the repository is
89
+ silent, the defaults above still apply.
90
+
91
+ Paths listed under "Policy documents" are pointers, not content: read them when
92
+ a decision depends on what they say.
93
+ <!-- /if -->
94
+
95
+ ## Branch naming
96
+
97
+ `branchName` must follow `__BRANCH_CONVENTION__`, where `{N}` is the issue number
98
+ and `{slug}` a short kebab-case summary of the issue title. A repository that
99
+ declares its own convention above overrides this one.
@@ -25,9 +25,16 @@ Run these, in this order:
25
25
  3. `gh pr diff __PR_NUMBER__ --stat` — size and shape of the change
26
26
  4. `git log --oneline <base>..<head>` — commit history of the branch
27
27
  5. Read __TASKS_PATH__ and __PRD_PATH__ when they exist, to learn what was intended
28
- 6. Read `CLAUDE.md` (root and any nested ones near the changed files) and `README.md`
29
- to learn the project's conventions a review that contradicts the documented
30
- conventions of the repository is a wrong review
28
+ 6. Learn the repository's conventions from **its own** sources, not from prior knowledge
29
+ a review that contradicts the documented conventions of the repository is a
30
+ wrong review. When this prompt ends with a section naming the repository's
31
+ policy documents, read the ones a finding would depend on. Otherwise read
32
+ `AGENTS.md`, `CLAUDE.md` (root and any nested ones near the changed files) and
33
+ `README.md`.
34
+
35
+ Follow a pointer file rather than stopping at it: a `CLAUDE.md` whose entire
36
+ content is "Read and follow the instructions in AGENTS.md" is not a repository
37
+ without conventions, and treating it as one discards everything it forwards to.
31
38
 
32
39
  ## Step 2 — Budget the diff
33
40
 
@@ -79,6 +86,42 @@ of "no problem here", not an axis skipped.
79
86
  - **Commit messages**: do they describe the change accurately, at a useful granularity?
80
87
  - **Simplification**: concrete opportunities to achieve the same result with less code
81
88
 
89
+ <!-- if:__REPO_POLICY__ -->
90
+ - **Repository policy conformance**: does the change respect what this repository
91
+ declares about itself? Check what applies, from the section at the end of this
92
+ prompt: the issue body against its Issue Template, labels against the ones that
93
+ exist, an Issue Type where the repository uses them, the title convention, the
94
+ Pull Request body against the PR template, the **base branch**, and the branch
95
+ and commit conventions. Read the policy documents listed there for rules they
96
+ state as mandatory.
97
+
98
+ **Cite where each rule is written** — the document and its section:
99
+
100
+ > `docs/engineering/ENGINEERING-STANDARDS.md#git-workflow` requires a branch and
101
+ > a Pull Request for ordinary changes; this commit went straight to the default
102
+ > branch.
103
+
104
+ A violation without a citation is an opinion, and the author has no way to check
105
+ whether the reviewer is right.
106
+
107
+ **Calibrate the severity.** Turning every formatting divergence into a blocker
108
+ makes the review noisy, and a noisy review gets ignored:
109
+
110
+ | Situation | Severity |
111
+ |---|---|
112
+ | A rule the documentation states as mandatory | blocker |
113
+ | A required template field left out | blocker |
114
+ | Wrong base branch or wrong target | blocker |
115
+ | Formatting or naming-convention divergence | observation |
116
+ | A document the change made stale | observation, unless the rule is mandatory |
117
+
118
+ When the change touches paths with a `CODEOWNERS` entry, record who owns them.
119
+ Do **not** block on it: GitHub enforces the approval, not this review.
120
+
121
+ Never restate a repository rule as if it were your own standard, and never
122
+ invent one it does not declare.
123
+ <!-- /if -->
124
+
82
125
  Ground every finding in the diff: cite `file:line`. A finding you cannot point at is
83
126
  speculation — leave it out or mark it clearly as a question.
84
127
 
@@ -93,7 +136,8 @@ Pick exactly one recommendation, by these criteria:
93
136
  - `REQUEST_CHANGES` — at least one blocker: a bug or regression in the changed
94
137
  behaviour, a security or data-loss risk, a broken/absent test for a critical path,
95
138
  an unimplemented part of the issue/PRD, or a change that contradicts the project's
96
- documented conventions in a way that must be fixed before merge.
139
+ documented conventions in a way that must be fixed before merge — see the
140
+ severity table on the policy-conformance axis for where that line falls.
97
141
 
98
142
  A missing preference or a matter of style is never a blocker. When you hesitate
99
143
  between two verdicts, pick the more conservative one and explain why in the summary.
@@ -142,3 +186,20 @@ IMPORTANT: You MUST include the `<pr-review-result>` block, with the recommendat
142
186
  written exactly as one of `APPROVE`, `APPROVE_WITH_SUGGESTIONS` or `REQUEST_CHANGES`.
143
187
  An output without it, or with any other value, is a failed review — it is never read
144
188
  as an approval.
189
+
190
+ <!-- if:__REPO_POLICY__ -->
191
+ ## Repository policy
192
+
193
+ The repository this runs in declares the conventions below. They were discovered
194
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
195
+ `CODEOWNERS`) and from its configuration.
196
+
197
+ __REPO_POLICY__
198
+
199
+ **This section takes precedence over any convention stated earlier in this
200
+ prompt.** Where the two disagree, follow the repository. Where the repository is
201
+ silent, the defaults above still apply.
202
+
203
+ Paths listed under "Policy documents" are pointers, not content: read them when
204
+ a decision depends on what they say.
205
+ <!-- /if -->
package/prompts/pr.md CHANGED
@@ -15,8 +15,8 @@ __ISSUE_BODY__
15
15
 
16
16
  Steps:
17
17
  1. Read the task plan from __TASKS_PATH__ if it exists
18
- 2. Review the git log for this branch: git log main..HEAD --oneline
19
- 3. Review the diff: git diff main...HEAD --stat
18
+ 2. Review the git log for this branch: git log __BASE_BRANCH__..HEAD --oneline
19
+ 3. Review the diff: git diff __BASE_BRANCH__...HEAD --stat
20
20
  4. Create a well-structured PR using gh pr create
21
21
 
22
22
  The PR should:
@@ -36,6 +36,40 @@ __ISSUE_CLOSES__
36
36
  __MULTI_ISSUE_CONTEXT__
37
37
 
38
38
  Use this command format:
39
- gh pr create --title "..." --body "..." --base main
39
+ gh pr create --title "..." --body "..." --base __BASE_BRANCH__
40
40
 
41
41
  IMPORTANT: Output the PR URL after creation so it can be parsed.
42
+
43
+ <!-- if:__REPO_POLICY__ -->
44
+ ## Repository policy
45
+
46
+ The repository this runs in declares the conventions below. They were discovered
47
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
48
+ `CODEOWNERS`) and from its configuration.
49
+
50
+ __REPO_POLICY__
51
+
52
+ **This section takes precedence over any convention stated earlier in this
53
+ prompt.** Where the two disagree, follow the repository. Where the repository is
54
+ silent, the defaults above still apply.
55
+
56
+ Paths listed under "Policy documents" are pointers, not content: read them when
57
+ a decision depends on what they say.
58
+ <!-- /if -->
59
+
60
+ <!-- if:__REPO_PR_TEMPLATE__ -->
61
+ ## This repository's Pull Request template
62
+
63
+ Write the body to this template. Keep **every** heading it defines, in its order.
64
+ A section that does not apply gets one line saying why — never delete it:
65
+ automated review and the repository's own checklists key off those headings, so a
66
+ removed section reads as an unanswered one.
67
+
68
+ ```
69
+ __REPO_PR_TEMPLATE__
70
+ ```
71
+
72
+ When the repository has several templates under `.github/PULL_REQUEST_TEMPLATE/`,
73
+ pick the one matching the nature of this issue and say in the body which one you
74
+ picked. If none clearly fits, ask rather than guess.
75
+ <!-- /if -->
package/prompts/prd.md CHANGED
@@ -42,3 +42,20 @@ Save the PRD to __PRD_PATH__ with this structure:
42
42
  [External dependencies or prerequisites]
43
43
 
44
44
  IMPORTANT: You MUST write the PRD to the file path above. Do not just output it.
45
+
46
+ <!-- if:__REPO_POLICY__ -->
47
+ ## Repository policy
48
+
49
+ The repository this runs in declares the conventions below. They were discovered
50
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
51
+ `CODEOWNERS`) and from its configuration.
52
+
53
+ __REPO_POLICY__
54
+
55
+ **This section takes precedence over any convention stated earlier in this
56
+ prompt.** Where the two disagree, follow the repository. Where the repository is
57
+ silent, the defaults above still apply.
58
+
59
+ Paths listed under "Policy documents" are pointers, not content: read them when
60
+ a decision depends on what they say.
61
+ <!-- /if -->
package/prompts/review.md CHANGED
@@ -39,3 +39,43 @@ FINDINGS:
39
39
  IMPORTANT: You MUST include the <review-result> block in your output.
40
40
 
41
41
  IMPORTANT: On FAIL, these FINDINGS are saved verbatim and handed to a correction iteration that has no other context about this review session — it only sees this text. Write each finding as a self-contained, actionable defect report: name the exact file and line, describe what is wrong and why, and state (or strongly imply) what a correct fix looks like. Avoid vague findings like "tests could be improved" — either the codebase fails an acceptance criterion or a regression, or it doesn't.
42
+
43
+ <!-- if:__REPO_POLICY__ -->
44
+ ## Repository policy
45
+
46
+ The repository this runs in declares the conventions below. They were discovered
47
+ from its own files (Issue Templates, labels, `AGENTS.md`, `CONTRIBUTING.md`,
48
+ `CODEOWNERS`) and from its configuration.
49
+
50
+ __REPO_POLICY__
51
+
52
+ **This section takes precedence over any convention stated earlier in this
53
+ prompt.** Where the two disagree, follow the repository. Where the repository is
54
+ silent, the defaults above still apply.
55
+
56
+ Paths listed under "Policy documents" are pointers, not content: read them when
57
+ a decision depends on what they say.
58
+
59
+ ### Repository policy conformance
60
+
61
+ Add this as an explicit axis of the review, alongside the acceptance criteria and
62
+ the regressions:
63
+
64
+ - The branch and the commits against the conventions above.
65
+ - The changes against any rule the policy documents state as **mandatory**. Read
66
+ the documents listed there; follow a pointer file rather than stopping at it —
67
+ a `CLAUDE.md` whose whole content forwards to `AGENTS.md` is not a repository
68
+ without conventions.
69
+ - Paths with a `CODEOWNERS` entry: record who owns them, and never fail on it.
70
+
71
+ **Cite the document and section that defines every rule you invoke.** A violation
72
+ without a citation is an opinion, and the author cannot check it.
73
+
74
+ Only a rule the repository states as **mandatory** — or a required template field
75
+ left out, or a wrong base branch — belongs in FINDINGS. A formatting or naming
76
+ divergence is worth mentioning in the body of your answer, never a FAIL: a review
77
+ that fails on style is a review that gets ignored.
78
+
79
+ Never restate a repository rule as if it were your own standard, and never invent
80
+ one it does not declare.
81
+ <!-- /if -->
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/analyze.ts"],"sourcesContent":["import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { 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 { 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 __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() ?? 300_000,\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 });\n // Before the success check: the tokens were spent either way.\n publishPhaseMetrics('analyze', result.cost, startedAtMs);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,iBAAiB;AAW3C,eAAsB,WAAW,OAAe,eAAgD;AAC9F,QAAM,cAAc,MAAM,QAAQ,MAAM,EAAE;AAC1C,QAAM,QAAQ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AAChD,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/pr.ts"],"sourcesContent":["import { execa } from 'execa';\nimport { runHeadless } from '../core/headless.js';\nimport { runPhaseWithRetry } from '../core/phase-runner.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { isoNow, loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { Issue, IssueSource, ResolvedIssue } from '../issues/types.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport { printError, printSuccess } from '../ui/logger.js';\nimport { isTransientFailure } from '../utils/retry.js';\n\n/**\n * Extract a PR URL from headless output.\n */\nfunction parsePrUrl(output: string): string | null {\n const match = output.match(/(https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+)/);\n return match?.[1] ?? null;\n}\n\n/**\n * The numeric id inside a PR URL, so later phases (`pr-review`) address the\n * Pull Request without querying GitHub again.\n */\nfunction parsePrNumber(url: string): number | null {\n const match = url.match(/\\/pull\\/(\\d+)/);\n return match?.[1] === undefined ? null : Number(match[1]);\n}\n\n/**\n * The `Closes #N` line for the PR body, empty when the Issue has no remote\n * counterpart: GitHub only understands the reference for Issues it hosts, and\n * an invented `#N` would silently point at an unrelated Issue.\n */\nfunction issueClosesLine(issue: Issue, fallbackId: string): string {\n if (issue.remoteRef === null) {\n return '';\n }\n return `Closes #${issue.number ?? fallbackId}`;\n}\n\n/** One Issue of a queue, as the consolidated Pull Request has to describe it. */\nexport interface PrQueueIssue {\n id: string;\n number: number | null;\n title: string;\n /** `null` when the Issue was never read — see {@link issueClosesLines}. */\n url: string | null;\n /** Origin the Issue came from; `github` is what GitHub can close. */\n source: IssueSource;\n}\n\n/**\n * What a multi-issue queue hands to the `pr` phase.\n *\n * Absent for every standalone run, and that absence is what guarantees the\n * single-issue Pull Request is byte-for-byte the one this command has always\n * produced: the extra placeholders resolve to empty strings.\n */\nexport interface PrQueueContext {\n /** Issues of the queue, in the order they were executed. */\n issues: PrQueueIssue[];\n /** Issues discovered but not executed, with the reason. */\n excluded: { id: string; number: number | null; title: string; reason: string }[];\n /** Anything else worth reporting as pending (unresolved review findings). */\n pending: string[];\n}\n\nexport interface RunPrOptions {\n /** Set only when the Pull Request consolidates a queue. */\n queue?: PrQueueContext;\n}\n\n/** `#51` when the Issue has a number, its raw identifier otherwise. */\nfunction issueRef(entry: { id: string; number: number | null }): string {\n return entry.number === null ? entry.id : `#${entry.number}`;\n}\n\n/**\n * Every `Closes #N` line of a consolidated Pull Request, one per line.\n *\n * Issues that GitHub does not host are skipped for the same reason a\n * single-issue Pull Request skips them — it cannot close what it does not\n * host — and a queue that mixes both origins still gets a valid body.\n *\n * The test is the origin and the number, not the URL: an Issue whose read\n * failed during discovery reaches the queue with `url: null`, and it is still\n * executed and still closed by the queue. Filtering on the URL would leave it\n * out of the very body that is supposed to reference it.\n */\nexport function issueClosesLines(issues: readonly PrQueueIssue[]): string {\n return issues\n .filter((entry) => entry.source === 'github' && entry.number !== null)\n .map((entry) => `Closes #${entry.number}`)\n .join('\\n');\n}\n\n/**\n * The extra instructions the prompt receives when the Pull Request covers a\n * whole queue.\n *\n * Returns `''` for a standalone run, which is what keeps `pr.md` rendering\n * exactly as before for the single-issue path — no empty \"Issues implemented\"\n * section, no redundant ordering of a list of one.\n */\nexport function multiIssueContext(queue: PrQueueContext | undefined): string {\n if (queue === undefined || queue.issues.length <= 1) {\n return '';\n }\n\n const order = queue.issues\n .map(\n (entry, index) => `${index + 1}. ${issueRef(entry)}${entry.title ? ` — ${entry.title}` : ''}`,\n )\n .join('\\n');\n\n const pending = [\n ...queue.excluded.map(\n (entry) => `- ${issueRef(entry)}${entry.title ? ` — ${entry.title}` : ''}: ${entry.reason}`,\n ),\n ...queue.pending.map((note) => `- ${note}`),\n ].join('\\n');\n\n return [\n '',\n 'This Pull Request consolidates several issues implemented on this same branch,',\n 'in this execution order:',\n '',\n order,\n '',\n 'The PR body MUST additionally contain:',\n '- an \"Issues implemented\" section listing every issue above, in that order,',\n ' with one line per issue describing what it delivered;',\n '- a \"Pending\" section with the items below, verbatim, plus anything you find',\n ' unfinished while reviewing the diff. Write \"None\" when the list below is',\n ' empty and you find nothing else;',\n '',\n pending === '' ? '(no known pending items)' : pending,\n '',\n 'The commits of this branch are scoped per issue (`feat(issue-N): …`), which is',\n 'how you tell which change belongs to which issue in `git log`.',\n ].join('\\n');\n}\n\nexport async function runPr(\n issue: string,\n resolvedIssue?: ResolvedIssue,\n options: RunPrOptions = {},\n): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n const tasksPath = paths.tasksFile;\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n // Get current branch\n let branchName: string;\n try {\n const proc = await execa('git', ['branch', '--show-current'], { reject: false });\n branchName = proc.stdout?.toString().trim() ?? '';\n if (!branchName) {\n printError('Could not determine current branch');\n return 1;\n }\n } catch {\n printError('Failed to get current branch');\n return 1;\n }\n\n const queue = options.queue;\n const consolidating = queue !== undefined && queue.issues.length > 1;\n\n const template = await loadPrompt('pr');\n const prompt = applyPlaceholders(template, {\n __ISSUE_NUMBER__: issueNumber,\n __BRANCH_NAME__: branchName,\n __TASKS_PATH__: tasksPath,\n __ISSUE_CLOSES__: consolidating\n ? issueClosesLines(queue.issues)\n : issueClosesLine(resolution.resolved.issue, issueNumber),\n __MULTI_ISSUE_CONTEXT__: multiIssueContext(queue),\n ...issuePlaceholders(resolution.resolved),\n });\n\n let headlessOutput = '';\n\n const outcome = await runPhaseWithRetry({\n phase: 'pr',\n attempt: async () => {\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 15,\n timeout: getGlobalTimeout() ?? 300_000,\n // json (not text) so the CLI reports usage: the envelope's `result`\n // field carries the same assistant text parsePrUrl() already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep'],\n addDirs: [paths.issueDir],\n statusMessage: `Creating PR for issue #${issueNumber}...`,\n });\n // One event per attempt; the reducer sums them into the phase total.\n publishPhaseMetrics('pr', result.cost, startedAtMs);\n\n if (!result.success) {\n return {\n ok: false,\n transient: isTransientFailure(1, result.error ?? ''),\n error: `PR creation failed: ${result.error}`,\n };\n }\n\n headlessOutput = result.result;\n return { ok: true };\n },\n });\n\n if (!outcome.ok) {\n printError(outcome.error ?? `PR creation failed for issue #${issueNumber}`);\n return 1;\n }\n\n const prUrl = parsePrUrl(headlessOutput);\n\n // Update pipeline state\n try {\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.prCreated = true;\n const prNumber = prUrl === null ? null : parsePrNumber(prUrl);\n // Without a URL the PR is still assumed created (the phase succeeded), but\n // there is nothing trustworthy to record: an invented number would send\n // `pr-review` at an unrelated Pull Request.\n if (prUrl !== null && prNumber !== null) {\n plan.pullRequest = {\n number: prNumber,\n url: prUrl,\n headBranch: branchName,\n createdAt: isoNow(),\n };\n }\n await saveTaskPlan(tasksPath, plan);\n } catch {\n // tasks.json may not exist\n }\n\n if (prUrl) {\n printSuccess(`PR created: ${prUrl}`);\n } else {\n printSuccess('PR creation completed');\n }\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAgBtB,SAAS,WAAW,QAA+B;AACjD,QAAM,QAAQ,OAAO,MAAM,4CAA4C;AACvE,SAAO,QAAQ,CAAC,KAAK;AACvB;AAMA,SAAS,cAAc,KAA4B;AACjD,QAAM,QAAQ,IAAI,MAAM,eAAe;AACvC,SAAO,QAAQ,CAAC,MAAM,SAAY,OAAO,OAAO,MAAM,CAAC,CAAC;AAC1D;AAOA,SAAS,gBAAgB,OAAc,YAA4B;AACjE,MAAI,MAAM,cAAc,MAAM;AAC5B,WAAO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AAoB,MAAM,OAAO,MAAM,WAAW;AAElD,UAAI,CAAC,OAAO,SAAS;AACnB,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,WAAW,mBAAmB,GAAG,OAAO,SAAS,EAAE;AAAA,UACnD,OAAO,uBAAuB,OAAO,KAAK;AAAA,QAC5C;AAAA,MACF;AAEA,uBAAiB,OAAO;AACxB,aAAO,EAAE,IAAI,KAAK;AAAA,IACpB;AAAA,EACF,CAAC;AAED,MAAI,CAAC,QAAQ,IAAI;AACf,eAAW,QAAQ,SAAS,iCAAiC,WAAW,EAAE;AAC1E,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,WAAW,cAAc;AAGvC,MAAI;AACF,UAAM,OAAO,MAAM,aAAa,SAAS;AACzC,SAAK,SAAS,YAAY;AAC1B,UAAM,WAAW,UAAU,OAAO,OAAO,cAAc,KAAK;AAI5D,QAAI,UAAU,QAAQ,aAAa,MAAM;AACvC,WAAK,cAAc;AAAA,QACjB,QAAQ;AAAA,QACR,KAAK;AAAA,QACL,YAAY;AAAA,QACZ,WAAW,OAAO;AAAA,MACpB;AAAA,IACF;AACA,UAAM,aAAa,WAAW,IAAI;AAAA,EACpC,QAAQ;AAAA,EAER;AAEA,MAAI,OAAO;AACT,iBAAa,eAAe,KAAK,EAAE;AAAA,EACrC,OAAO;AACL,iBAAa,uBAAuB;AAAA,EACtC;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/review.ts"],"sourcesContent":["import { 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 { resolveIssuePaths } from '../storage/resolve.js';\nimport { printError, printSuccess } from '../ui/logger.js';\n\nexport interface ReviewResult {\n status: 'PASS' | 'FAIL';\n findings?: string;\n}\n\n/**\n * Parse the <review-result> block from headless output.\n */\nfunction parseReviewResult(output: string): ReviewResult {\n const match = output.match(/<review-result>([\\s\\S]*?)<\\/review-result>/);\n if (!match) {\n // Try to detect PASS/FAIL from the raw output\n if (/STATUS:\\s*PASS/i.test(output)) {\n return { status: 'PASS' };\n }\n if (/STATUS:\\s*FAIL/i.test(output)) {\n const findingsMatch = output.match(/FINDINGS:([\\s\\S]*?)(?:$|<\\/)/);\n return { status: 'FAIL', findings: findingsMatch?.[1]?.trim() ?? 'Unknown findings' };\n }\n // Default to PASS if no explicit status found and no errors\n return { status: 'PASS' };\n }\n\n const block = match[1];\n if (/STATUS:\\s*PASS/i.test(block)) {\n return { status: 'PASS' };\n }\n\n const findingsMatch = block.match(/FINDINGS:([\\s\\S]*)/);\n return {\n status: 'FAIL',\n findings: findingsMatch?.[1]?.trim() ?? 'Unknown findings',\n };\n}\n\nexport async function runReview(issue: string, resolvedIssue?: ResolvedIssue): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n const tasksPath = paths.tasksFile;\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n const template = await loadPrompt('review');\n const prompt = applyPlaceholders(template, {\n __ISSUE_NUMBER__: issueNumber,\n __TASKS_PATH__: tasksPath,\n ...issuePlaceholders(resolution.resolved),\n });\n\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 25,\n timeout: getGlobalTimeout() ?? 300_000,\n // json (not text) so the CLI reports usage: the envelope's `result` field\n // carries the same assistant text parseReviewResult() already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep'],\n addDirs: [paths.issueDir],\n statusMessage: `Reviewing issue #${issueNumber} resolution...`,\n });\n // Before the success check: the tokens were spent either way. A correction\n // cycle calls runReview() again and the reducer sums both invocations.\n publishPhaseMetrics('review', result.cost, startedAtMs);\n\n if (!result.success) {\n printError(`Review failed: ${result.error}`);\n return 1;\n }\n\n const review = parseReviewResult(result.result);\n\n if (review.status === 'PASS') {\n // Update pipeline state\n try {\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.reviewCompleted = true;\n plan.lastReviewFindings = null;\n await saveTaskPlan(tasksPath, plan);\n } catch {\n // tasks.json may not exist\n }\n\n printSuccess('Review PASSED — implementation meets acceptance criteria');\n return 0;\n }\n\n printError('Review FAILED — issues found:');\n if (review.findings) {\n console.log(review.findings);\n }\n\n // Persist the findings so a correction cycle can act on them: without this,\n // a re-run of execute sees every userStories[].passes already true and\n // exits immediately without attempting any fix (see engine.ts's\n // \"already complete\" guards).\n try {\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.reviewCompleted = false;\n plan.lastReviewFindings = review.findings ?? 'Unknown findings';\n await saveTaskPlan(tasksPath, plan);\n } catch {\n // tasks.json may not exist\n }\n\n return 1;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,kBAAkB,QAA8B;AACvD,QAAM,QAAQ,OAAO,MAAM,4CAA4C;AACvE,MAAI,CAAC,OAAO;AAEV,QAAI,kBAAkB,KAAK,MAAM,GAAG;AAClC,aAAO,EAAE,QAAQ,OAAO;AAAA,IAC1B;AACA,QAAI,kBAAkB,KAAK,MAAM,GAAG;AAClC,YAAMA,iBAAgB,OAAO,MAAM,8BAA8B;AACjE,aAAO,EAAE,QAAQ,QAAQ,UAAUA,iBAAgB,CAAC,GAAG,KAAK,KAAK,mBAAmB;AAAA,IACtF;AAEA,WAAO,EAAE,QAAQ,OAAO;AAAA,EAC1B;AAEA,QAAM,QAAQ,MAAM,CAAC;AACrB,MAAI,kBAAkB,KAAK,KAAK,GAAG;AACjC,WAAO,EAAE,QAAQ,OAAO;AAAA,EAC1B;AAEA,QAAM,gBAAgB,MAAM,MAAM,oBAAoB;AACtD,SAAO;AAA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AO,UAAU;AACnB,YAAQ,IAAI,OAAO,QAAQ;AAAA,EAC7B;AAMA,MAAI;AACF,UAAM,OAAO,MAAM,aAAa,SAAS;AACzC,SAAK,SAAS,kBAAkB;AAChC,SAAK,qBAAqB,OAAO,YAAY;AAC7C,UAAM,aAAa,WAAW,IAAI;AAAA,EACpC,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;","names":["findingsMatch"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/engine.ts","../src/ui/progress.ts","../src/ui/summary.ts","../src/core/executor.ts","../src/commands/execute.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { cp, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { EngineConfig, ResolvedPaths, TaskPlan, UserStory } from '../types.js';\nimport { printError, printInfo, printRetry, printSuccess, printWarning } from '../ui/logger.js';\nimport { printIterationHeader } from '../ui/progress.js';\nimport { printStartupHeader, printSummaryBox } from '../ui/summary.js';\nimport { isTransientFailure, retryDelaySeconds, sleep } from '../utils/retry.js';\nimport { executeClaude } from './executor.js';\nimport { divideUsage } from './metrics.js';\nimport { applyPlaceholders, loadPrompt } from './prompt-resolver.js';\nimport { publishGitState } from './session-git.js';\nimport {\n EXECUTE_PHASE,\n elapsedSecondsSince,\n getPhaseUsageTotals,\n publishIterationMetrics,\n publishStoryMetrics,\n} from './session-metrics.js';\nimport { getSessionPublisher } from './session-publisher.js';\nimport {\n allStoriesPass,\n applyStoryMetrics,\n clearLastError,\n hasPendingCorrection,\n initializeState,\n isoNow,\n loadTaskPlan,\n markIssueCompleted,\n markIssueInProgress,\n saveTaskPlan,\n selectActiveStory,\n setLastError,\n trimErrorMessage,\n} from './state-manager.js';\nimport {\n getOutputCallback,\n getStoryStageCallback,\n getStoryUpdateCallback,\n isVerbose,\n} from './verbose.js';\n\n/**\n * Emit a message through the output callback if available, otherwise console.log.\n * Used for bare console.log calls in engine functions so they route through listr2.\n */\nfunction emitLog(message: string): void {\n const cb = getOutputCallback();\n if (cb) {\n // Skip empty lines in listr2 context — they don't render meaningfully\n if (message) {\n cb(message);\n }\n } else {\n console.log(message);\n }\n}\n\n/**\n * Ids of the stories that flipped from `passes: false` to `passes: true`\n * between the two readings of the plan taken around one execute iteration.\n *\n * Stories already passing before the iteration, and stories that only exist in\n * the newer plan, are never attributed: nothing says this iteration paid for\n * them.\n */\nfunction newlyCompletedStoryIds(before: UserStory[], after: UserStory[]): string[] {\n const wasPassing = new Map(before.map((story) => [story.id, story.passes]));\n return after\n .filter((story) => story.passes && wasPassing.get(story.id) === false)\n .map((story) => story.id);\n}\n\n/**\n * Commit message formats handed to the execute prompt.\n *\n * Without a scope they are byte-for-byte what the prompt has always spelled\n * out, so a single-issue run produces the same history it always did. With one\n * — the only case being several issues sharing a branch — the issue becomes a\n * conventional-commit scope, which is what makes `git log` on the shared branch\n * readable per issue.\n */\nexport function commitPlaceholders(scope?: string): Record<string, string> {\n const suffix = scope === undefined || scope === '' ? '' : `(${scope})`;\n return {\n __COMMIT_MESSAGE__: `feat${suffix}: [Story ID] - [Story Title]`,\n __FIX_COMMIT_MESSAGE__: `fix${suffix}: address review findings`,\n };\n}\n\n/**\n * Initialize the progress file if it doesn't exist.\n */\nasync function ensureProgressFile(progressFile: string): Promise<void> {\n if (!existsSync(progressFile)) {\n const content = `# Issue Flow Progress Log\\nStarted: ${new Date().toString()}\\n---\\n`;\n await writeFile(progressFile, content, 'utf-8');\n }\n}\n\n/**\n * Archive previous run artifacts if the branch has changed.\n */\nasync function archiveIfBranchChanged(plan: TaskPlan, paths: ResolvedPaths): Promise<void> {\n const { lastBranchFile, archiveDir, prdFile, progressFile } = paths;\n\n if (!existsSync(lastBranchFile)) {\n return;\n }\n\n const currentBranch = plan.branchName ?? '';\n let lastBranch = '';\n\n try {\n lastBranch = (await readFile(lastBranchFile, 'utf-8')).trim();\n } catch {\n return;\n }\n\n if (currentBranch && lastBranch && currentBranch !== lastBranch) {\n const dateStr = new Date().toISOString().split('T')[0];\n const folderName = lastBranch.replace(/^issue\\//, '').replace(/[<>:\"|?*\\\\]/g, '_');\n const archiveFolder = join(archiveDir, `${dateStr}-${folderName}`);\n\n printInfo(`Archiving previous run: ${lastBranch}`);\n await mkdir(archiveFolder, { recursive: true });\n\n if (existsSync(prdFile)) {\n await cp(prdFile, join(archiveFolder, 'tasks.json'));\n }\n if (existsSync(progressFile)) {\n await cp(progressFile, join(archiveFolder, 'progress.txt'));\n }\n\n printInfo(` Archived to: ${archiveFolder}`);\n\n // Reset progress file for new run\n await writeFile(\n progressFile,\n `# Issue Flow Progress Log\\nStarted: ${new Date().toString()}\\n---\\n`,\n 'utf-8',\n );\n }\n}\n\n/**\n * Write the current branch to the last-branch tracking file.\n */\nasync function trackBranch(plan: TaskPlan, lastBranchFile: string): Promise<void> {\n const branch = plan.branchName ?? '';\n if (branch) {\n await writeFile(lastBranchFile, `${branch}\\n`, 'utf-8');\n }\n}\n\n/**\n * Run the issue-flow engine loop.\n *\n * This replicates the full execution flow:\n * 1. Load and initialize task plan state\n * 2. Check for early exit (already complete)\n * 3. Archive previous run if branch changed\n * 4. Resolve prompt\n * 5. Main loop: iterate, execute Claude, handle results\n * 6. Print summary\n */\nexport async function runEngine(config: EngineConfig, paths: ResolvedPaths): Promise<number> {\n // Load task plan\n if (!existsSync(paths.prdFile)) {\n printError(`PRD file not found at ${paths.prdFile}`);\n if (config.issueNumber) {\n emitLog(`Have you run the resolve-issue skill for issue #${config.issueNumber} first?`);\n }\n return 1;\n }\n\n let plan = await loadTaskPlan(paths.prdFile);\n plan = initializeState(plan);\n await saveTaskPlan(paths.prdFile, plan);\n\n // Check if already completed. A pending correction (a failed review whose\n // findings haven't been addressed yet) always overrides this, even though\n // every userStories[].passes is already true — otherwise a correction\n // cycle's re-run of execute would exit here without ever looking at what\n // the review found.\n if (plan.issueStatus === 'completed' && allStoriesPass(plan) && !hasPendingCorrection(plan)) {\n emitLog(`Issue already marked complete in ${paths.prdFile}`);\n return 0;\n }\n\n // Warn if marked complete but stories still pending\n if (plan.issueStatus === 'completed' && !allStoriesPass(plan)) {\n printWarning(\n 'Issue marked completed but some stories are still pending. Resetting to in_progress.',\n );\n plan = markIssueInProgress(plan);\n plan = setLastError(\n plan,\n 'invalid_completion_state',\n 'tasks.json claimed the issue was completed before every story had passes=true.',\n );\n await saveTaskPlan(paths.prdFile, plan);\n }\n\n // Check if all stories already pass\n if (allStoriesPass(plan) && !hasPendingCorrection(plan)) {\n emitLog('All user stories already pass. Marking issue as completed.');\n plan = markIssueCompleted(plan);\n await saveTaskPlan(paths.prdFile, plan);\n return 0;\n }\n\n // Archive previous run if branch changed\n await archiveIfBranchChanged(plan, paths);\n\n // Track current branch\n await trackBranch(plan, paths.lastBranchFile);\n\n // Initialize progress file\n await ensureProgressFile(paths.progressFile);\n\n // Load prompt template\n const promptTemplate = await loadPrompt('execute');\n\n // Print startup header\n printStartupHeader(config, plan);\n\n const startTime = Date.now();\n let i = 0;\n let retryCount = 0;\n let totalRetryCount = 0;\n\n // Main loop\n while (true) {\n // Check iteration limit\n if (config.maxIterations !== undefined && i >= config.maxIterations) {\n break;\n }\n\n i++;\n\n // Re-read plan to get latest state\n plan = await loadTaskPlan(paths.prdFile);\n // Baseline for story attribution: whatever was still pending before the\n // agent ran is what this iteration can claim credit for.\n const storiesBeforeIteration = plan.userStories;\n\n // Highest-priority story with passes: false — the same rule\n // prompts/execute.md gives the agent. Computed once, here, and shared by\n // the published event and the verbose terminal header, so every surface\n // agrees on who is active instead of each deriving its own heuristic.\n const activeStoryId = selectActiveStory(plan.userStories)?.id;\n getSessionPublisher().publish({\n type: 'iteration:start',\n at: isoNow(),\n iteration: i,\n storyId: activeStoryId,\n });\n getStoryStageCallback()?.(activeStoryId);\n\n if (isVerbose()) {\n printIterationHeader(i, config.maxIterations, plan.userStories, activeStoryId);\n }\n\n // Apply placeholders to prompt\n const prompt = applyPlaceholders(promptTemplate, {\n __PRD_FILE__: paths.prdFile,\n __PROGRESS_FILE__: paths.progressFile,\n ...commitPlaceholders(config.commitScope),\n });\n\n const iterationStartedAt = isoNow();\n plan = markIssueInProgress(plan, iterationStartedAt);\n await saveTaskPlan(paths.prdFile, plan);\n\n // Execute Claude\n const iterationStartedAtMs = Date.now();\n const result = await executeClaude(prompt);\n const iterationSeconds = elapsedSecondsSince(iterationStartedAtMs);\n\n if (result.exitCode !== 0) {\n // A failed iteration still burned tokens: report them on the execute\n // phase, with no attribution to any story.\n publishIterationMetrics(i, result.cost, iterationSeconds);\n\n const errorMessage = trimErrorMessage(result.output);\n\n if (isTransientFailure(result.exitCode, result.output)) {\n retryCount++;\n totalRetryCount++;\n plan = await loadTaskPlan(paths.prdFile);\n plan = setLastError(plan, 'transient_claude_failure', errorMessage);\n await saveTaskPlan(paths.prdFile, plan);\n\n if (!config.retryForever && retryCount > config.retryLimit) {\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n plan = await loadTaskPlan(paths.prdFile);\n printSummaryBox(\n 'failed',\n i,\n totalRetryCount,\n elapsed,\n plan,\n `Exceeded retry limit (${config.retryLimit}) on transient errors`,\n getPhaseUsageTotals(EXECUTE_PHASE),\n );\n return result.exitCode;\n }\n\n const delaySeconds = retryDelaySeconds(\n retryCount,\n config.backoffBaseSeconds,\n config.backoffMaxSeconds,\n );\n getSessionPublisher().publish({\n type: 'retry',\n at: isoNow(),\n attempt: retryCount,\n delaySeconds,\n reason: 'transient_claude_failure',\n });\n\n if (isVerbose()) {\n emitLog('');\n }\n printRetry(\n `Transient Claude failure on iteration ${i} (attempt ${retryCount}). Retrying in ${delaySeconds}s.`,\n );\n\n // Stay within current iteration budget\n i--;\n await sleep(delaySeconds);\n continue;\n }\n\n // Fatal failure\n plan = await loadTaskPlan(paths.prdFile);\n plan = setLastError(plan, 'fatal_claude_failure', errorMessage);\n await saveTaskPlan(paths.prdFile, plan);\n\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n printSummaryBox(\n 'failed',\n i,\n totalRetryCount,\n elapsed,\n plan,\n `Claude CLI failed with exit code ${result.exitCode}`,\n getPhaseUsageTotals(EXECUTE_PHASE),\n );\n return result.exitCode;\n }\n\n // Success — reset retry counter\n retryCount = 0;\n plan = await loadTaskPlan(paths.prdFile);\n plan = clearLastError(plan, iterationStartedAt);\n await saveTaskPlan(paths.prdFile, plan);\n\n // Notify story progress listeners (e.g., listr2 subtasks)\n const storyUpdateCb = getStoryUpdateCallback();\n if (storyUpdateCb) {\n storyUpdateCb(plan.userStories);\n }\n getSessionPublisher().publish({\n type: 'stories:update',\n at: isoNow(),\n stories: plan.userStories,\n });\n\n // Story attribution — an approximation by construction: the CLI reports a\n // single usage for the whole iteration, so the stories that flipped to\n // passing in it split tokens, cost and duration evenly. With none, nothing\n // is attributed and the whole cost stays on the execute phase. Published\n // after stories:update, which rebuilds the stories array.\n const completedStoryIds = newlyCompletedStoryIds(storiesBeforeIteration, plan.userStories);\n if (completedStoryIds.length > 0) {\n const storyShare = divideUsage(result.cost, completedStoryIds.length);\n const storySeconds = Math.round(iterationSeconds / completedStoryIds.length);\n for (const storyId of completedStoryIds) {\n publishStoryMetrics(storyId, storyShare, storySeconds);\n }\n\n // The same shares also land on tasks.json, so the numbers outlive the\n // session and are readable with web monitoring off. Persisting them is\n // observational: a write failure must never change the iteration's\n // outcome, so the plan in memory only advances when the write succeeded.\n const planWithMetrics = applyStoryMetrics(plan, completedStoryIds, storyShare, storySeconds);\n try {\n await saveTaskPlan(paths.prdFile, planWithMetrics);\n plan = planWithMetrics;\n } catch {\n // Metrics are a nice-to-have; the iteration succeeded regardless.\n }\n }\n\n getSessionPublisher().publish({ type: 'iteration:end', at: isoNow(), iteration: i });\n publishIterationMetrics(i, result.cost, iterationSeconds);\n // Low-frequency commit/PR enrichment: iteration end is one of the only\n // two sanctioned points (the other is phase boundaries in run.ts).\n await publishGitState(getSessionPublisher());\n\n // Check for completion signal\n if (result.output.includes('<promise>COMPLETE</promise>')) {\n plan = await loadTaskPlan(paths.prdFile);\n if (allStoriesPass(plan) && !hasPendingCorrection(plan)) {\n plan = markIssueCompleted(plan);\n await saveTaskPlan(paths.prdFile, plan);\n\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n printSummaryBox(\n 'success',\n i,\n totalRetryCount,\n elapsed,\n plan,\n undefined,\n getPhaseUsageTotals(EXECUTE_PHASE),\n );\n return 0;\n }\n\n plan = setLastError(\n plan,\n 'invalid_completion_signal',\n hasPendingCorrection(plan)\n ? 'Claude returned <promise>COMPLETE</promise> while lastReviewFindings was still set.'\n : 'Claude returned <promise>COMPLETE</promise> before every story had passes=true.',\n );\n await saveTaskPlan(paths.prdFile, plan);\n\n emitLog('');\n printWarning(\n hasPendingCorrection(plan)\n ? 'Claude returned a completion signal, but lastReviewFindings is still set. Ignoring completion and continuing.'\n : 'Claude returned a completion signal, but tasks.json still has pending stories. Ignoring completion and continuing.',\n );\n }\n\n if (isVerbose()) {\n printSuccess(`Iteration ${i} complete. Continuing...`);\n }\n await sleep(2);\n }\n\n // Reached max iterations\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n plan = await loadTaskPlan(paths.prdFile);\n printSummaryBox(\n 'incomplete',\n config.maxIterations ?? i,\n totalRetryCount,\n elapsed,\n plan,\n 'Reached max iterations without completing all tasks.',\n getPhaseUsageTotals(EXECUTE_PHASE),\n );\n return 1;\n}\n","import chalk from 'chalk';\nimport { getOutputCallback } from '../core/verbose.js';\nimport type { UserStory } from '../types.js';\nimport { getIcons, useColor, useUnicode } from './logger.js';\n\n/**\n * Print a visual progress bar showing passed/total stories.\n */\nexport function printProgressBar(passed: number, total: number): string {\n const barWidth = 20;\n let pct = 0;\n let filled = 0;\n\n if (total > 0) {\n pct = Math.floor((passed * 100) / total);\n filled = Math.floor((passed * barWidth) / total);\n }\n\n const empty = barWidth - filled;\n const fillChar = useUnicode() ? '\\u2588' : '#';\n const emptyChar = useUnicode() ? '\\u2591' : '-';\n\n const bar = fillChar.repeat(filled) + emptyChar.repeat(empty);\n const text = `${passed}/${total} (${pct}%)`;\n\n if (useColor()) {\n return `${chalk.green(bar)} ${text}`;\n }\n return `${bar} ${text}`;\n}\n\n/**\n * Print the iteration header showing story statuses and progress bar.\n *\n * When a global output callback is set (e.g., inside a listr2 task),\n * output is routed through it instead of console.log.\n *\n * `activeStoryId`, when provided, identifies the story the engine is\n * actually about to work on this iteration (the same id published on\n * `iteration:start` \\u2014 see `core/state-manager.ts`'s `selectActiveStory`),\n * so the header agrees with the session snapshot instead of guessing.\n * Omitted, it falls back to the previous heuristic (\"first non-passing story\n * in array order\"), which existing callers that cannot supply the real id\n * keep relying on.\n */\nexport function printIterationHeader(\n iteration: number,\n maxIter: number | undefined,\n stories: UserStory[],\n activeStoryId?: string,\n): void {\n const icons = getIcons();\n const colored = useColor();\n const cb = getOutputCallback();\n\n const iterLabel = maxIter ? `Iteration ${iteration} of ${maxIter}` : `Iteration ${iteration}`;\n\n const total = stories.length;\n const passed = stories.filter((s) => s.passes).length;\n\n const lines: string[] = [];\n\n if (colored) {\n lines.push(chalk.blue(`\\u2501\\u2501\\u2501 ${icons.start} ${iterLabel} \\u2501\\u2501\\u2501`));\n } else {\n lines.push(`--- ${icons.start} ${iterLabel} ---`);\n }\n\n // Display each story status\n let foundFirstPending = false;\n for (const story of stories) {\n let icon: string;\n let colorFn: (s: string) => string;\n const isActive =\n activeStoryId !== undefined\n ? story.id === activeStoryId\n : !story.passes && !foundFirstPending;\n\n if (story.passes) {\n icon = icons.success;\n colorFn = colored ? chalk.green : (s: string) => s;\n } else if (isActive) {\n icon = icons.pending;\n colorFn = colored ? chalk.yellow : (s: string) => s;\n foundFirstPending = true;\n } else {\n // Not yet reached\n icon = icons.notReached;\n colorFn = colored ? chalk.gray : (s: string) => s;\n }\n\n lines.push(colorFn(` ${icon} ${story.id}: ${story.title}`));\n }\n\n lines.push(` ${printProgressBar(passed, total)}`);\n\n if (cb) {\n // Send as single output to listr2 task context\n cb(lines.join('\\n'));\n } else {\n console.log('');\n for (const line of lines) {\n console.log(line);\n }\n console.log('');\n }\n}\n","import chalk from 'chalk';\nimport { type ClaudeUsage, formatTokens } from '../core/metrics.js';\nimport type { EngineConfig, PrReviewRecommendation, TaskPlan } from '../types.js';\nimport {\n formatDuration,\n getIcons,\n getTermWidth,\n printSuccess,\n printWarning,\n useColor,\n useUnicode,\n} from './logger.js';\n\n/**\n * Truncate or pad a string to fit within a given width.\n */\nfunction fitLine(text: string, width: number): string {\n if (text.length > width) {\n return text.substring(0, width);\n }\n return text.padEnd(width);\n}\n\n/**\n * Print a box with border characters around content lines.\n * Lines equal to \"---\" render as separator rows.\n */\nexport function printBox(lines: string[]): void {\n const colored = useColor();\n const unicode = useUnicode();\n const termWidth = getTermWidth();\n\n // Find max content width\n let maxContentWidth = 0;\n for (const line of lines) {\n if (line !== '---' && line.length > maxContentWidth) {\n maxContentWidth = line.length;\n }\n }\n\n // Cap to terminal width (border + padding = 4 chars)\n const available = termWidth - 4;\n if (maxContentWidth > available) {\n maxContentWidth = available;\n }\n if (maxContentWidth < 20) {\n maxContentWidth = 20;\n }\n\n // Box drawing characters\n const tl = unicode ? '\\u256D' : '+';\n const tr = unicode ? '\\u256E' : '+';\n const bl = unicode ? '\\u2570' : '+';\n const br = unicode ? '\\u256F' : '+';\n const h = unicode ? '\\u2500' : '-';\n const v = unicode ? '\\u2502' : '|';\n const sepL = unicode ? '\\u251C' : '+';\n const sepR = unicode ? '\\u2524' : '+';\n\n const hrule = h.repeat(maxContentWidth + 2);\n\n const blue = colored ? chalk.blue : (s: string) => s;\n const _reset = (s: string) => s;\n\n // Top border\n console.log(blue(`${tl}${hrule}${tr}`));\n\n // Content lines\n for (const line of lines) {\n if (line === '---') {\n console.log(blue(`${sepL}${hrule}${sepR}`));\n } else {\n const fitted = fitLine(line, maxContentWidth);\n console.log(`${blue(v)} ${fitted} ${blue(v)}`);\n }\n }\n\n // Bottom border\n console.log(blue(`${bl}${hrule}${br}`));\n}\n\n/**\n * Print the startup header box showing engine configuration.\n */\nexport function printStartupHeader(config: EngineConfig, plan: TaskPlan): void {\n const icons = getIcons();\n\n const storiesTotal = plan.userStories.length;\n const storiesPassing = plan.userStories.filter((s) => s.passes).length;\n const branchName = plan.branchName ?? 'N/A';\n\n const issueLabel = config.issueNumber ? `Issue #${config.issueNumber}` : 'Standalone mode';\n\n const maxIterLabel =\n config.maxIterations !== undefined ? String(config.maxIterations) : 'unlimited';\n\n const retryLabel = config.retryForever\n ? 'unlimited retries'\n : `${config.retryLimit} consecutive retries`;\n\n printBox([\n `${icons.start} Issue Flow`,\n '---',\n `Issue: ${issueLabel}`,\n `Branch: ${branchName}`,\n `Stories: ${storiesPassing}/${storiesTotal} passing`,\n `Iterations: ${maxIterLabel}`,\n `Retries: ${retryLabel}`,\n ]);\n}\n\n// Re-export formatDuration from logger to maintain backwards compatibility\nexport { formatDuration } from './logger.js';\n\n/**\n * Print the final summary box.\n */\nexport function printSummaryBox(\n status: 'success' | 'incomplete' | 'failed',\n iterations: number,\n totalRetries: number,\n elapsedSeconds: number,\n plan: TaskPlan,\n extraInfo?: string,\n /**\n * Tokens and cost spent by this run, already resolved by the caller (the\n * process-owned counters in `core/session-metrics.ts`, never the session\n * snapshot — that one is empty whenever web monitoring is off). Omitted or\n * empty means \"the CLI reported nothing\", and the line is skipped entirely.\n */\n usage?: ClaudeUsage | null,\n): void {\n const icons = getIcons();\n\n const storiesTotal = plan.userStories.length;\n const storiesPassing = plan.userStories.filter((s) => s.passes).length;\n const duration = formatDuration(elapsedSeconds);\n\n let statusIcon: string;\n let statusLabel: string;\n\n switch (status) {\n case 'success':\n statusIcon = icons.success;\n statusLabel = 'Completed';\n break;\n case 'incomplete':\n statusIcon = icons.warn;\n statusLabel = 'Incomplete';\n break;\n case 'failed':\n statusIcon = icons.fail;\n statusLabel = 'Failed';\n break;\n }\n\n const boxLines = [\n `${icons.end} Issue Flow Summary`,\n '---',\n `Status: ${statusIcon} ${statusLabel}`,\n `Stories: ${storiesPassing}/${storiesTotal} passing`,\n `Iterations: ${iterations}`,\n `Duration: ${duration}`,\n ];\n\n const tokens = formatTokens(usage);\n if (tokens !== '') {\n boxLines.push(`Tokens: ${tokens}`);\n }\n\n boxLines.push(`Retries: ${totalRetries}`);\n\n if (extraInfo) {\n boxLines.push('---');\n boxLines.push(extraInfo);\n }\n\n console.log('');\n printBox(boxLines);\n}\n\n/**\n * What the optional `pr-review` phase produced, as far as the summary cares.\n * `null` in `recommendation` means the verdict could not be recovered from\n * disk — the exit code still told us whether changes were requested.\n */\nexport interface RunSummaryPrReview {\n requestedChanges: boolean;\n recommendation: PrReviewRecommendation | null;\n reportPath: string | null;\n}\n\n/**\n * Everything the final `run` summary prints, already resolved by the caller.\n */\nexport interface RunSummaryInfo {\n issueNumber: string;\n /** 'unknown' when the branch could not be detected. */\n branchName: string;\n /** Pipelines run with --no-branch open no Pull Request. */\n noBranch: boolean;\n storyCount: number;\n elapsedSeconds: number;\n /** 'unknown' when no Pull Request could be resolved. */\n prUrl: string;\n /** Only set when the pr-review phase actually ran. */\n prReview?: RunSummaryPrReview | null;\n /**\n * Tokens and cost of the whole pipeline, from the process-owned counters in\n * `core/session-metrics.ts`. Absent or empty omits the line.\n */\n usage?: ClaudeUsage | null;\n}\n\n/**\n * Detail lines of the final `run` summary (everything below the headline).\n *\n * Kept separate from the printing so the shape is testable without capturing\n * stdout. Without `prReview` the lines are exactly the ones the pipeline has\n * always printed.\n */\nexport function buildRunSummaryLines(info: RunSummaryInfo): string[] {\n const lines = [\n ` Branch: ${info.branchName}${info.noBranch ? ' (current)' : ''}`,\n ` Stories: ${info.storyCount}`,\n ` Duration: ${formatDuration(info.elapsedSeconds)}`,\n ];\n\n // Skipped altogether when the CLI reported nothing — better no line than\n // \"0 in / 0 out\" or \"~$NaN\".\n const tokens = formatTokens(info.usage);\n if (tokens !== '') {\n lines.push(` Tokens: ${tokens}`);\n }\n\n if (!info.noBranch) {\n lines.push(` PR: ${info.prUrl}`);\n }\n\n const review = info.prReview;\n if (review) {\n // The exit code is the source of truth for the verdict, so a report whose\n // recommendation could not be read still reports REQUEST_CHANGES.\n const verdict =\n review.recommendation ?? (review.requestedChanges ? 'REQUEST_CHANGES' : 'unknown');\n lines.push(` Review: ${verdict}`);\n if (review.reportPath !== null) {\n lines.push(` Report: ${review.reportPath}`);\n }\n }\n\n return lines;\n}\n\n/** One issue of a multi-issue queue, as the consolidated summary reports it. */\nexport interface QueueIssueSummary {\n id: string;\n title: string;\n storyCount: number;\n elapsedSeconds: number;\n /** Tokens and cost of this issue alone — never of the whole queue. */\n usage?: ClaudeUsage | null;\n}\n\n/** Everything the consolidated summary of a queue prints. */\nexport interface QueueSummaryInfo {\n /** Identifier of the queue, i.e. of its primary issue. */\n queueId: string;\n /** Branch every issue shared, `null` when the queue ran with --no-branch. */\n branchName: string | null;\n issues: QueueIssueSummary[];\n /** Issues discovered but left out of the run. */\n excluded: { id: string; title: string }[];\n elapsedSeconds: number;\n /** The single consolidated Pull Request, `null` when none was opened. */\n prUrl: string | null;\n /** Tokens and cost of the whole queue. */\n usage?: ClaudeUsage | null;\n /** Verdict of the pr-review phase, when the queue ran it. */\n prReview?: RunSummaryPrReview | null;\n}\n\n/**\n * Detail lines of a queue's final summary.\n *\n * Per-issue lines carry their own duration and cost, which is the visible half\n * of the per-issue metric scoping: what one issue spent is never folded into\n * another's line.\n */\nexport function buildQueueSummaryLines(info: QueueSummaryInfo): string[] {\n const lines: string[] = [];\n\n lines.push(` Branch: ${info.branchName ?? 'current'}`);\n lines.push(` Issues: ${info.issues.length}`);\n\n for (const issue of info.issues) {\n const tokens = formatTokens(issue.usage);\n const title = issue.title === '' ? '' : ` ${issue.title}`;\n lines.push(\n ` #${issue.id}${title} — ${issue.storyCount} stories, ${formatDuration(issue.elapsedSeconds)}` +\n (tokens === '' ? '' : `, ${tokens}`),\n );\n }\n\n lines.push(` Duration: ${formatDuration(info.elapsedSeconds)}`);\n\n const tokens = formatTokens(info.usage);\n if (tokens !== '') {\n lines.push(` Tokens: ${tokens}`);\n }\n if (info.prUrl !== null) {\n lines.push(` PR: ${info.prUrl}`);\n }\n if (info.excluded.length > 0) {\n lines.push(` Skipped: ${info.excluded.map((entry) => `#${entry.id}`).join(', ')}`);\n }\n\n const review = info.prReview;\n if (review) {\n lines.push(\n ` Review: ${review.recommendation ?? (review.requestedChanges ? 'REQUEST_CHANGES' : 'unknown')}`,\n );\n if (review.reportPath !== null) {\n lines.push(` Report: ${review.reportPath}`);\n }\n }\n\n return lines;\n}\n\n/** Print the consolidated summary of a multi-issue queue. */\nexport function printQueueSummary(info: QueueSummaryInfo): void {\n console.log('');\n if (info.prReview?.requestedChanges === true) {\n printWarning(`Queue finished for issue #${info.queueId}, but the PR review requested changes.`);\n } else {\n printSuccess(`Queue complete for issue #${info.queueId} (${info.issues.length} issues)!`);\n }\n for (const line of buildQueueSummaryLines(info)) {\n console.log(line);\n }\n}\n\n/**\n * Print the final summary of a `run` (the flat listing, not the box used by\n * the execute engine).\n */\nexport function printRunSummary(info: RunSummaryInfo): void {\n console.log('');\n if (info.prReview?.requestedChanges) {\n printWarning(\n `Pipeline finished for issue #${info.issueNumber}, but the PR review requested changes.`,\n );\n } else {\n printSuccess(`Pipeline complete for issue #${info.issueNumber}!`);\n }\n for (const line of buildRunSummaryLines(info)) {\n console.log(line);\n }\n}\n","import { execa } from 'execa';\nimport type { ClaudeResult } from '../types.js';\nimport { type ClaudeUsage, parseUsage } from './metrics.js';\nimport { getOutputCallback } from './verbose.js';\n\n/**\n * Execute Claude CLI with a prompt piped to stdin.\n *\n * Runs: echo $PROMPT | claude --dangerously-skip-permissions --print --output-format json\n *\n * The JSON envelope is requested purely for observability: it carries the token\n * and cost metrics of the execute phase. Every flow decision keeps working off\n * the same values as before — `exitCode` and the assistant's text — so the\n * envelope is unwrapped here and never leaks to callers. Whenever stdout is not\n * parseable JSON (or the CLI failed), the behaviour falls back exactly to the\n * previous combined stdout+stderr text with no metrics.\n */\nexport async function executeClaude(prompt: string): Promise<ClaudeResult> {\n const result = await execa(\n 'claude',\n ['--dangerously-skip-permissions', '--print', '--output-format', 'json'],\n {\n input: prompt,\n reject: false,\n timeout: 0, // No timeout — let the engine handle iteration limits\n stripFinalNewline: false,\n },\n );\n\n // Combine stdout and stderr to match Bash's 2>&1 behavior\n const stdout = result.stdout?.toString() ?? '';\n const stderr = result.stderr?.toString() ?? '';\n const exitCode = result.exitCode ?? 1;\n\n let output = stdout + (stderr ? `\\n${stderr}` : '');\n let cost: ClaudeUsage | null = null;\n\n // Only unwrap on success: a failing CLI may print diagnostics on stderr that\n // trimErrorMessage()/isTransientFailure() need to see verbatim.\n if (exitCode === 0) {\n try {\n const parsed: unknown = JSON.parse(stdout);\n const text = (parsed as { result?: unknown } | null)?.result;\n // Non-string `result` would break the callers that treat output as text.\n output = typeof text === 'string' ? text : stdout;\n cost = parseUsage(parsed);\n } catch {\n // Not JSON — keep the raw combined output and report no metrics.\n }\n }\n\n // Forward output through the global callback (listr2 renderer) when active\n const onOutput = getOutputCallback();\n if (onOutput) {\n const trimmed = output.trim();\n if (trimmed) {\n onOutput(trimmed);\n }\n }\n\n return {\n exitCode,\n output,\n cost,\n };\n}\n","import { createConfig, resolvePaths, validateDependencies } from '../config.js';\nimport { runEngine } from '../core/engine.js';\nimport { allStoriesPass, loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { printError } from '../ui/logger.js';\n\nexport interface ExecuteOptions {\n issue?: string;\n maxIterations?: number;\n retryLimit?: number;\n retryForever?: boolean;\n /**\n * Conventional-commit scope for the stories of this issue (`issue-71`).\n * Only the multi-issue queue sets it — see `EngineConfig.commitScope`.\n */\n commitScope?: string;\n}\n\nexport async function runExecute(\n positionalMaxIter: number | undefined,\n options: ExecuteOptions,\n): Promise<number> {\n const errors = await validateDependencies();\n if (errors.length > 0) {\n printError('The following required tools are not installed:');\n for (const err of errors) {\n console.log(err);\n }\n return 1;\n }\n\n const maxIterations = options.maxIterations ?? positionalMaxIter;\n\n const config = createConfig({\n issueNumber: options.issue,\n maxIterations,\n retryLimit: options.retryLimit,\n retryForever: options.retryForever,\n commitScope: options.commitScope,\n });\n\n const paths = await resolvePaths(config);\n const exitCode = await runEngine(config, paths);\n\n // Update pipeline state if all stories pass\n if (exitCode === 0 && config.issueNumber) {\n try {\n const plan = await loadTaskPlan(paths.prdFile);\n if (allStoriesPass(plan)) {\n plan.pipeline.executionCompleted = true;\n await saveTaskPlan(paths.prdFile, plan);\n }\n } catch {\n // Non-critical — engine already handled state\n }\n }\n\n return exitCode;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,IAAI,OAAO,UAAU,iBAAiB;AAC/C,SAAS,YAAY;;;ACFrB,OAAO,WAAW;AAQX,SAAS,iBAAiB,QAAgB,OAAuB;AACtE,QAAM,WAAW;AACjB,MAAI,MAAM;AACV,MAAI,SAAS;AAEb,MAAI,QAAQ,GAAG;AACb,UAAM,KAAK,MAAO,SAAS,MAAO,KAAK;AACvC,aAAS,KAAK,MAAO,SAAS,WAAY,KAAK;AAAA,EACjD;AAEA,QAAM,QAAQ,WAAW;AACzB,QAAM,WAAW,WAAW,IAAI,WAAW;AAC3C,QAAM,YAAY,WAAW,IAAI,WAAW;AAE5C,QAAM,MAAM,SAAS,OAAO,MAAM,IAAI,UAAU,OAAO,KAAK;AAC5D,QAAM,OAAO,GAAG,MAAM,IAAI,KAAK,KAAK,GAAG;AAEvC,MAAI,SAAS,GAAG;AACd,WAAO,GAAG,MAAM,MAAM,GAAG,CAAC,IAAI,IAAI;AAAA,EACpC;AACA,SAAO,GAAG,GAAG,IAAI,IAAI;AACvB;AAgBO,SAAS,qBACd,WACA,SACA,SACA,eACM;AACN,QAAM,QAAQ,SAAS;AACvB,QAAM,UAAU,SAAS;AACzB,QAAM,KAAK,kBAAkB;AAE7B,QAAM,YAAY,UAAU,aAAa,SAAS,OAAO,OAAO,KAAK,aAAa,SAAS;AAE3F,QAAM,QAAQ,QAAQ;AAC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