@mmerterden/multi-agent-pipeline 20.44.0 → 21.0.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.
Files changed (419) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +31 -35
  3. package/README.tr.md +30 -34
  4. package/SECURITY.md +4 -4
  5. package/docs/architecture.md +6 -6
  6. package/docs/ecosystem.md +35 -30
  7. package/docs/facts.json +10 -8
  8. package/docs/features.md +6 -5
  9. package/index.js +1 -1
  10. package/install/_common.mjs +5 -1
  11. package/install/_mcp-register.mjs +80 -5
  12. package/install/_plugin-skills.mjs +1 -1
  13. package/install/_unattended-profile.mjs +12 -3
  14. package/install/claude.mjs +45 -4
  15. package/install/codex.mjs +2 -2
  16. package/install/index.mjs +49 -9
  17. package/install/templates/claude-hooks.json +2 -2
  18. package/install/templates/codex-instructions.md +1 -1
  19. package/install/templates/copilot-instructions.md +7 -7
  20. package/manifest.json +404 -404
  21. package/package.json +4 -4
  22. package/pipeline/agents/security-auditor.md +2 -2
  23. package/pipeline/agents/test-gen-analyst.md +1 -1
  24. package/pipeline/commands/archive-guard.md +6 -6
  25. package/pipeline/commands/multi-agent/SKILL.md +23 -2
  26. package/pipeline/commands/multi-agent/analysis/SKILL.md +8 -0
  27. package/pipeline/commands/multi-agent/analysis-jira/SKILL.md +8 -0
  28. package/pipeline/commands/multi-agent/autopilot-off/SKILL.md +10 -6
  29. package/pipeline/commands/multi-agent/bug-bash/SKILL.md +1 -1
  30. package/pipeline/commands/multi-agent/channels/SKILL.md +8 -0
  31. package/pipeline/commands/multi-agent/complaint-analysis/SKILL.md +8 -0
  32. package/pipeline/commands/multi-agent/create-jira/SKILL.md +8 -0
  33. package/pipeline/commands/multi-agent/design-check/SKILL.md +9 -1
  34. package/pipeline/commands/multi-agent/issue/SKILL.md +8 -0
  35. package/pipeline/commands/multi-agent/jira/SKILL.md +8 -0
  36. package/pipeline/commands/multi-agent/kill/SKILL.md +8 -0
  37. package/pipeline/commands/multi-agent/office-off/SKILL.md +3 -4
  38. package/pipeline/commands/multi-agent/office-on/SKILL.md +2 -6
  39. package/pipeline/commands/multi-agent/office-status/SKILL.md +1 -6
  40. package/pipeline/commands/multi-agent/prune-logs/SKILL.md +2 -2
  41. package/pipeline/commands/multi-agent/purge/SKILL.md +8 -0
  42. package/pipeline/commands/multi-agent/refactor/SKILL.md +16 -8
  43. package/pipeline/commands/multi-agent/research/SKILL.md +1 -1
  44. package/pipeline/commands/multi-agent/resume/SKILL.md +8 -0
  45. package/pipeline/commands/multi-agent/review/SKILL.md +8 -0
  46. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +8 -0
  47. package/pipeline/commands/multi-agent/review-issue/SKILL.md +8 -0
  48. package/pipeline/commands/multi-agent/review-jira/SKILL.md +8 -0
  49. package/pipeline/commands/multi-agent/review-priority/SKILL.md +8 -0
  50. package/pipeline/commands/multi-agent/route-on/SKILL.md +1 -1
  51. package/pipeline/commands/multi-agent/routines/SKILL.md +36 -14
  52. package/pipeline/commands/multi-agent/save/SKILL.md +1 -1
  53. package/pipeline/commands/multi-agent/scaffold/SKILL.md +8 -0
  54. package/pipeline/commands/multi-agent/search/SKILL.md +4 -4
  55. package/pipeline/commands/multi-agent/security-review/SKILL.md +9 -4
  56. package/pipeline/commands/multi-agent/setup/SKILL.md +7 -2
  57. package/pipeline/commands/multi-agent/store-ready/SKILL.md +5 -3
  58. package/pipeline/commands/multi-agent/sync/SKILL.md +20 -12
  59. package/pipeline/commands/multi-agent/test/SKILL.md +1 -1
  60. package/pipeline/commands/multi-agent/test-accessibility/SKILL.md +1 -1
  61. package/pipeline/commands/multi-agent/test-dark-mode/SKILL.md +1 -1
  62. package/pipeline/commands/multi-agent/test-dynamic-type/SKILL.md +1 -1
  63. package/pipeline/commands/multi-agent/test-gen/SKILL.md +1 -1
  64. package/pipeline/commands/multi-agent/test-screenshots/SKILL.md +1 -1
  65. package/pipeline/commands/multi-agent/testflight-validation/SKILL.md +1 -1
  66. package/pipeline/commands/multi-agent/uninstall/SKILL.md +3 -3
  67. package/pipeline/commands/multi-agent/update/SKILL.md +9 -2
  68. package/pipeline/commands/sim-test.md +5 -5
  69. package/pipeline/contract/CHANGELOG.md +49 -0
  70. package/pipeline/contract/README.md +34 -29
  71. package/pipeline/contract/build.mjs +0 -5
  72. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  73. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  74. package/pipeline/contract/manifest.json +62 -122
  75. package/pipeline/contract/types/index.d.ts +97 -49
  76. package/pipeline/lib/credential-inventory.sh +3 -2
  77. package/pipeline/lib/cross-repo.mjs +11 -6
  78. package/pipeline/lib/fetch-crashlytics.sh +5 -2
  79. package/pipeline/lib/mcp-rename.mjs +508 -0
  80. package/pipeline/lib/model-dispatch.sh +1 -1
  81. package/pipeline/lib/office-legacy.mjs +207 -0
  82. package/pipeline/lib/outbound-gate.mjs +8 -2
  83. package/pipeline/lib/route-state.sh +2 -2
  84. package/pipeline/lib/routine-secret-scan.mjs +166 -0
  85. package/pipeline/lib/toolkit-llm.sh +12 -10
  86. package/pipeline/lib/unattended.mjs +1 -1
  87. package/pipeline/lib/unattended.sh +1 -1
  88. package/pipeline/lib/untrusted-fence.mjs +1 -1
  89. package/pipeline/lib/usage-endpoint.mjs +32 -0
  90. package/pipeline/lib/usage-token.mjs +76 -0
  91. package/pipeline/multi-agent-refs/_input-parser.md +22 -0
  92. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  93. package/pipeline/multi-agent-refs/android-guide.md +2 -2
  94. package/pipeline/multi-agent-refs/audit-guide.md +1 -1
  95. package/pipeline/multi-agent-refs/complaint-analysis/phases.md +1 -1
  96. package/pipeline/multi-agent-refs/cross-cli-contract.md +20 -18
  97. package/pipeline/multi-agent-refs/design-check/build-launch.md +2 -2
  98. package/pipeline/multi-agent-refs/design-check/compare.md +2 -2
  99. package/pipeline/multi-agent-refs/design-check/drive-capture.md +1 -1
  100. package/pipeline/multi-agent-refs/design-check/export.md +1 -1
  101. package/pipeline/multi-agent-refs/design-check/init-inventory.md +2 -2
  102. package/pipeline/multi-agent-refs/design-check/mcp-currency-gate.md +4 -4
  103. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  104. package/pipeline/multi-agent-refs/features/build-facts.md +115 -0
  105. package/pipeline/multi-agent-refs/features/code-graph.md +8 -8
  106. package/pipeline/multi-agent-refs/features/code-intelligence.md +5 -5
  107. package/pipeline/multi-agent-refs/features/design-conformance.md +4 -4
  108. package/pipeline/multi-agent-refs/features/doctor.md +43 -4
  109. package/pipeline/multi-agent-refs/features/exploratory-testing.md +1 -1
  110. package/pipeline/multi-agent-refs/features/external-context-injection.md +1 -1
  111. package/pipeline/multi-agent-refs/features/free-models.md +5 -5
  112. package/pipeline/multi-agent-refs/features/office-threat-model.md +9 -32
  113. package/pipeline/multi-agent-refs/features/plan-attachment.md +55 -0
  114. package/pipeline/multi-agent-refs/features/product-context.md +1 -1
  115. package/pipeline/multi-agent-refs/features/routine-sharing.md +196 -0
  116. package/pipeline/multi-agent-refs/features/security-audit.md +3 -3
  117. package/pipeline/multi-agent-refs/features/test-classification.md +2 -2
  118. package/pipeline/multi-agent-refs/features/unattended-gates.md +1 -1
  119. package/pipeline/multi-agent-refs/features/unattended-security.md +8 -23
  120. package/pipeline/multi-agent-refs/features/usage-reporting.md +172 -4
  121. package/pipeline/multi-agent-refs/features/visual-evidence.md +1 -1
  122. package/pipeline/multi-agent-refs/help/en.md +138 -274
  123. package/pipeline/multi-agent-refs/help/tr.md +140 -274
  124. package/pipeline/multi-agent-refs/keychain.md +2 -2
  125. package/pipeline/multi-agent-refs/knowledge.md +4 -4
  126. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +3 -3
  127. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +2 -0
  128. package/pipeline/multi-agent-refs/outside-the-pipeline.md +2 -2
  129. package/pipeline/multi-agent-refs/phases/modes.md +17 -0
  130. package/pipeline/multi-agent-refs/phases/phase-0-init.md +21 -2
  131. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +8 -5
  132. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +2 -2
  133. package/pipeline/multi-agent-refs/phases/phase-3-review.md +4 -4
  134. package/pipeline/multi-agent-refs/phases/phase-5-report.md +10 -0
  135. package/pipeline/multi-agent-refs/refactor/sweep.md +4 -4
  136. package/pipeline/multi-agent-refs/refactor/toolkit-research.md +1 -1
  137. package/pipeline/multi-agent-refs/research/engine.md +1 -1
  138. package/pipeline/multi-agent-refs/rules.md +2 -2
  139. package/pipeline/multi-agent-refs/setup/app-store-connect.md +2 -2
  140. package/pipeline/multi-agent-refs/setup/firebase.md +3 -2
  141. package/pipeline/multi-agent-refs/setup/google-play.md +1 -1
  142. package/pipeline/multi-agent-refs/setup/token-save-flow.md +3 -2
  143. package/pipeline/multi-agent-refs/store-ready/gate-1-static.md +12 -2
  144. package/pipeline/multi-agent-refs/store-ready/gate-3-policy.md +3 -3
  145. package/pipeline/multi-agent-refs/store-ready/gates.md +2 -1
  146. package/pipeline/multi-agent-refs/store-ready/report.md +10 -1
  147. package/pipeline/multi-agent-refs/swiftui-guide.md +2 -2
  148. package/pipeline/multi-agent-refs/sync/codex.md +1 -1
  149. package/pipeline/multi-agent-refs/sync/dev-toolkit.md +5 -5
  150. package/pipeline/multi-agent-refs/sync/overview.md +2 -2
  151. package/pipeline/multi-agent-refs/sync/stack-plugins.md +2 -2
  152. package/pipeline/multi-agent-refs/tracker-contract.md +1 -1
  153. package/pipeline/multi-agent-refs/unattended-contract.md +1 -2
  154. package/pipeline/multi-agent-refs/web-guide.md +2 -2
  155. package/pipeline/office/index.html +645 -144
  156. package/pipeline/office/toolkit.json +1 -1
  157. package/pipeline/preferences-template.json +6 -6
  158. package/pipeline/rules/figma-pipeline.md +2 -2
  159. package/pipeline/rules/outside-the-pipeline.md +1 -1
  160. package/pipeline/schemas/activity-chat.schema.json +1 -1
  161. package/pipeline/schemas/activity-roles.schema.json +1 -1
  162. package/pipeline/schemas/activity.schema.json +1 -1
  163. package/pipeline/schemas/agent-state.schema.json +36 -2
  164. package/pipeline/schemas/analysis-output.schema.json +1 -1
  165. package/pipeline/schemas/answer-request.schema.json +1 -1
  166. package/pipeline/schemas/answer-result.schema.json +1 -1
  167. package/pipeline/schemas/autopilot-config.schema.json +1 -1
  168. package/pipeline/schemas/autopilot-off-request.schema.json +1 -1
  169. package/pipeline/schemas/autopilot-off.schema.json +1 -1
  170. package/pipeline/schemas/autopilot-on-request.schema.json +1 -1
  171. package/pipeline/schemas/autopilot-on.schema.json +1 -1
  172. package/pipeline/schemas/autopilot-status.schema.json +1 -1
  173. package/pipeline/schemas/bug-bash-verification.schema.json +1 -1
  174. package/pipeline/schemas/code-graph.schema.json +1 -1
  175. package/pipeline/schemas/command-parameters.schema.json +1 -1
  176. package/pipeline/schemas/constitution.schema.json +1 -1
  177. package/pipeline/schemas/contract-error.schema.json +6 -13
  178. package/pipeline/schemas/criteria-manifest.schema.json +1 -1
  179. package/pipeline/schemas/design-check-config.schema.json +1 -1
  180. package/pipeline/schemas/diff-risk.schema.json +1 -1
  181. package/pipeline/schemas/disk-clean-request.schema.json +1 -1
  182. package/pipeline/schemas/disk-clean.schema.json +1 -1
  183. package/pipeline/schemas/doctor-report.schema.json +1 -1
  184. package/pipeline/schemas/explore-run.schema.json +1 -1
  185. package/pipeline/schemas/figma-project-config.schema.json +1 -1
  186. package/pipeline/schemas/gc-request.schema.json +1 -1
  187. package/pipeline/schemas/gc.schema.json +1 -1
  188. package/pipeline/schemas/issue-maturity.schema.json +1 -1
  189. package/pipeline/schemas/issues.schema.json +1 -1
  190. package/pipeline/schemas/job-change.schema.json +1 -1
  191. package/pipeline/schemas/job-request.schema.json +1 -1
  192. package/pipeline/schemas/kill-request.schema.json +1 -1
  193. package/pipeline/schemas/kill.schema.json +1 -1
  194. package/pipeline/schemas/launch-plan.schema.json +1 -1
  195. package/pipeline/schemas/launch-request.schema.json +2 -2
  196. package/pipeline/schemas/launch.schema.json +1 -1
  197. package/pipeline/schemas/learnings-ledger.schema.json +1 -1
  198. package/pipeline/schemas/ledger.schema.json +1 -1
  199. package/pipeline/schemas/office-archive.schema.json +2 -2
  200. package/pipeline/schemas/office-credentials.schema.json +1 -1
  201. package/pipeline/schemas/office-jobs.schema.json +1 -1
  202. package/pipeline/schemas/office-memory.schema.json +1 -1
  203. package/pipeline/schemas/office-server-room.schema.json +1 -1
  204. package/pipeline/schemas/office-settings-request.schema.json +1 -1
  205. package/pipeline/schemas/office-settings.schema.json +1 -1
  206. package/pipeline/schemas/permissions.schema.json +1 -1
  207. package/pipeline/schemas/phases.json +4 -4
  208. package/pipeline/schemas/phases.schema.json +1 -1
  209. package/pipeline/schemas/plan-critique.schema.json +1 -1
  210. package/pipeline/schemas/planning-output.schema.json +1 -1
  211. package/pipeline/schemas/pr-reach.schema.json +1 -1
  212. package/pipeline/schemas/pr-request.schema.json +1 -1
  213. package/pipeline/schemas/prefs.schema.json +40 -18
  214. package/pipeline/schemas/product-tree-overlay.schema.json +1 -1
  215. package/pipeline/schemas/product-tree.schema.json +1 -1
  216. package/pipeline/schemas/prs.schema.json +1 -1
  217. package/pipeline/schemas/prune-logs-request.schema.json +1 -1
  218. package/pipeline/schemas/prune-logs.schema.json +1 -1
  219. package/pipeline/schemas/repo-change.schema.json +1 -1
  220. package/pipeline/schemas/repo-profile.schema.json +1 -1
  221. package/pipeline/schemas/repo-request.schema.json +1 -1
  222. package/pipeline/schemas/repos.schema.json +1 -1
  223. package/pipeline/schemas/research-output.schema.json +1 -1
  224. package/pipeline/schemas/resume-request.schema.json +1 -1
  225. package/pipeline/schemas/review-file-exclusions.schema.json +1 -1
  226. package/pipeline/schemas/review-verdict-request.schema.json +1 -1
  227. package/pipeline/schemas/review-verdict.schema.json +1 -1
  228. package/pipeline/schemas/reviewer-output.schema.json +1 -1
  229. package/pipeline/schemas/route-config.schema.json +2 -2
  230. package/pipeline/schemas/routine-delete.schema.json +1 -1
  231. package/pipeline/schemas/routines.schema.json +1 -1
  232. package/pipeline/schemas/run-evidence.schema.json +1 -1
  233. package/pipeline/schemas/run-log.schema.json +1 -1
  234. package/pipeline/schemas/run-questions.schema.json +1 -1
  235. package/pipeline/schemas/run-results.schema.json +1 -1
  236. package/pipeline/schemas/runs-index.schema.json +1 -1
  237. package/pipeline/schemas/scaffold-manifest.schema.json +1 -1
  238. package/pipeline/schemas/scope-check.schema.json +1 -1
  239. package/pipeline/schemas/secret-patterns.schema.json +1 -1
  240. package/pipeline/schemas/security-finding.schema.json +1 -1
  241. package/pipeline/schemas/service-read.schema.json +1 -1
  242. package/pipeline/schemas/shared-routine-import-request.schema.json +43 -0
  243. package/pipeline/schemas/shared-routine-import.schema.json +118 -0
  244. package/pipeline/schemas/shared-routine.schema.json +79 -0
  245. package/pipeline/schemas/shared-routines.schema.json +83 -0
  246. package/pipeline/schemas/skill-catalog.schema.json +1 -1
  247. package/pipeline/schemas/stack-adapters.schema.json +1 -1
  248. package/pipeline/schemas/stack-change.schema.json +1 -1
  249. package/pipeline/schemas/stack-request.schema.json +1 -1
  250. package/pipeline/schemas/stack.schema.json +1 -1
  251. package/pipeline/schemas/steer-request.schema.json +1 -1
  252. package/pipeline/schemas/steer.schema.json +1 -1
  253. package/pipeline/schemas/system-status.schema.json +2 -2
  254. package/pipeline/schemas/test-gap.schema.json +1 -1
  255. package/pipeline/schemas/test-gen-discovery.schema.json +1 -1
  256. package/pipeline/schemas/test-gen-gaps.schema.json +1 -1
  257. package/pipeline/schemas/test-gen-inventory.schema.json +1 -1
  258. package/pipeline/schemas/test-gen-results.schema.json +1 -1
  259. package/pipeline/schemas/token-budget.json +4 -4
  260. package/pipeline/schemas/token-budget.schema.json +1 -1
  261. package/pipeline/schemas/tool-call-request.schema.json +1 -1
  262. package/pipeline/schemas/tool-call.schema.json +1 -1
  263. package/pipeline/schemas/toolkit-path-params.json +34 -2
  264. package/pipeline/schemas/toolkit-path-params.schema.json +2 -2
  265. package/pipeline/schemas/tools.schema.json +2 -2
  266. package/pipeline/schemas/triage-corpus.schema.json +1 -1
  267. package/pipeline/schemas/triage-output.schema.json +1 -1
  268. package/pipeline/schemas/unattended-policy.json +8 -4
  269. package/pipeline/schemas/unattended-policy.schema.json +1 -1
  270. package/pipeline/schemas/unattended-profile.json +8 -6
  271. package/pipeline/schemas/unattended-profile.schema.json +1 -1
  272. package/pipeline/schemas/worktrees.schema.json +1 -1
  273. package/pipeline/scripts/_contract-core.mjs +1 -1
  274. package/pipeline/scripts/_contract-routes-ops.mjs +14 -1
  275. package/pipeline/scripts/_contract-routes-routines.mjs +327 -0
  276. package/pipeline/scripts/_contract-routes-runs.mjs +4 -47
  277. package/pipeline/scripts/_guard-probe.mjs +1 -1
  278. package/pipeline/scripts/_renamed-skills.mjs +20 -8
  279. package/pipeline/scripts/_sibling-root.mjs +1 -1
  280. package/pipeline/scripts/_stack-routing.mjs +1 -0
  281. package/pipeline/scripts/_user_guard_rules.py +22 -7
  282. package/pipeline/scripts/autopilot-control.mjs +14 -2
  283. package/pipeline/scripts/autopilot-loop.mjs +16 -1
  284. package/pipeline/scripts/autopilot-runner.mjs +37 -12
  285. package/pipeline/scripts/bulk-read.sh +1 -1
  286. package/pipeline/scripts/contract-server.mjs +68 -147
  287. package/pipeline/scripts/cost-table.json +2 -2
  288. package/pipeline/scripts/doctor.mjs +171 -10
  289. package/pipeline/scripts/feedback-send.mjs +2 -36
  290. package/pipeline/scripts/gen-facts.mjs +21 -1
  291. package/pipeline/scripts/gen-free-hosts.mjs +2 -2
  292. package/pipeline/scripts/gen-mode-dispatch.mjs +11 -7
  293. package/pipeline/scripts/graph-hint.mjs +1 -1
  294. package/pipeline/scripts/health-report.mjs +4 -3
  295. package/pipeline/scripts/job-launch.mjs +1 -1
  296. package/pipeline/scripts/launch-request.mjs +12 -25
  297. package/pipeline/scripts/migrate-prefs.mjs +21 -1
  298. package/pipeline/scripts/office-archive.mjs +1 -2
  299. package/pipeline/scripts/office-control.mjs +17 -92
  300. package/pipeline/scripts/office-server-room.mjs +1 -1
  301. package/pipeline/scripts/phase0-exit-gate.mjs +1 -1
  302. package/pipeline/scripts/plan-attachment.mjs +1082 -0
  303. package/pipeline/scripts/pre-commit-check.sh +4 -0
  304. package/pipeline/scripts/pre-push-check.sh +1 -1
  305. package/pipeline/scripts/probe-evidence-capability.sh +1 -1
  306. package/pipeline/scripts/repo-recommend.mjs +2 -2
  307. package/pipeline/scripts/routine-registry.mjs +537 -53
  308. package/pipeline/scripts/routine-share.mjs +442 -0
  309. package/pipeline/scripts/runs-index.mjs +1 -1
  310. package/pipeline/scripts/system-status.mjs +8 -2
  311. package/pipeline/scripts/test-classify.mjs +1 -1
  312. package/pipeline/scripts/toolkit-tools.mjs +4 -3
  313. package/pipeline/scripts/unattended_policy.py +18 -5
  314. package/pipeline/scripts/uninstall.mjs +71 -28
  315. package/pipeline/scripts/usage-access.mjs +384 -0
  316. package/pipeline/scripts/usage-identity.mjs +81 -14
  317. package/pipeline/scripts/usage-register.mjs +389 -72
  318. package/pipeline/scripts/usage-report.mjs +124 -11
  319. package/pipeline/scripts/work-items.mjs +1 -1
  320. package/pipeline/scripts/write-store-config.mjs +3 -3
  321. package/pipeline/skills/.skill-manifest.json +66 -70
  322. package/pipeline/skills/.skills-index.json +18 -29
  323. package/pipeline/skills/renamed.json +2 -1
  324. package/pipeline/skills/shared/README.md +11 -12
  325. package/pipeline/skills/shared/core/apple-archive-compliance/SKILL.md +14 -14
  326. package/pipeline/skills/shared/core/apple-archive-compliance/references/examples.md +1 -1
  327. package/pipeline/skills/shared/core/apple-archive-compliance/references/version-history.md +3 -3
  328. package/pipeline/skills/shared/core/google-play-compliance/SKILL.md +1 -1
  329. package/pipeline/skills/shared/core/google-play-compliance/references/notes.md +1 -1
  330. package/pipeline/skills/shared/core/multi-agent/SKILL.md +14 -4
  331. package/pipeline/skills/shared/core/multi-agent-analysis/SKILL.md +8 -0
  332. package/pipeline/skills/shared/core/multi-agent-analysis-jira/SKILL.md +8 -0
  333. package/pipeline/skills/shared/core/multi-agent-autopilot-off/SKILL.md +6 -3
  334. package/pipeline/skills/shared/core/multi-agent-bug-bash/SKILL.md +1 -1
  335. package/pipeline/skills/shared/core/multi-agent-channels/SKILL.md +8 -0
  336. package/pipeline/skills/shared/core/multi-agent-complaint-analysis/SKILL.md +9 -1
  337. package/pipeline/skills/shared/core/multi-agent-create-jira/SKILL.md +8 -0
  338. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +13 -5
  339. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +6 -6
  340. package/pipeline/skills/shared/core/multi-agent-help/SKILL.md +1 -1
  341. package/pipeline/skills/shared/core/multi-agent-issue/SKILL.md +8 -0
  342. package/pipeline/skills/shared/core/multi-agent-jira/SKILL.md +8 -0
  343. package/pipeline/skills/shared/core/multi-agent-kill/SKILL.md +8 -0
  344. package/pipeline/skills/shared/core/multi-agent-office-off/SKILL.md +2 -2
  345. package/pipeline/skills/shared/core/multi-agent-office-on/SKILL.md +1 -1
  346. package/pipeline/skills/shared/core/multi-agent-office-status/SKILL.md +2 -4
  347. package/pipeline/skills/shared/core/multi-agent-purge/SKILL.md +8 -0
  348. package/pipeline/skills/shared/core/multi-agent-refactor/SKILL.md +16 -8
  349. package/pipeline/skills/shared/core/multi-agent-research/SKILL.md +2 -2
  350. package/pipeline/skills/shared/core/multi-agent-resume/SKILL.md +8 -0
  351. package/pipeline/skills/shared/core/multi-agent-review/SKILL.md +8 -0
  352. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +8 -0
  353. package/pipeline/skills/shared/core/multi-agent-review-issue/SKILL.md +8 -0
  354. package/pipeline/skills/shared/core/multi-agent-review-jira/SKILL.md +8 -0
  355. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +8 -0
  356. package/pipeline/skills/shared/core/multi-agent-route-on/SKILL.md +1 -1
  357. package/pipeline/skills/shared/core/multi-agent-routines/SKILL.md +17 -6
  358. package/pipeline/skills/shared/core/multi-agent-save/SKILL.md +3 -3
  359. package/pipeline/skills/shared/core/multi-agent-scaffold/SKILL.md +8 -0
  360. package/pipeline/skills/shared/core/multi-agent-search/SKILL.md +3 -3
  361. package/pipeline/skills/shared/core/multi-agent-security-review/SKILL.md +6 -5
  362. package/pipeline/skills/shared/core/multi-agent-setup/SKILL.md +7 -2
  363. package/pipeline/skills/shared/core/multi-agent-store-ready/SKILL.md +20 -8
  364. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +18 -10
  365. package/pipeline/skills/shared/core/multi-agent-test/SKILL.md +5 -3
  366. package/pipeline/skills/shared/core/multi-agent-test-accessibility/SKILL.md +5 -3
  367. package/pipeline/skills/shared/core/multi-agent-test-dark-mode/SKILL.md +5 -3
  368. package/pipeline/skills/shared/core/multi-agent-test-dynamic-type/SKILL.md +5 -3
  369. package/pipeline/skills/shared/core/multi-agent-test-gen/SKILL.md +2 -2
  370. package/pipeline/skills/shared/core/multi-agent-test-screenshots/SKILL.md +5 -3
  371. package/pipeline/skills/shared/core/multi-agent-testflight-validation/SKILL.md +7 -4
  372. package/pipeline/skills/shared/core/multi-agent-update/SKILL.md +70 -17
  373. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -2
  374. package/pipeline/skills/shared/external/app-store-review/SKILL.md +1 -1
  375. package/pipeline/skills/shared/external/e2e-testing/SKILL.md +23 -23
  376. package/pipeline/skills/shared/external/e2e-testing/evals/evals.json +1 -1
  377. package/pipeline/skills/shared/external/e2e-testing/references/document-fixtures.md +6 -6
  378. package/pipeline/skills/shared/external/free-llm-apis/SKILL.md +2 -2
  379. package/pipeline/skills/shared/external/handle-request/SKILL.md +1 -1
  380. package/pipeline/skills/shared/external/hig-app-icons/SKILL.md +2 -2
  381. package/pipeline/skills/shared/external/hig-app-icons/references/icon-workflow.md +1 -1
  382. package/pipeline/skills/shared/external/ios-design-review/SKILL.md +12 -12
  383. package/pipeline/skills/shared/external/ios-design-review/evals/evals.json +1 -1
  384. package/pipeline/skills/shared/external/ios-design-review/references/appearance-matrix.md +17 -17
  385. package/pipeline/skills/shared/external/ios-design-review/references/checklist.md +1 -1
  386. package/pipeline/skills/shared/external/ios-simulator-debugging/SKILL.md +5 -5
  387. package/pipeline/skills/shared/external/passkit-wallet/SKILL.md +4 -4
  388. package/pipeline/skills/shared/external/release-video/SKILL.md +10 -10
  389. package/pipeline/skills/shared/external/release-video/evals/evals.json +8 -8
  390. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +231 -0
  391. package/pipeline/skills/shared/external/reverse-engineer-own-app/evals/evals.json +43 -0
  392. package/pipeline/skills/shared/external/security-review/SKILL.md +2 -2
  393. package/pipeline/skills/shared/external/security-review/references/owasp-mobile-top10-2024.md +1 -1
  394. package/pipeline/skills/shared/external/security-review/references/owasp-web-api-top10-2021.md +1 -1
  395. package/pipeline/skills/shared/external/short-video-craft/SKILL.md +20 -20
  396. package/pipeline/skills/shared/external/short-video-craft/evals/evals.json +3 -3
  397. package/pipeline/skills/shared/external/short-video-craft/references/generated-defaults.md +2 -2
  398. package/pipeline/skills/shared/external/signal-community/SKILL.md +6 -6
  399. package/pipeline/skills/shared/external/test-result-triage/SKILL.md +4 -4
  400. package/pipeline/skills/shared/external/web-testing/SKILL.md +3 -3
  401. package/pipeline/skills/shared/external/web-testing/references/testing-examples.md +13 -13
  402. package/pipeline/skills/skills-index.md +7 -8
  403. package/pipeline/commands/multi-agent/autopilot/SKILL.md +0 -123
  404. package/pipeline/commands/multi-agent/office-pair/SKILL.md +0 -89
  405. package/pipeline/contract/fixtures/error-unsigned.json +0 -5
  406. package/pipeline/lib/office-remote.mjs +0 -228
  407. package/pipeline/lib/qr-code.mjs +0 -386
  408. package/pipeline/lib/web-push.mjs +0 -198
  409. package/pipeline/multi-agent-refs/features/office-remote-protocol.md +0 -319
  410. package/pipeline/multi-agent-refs/features/phone-api.md +0 -306
  411. package/pipeline/schemas/phone-devices.schema.json +0 -61
  412. package/pipeline/schemas/phone-signed-request.schema.json +0 -67
  413. package/pipeline/scripts/_phone-auth.mjs +0 -485
  414. package/pipeline/scripts/office-pair.mjs +0 -459
  415. package/pipeline/scripts/office-push.mjs +0 -613
  416. package/pipeline/scripts/office-remote-client.mjs +0 -490
  417. package/pipeline/scripts/phone-devices.mjs +0 -248
  418. package/pipeline/skills/shared/core/multi-agent-autopilot/SKILL.md +0 -62
  419. package/pipeline/skills/shared/core/multi-agent-office-pair/SKILL.md +0 -19
@@ -0,0 +1,1082 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * plan-attachment.mjs - put the approved Phase 1 plan on the issue the run
4
+ * started from, so the people who read the ticket see the plan the code
5
+ * follows.
6
+ *
7
+ * A Jira issue gets the plan as a Markdown attachment named
8
+ * `plan-<taskId>-v<N>.md`; a GitHub issue, which has no attachment API, gets
9
+ * one comment holding the plan inside a <details> block. A free-text run has
10
+ * no issue and nothing happens. The decision follows
11
+ * `prefs.projects.<project>.planAttachment`, else
12
+ * `prefs.global.planAttachment`, else "ask":
13
+ *
14
+ * never nothing leaves the machine
15
+ * always attached without asking; in a run with MULTI_AGENT_UNATTENDED=1
16
+ * only when unattended-policy.json does not block this script's
17
+ * `upload` (publisherScripts), the same entry agent-guard reads
18
+ * ask an attended run asks once (the orchestrator does, after `decide`
19
+ * prints action "ask") and the answer holds for the rest of the run;
20
+ * a run that cannot ask (unattended or autopilot) skips and says why
21
+ *
22
+ * Only a plan the gate let through is sent, and only on a record the
23
+ * orchestrator wrote at the gate: `phases["1"].planApprovedAt` (the user's
24
+ * Approve), or, in autopilot, `phases["1"].gateSkippedAt` (the safety
25
+ * classifier did not pause, so the gate was skipped by policy). plan.json's
26
+ * own `approved` flag proves nothing and is not read. A gate that was shown
27
+ * and not yet answered has neither record, so nothing is sent. Writing a new
28
+ * plan clears both records, and a record older than the plan file's last
29
+ * write (to the second) is refused as well, so an approval never carries over
30
+ * to a plan written after it. The rendered
31
+ * text goes through the outbound gate's rules first, and any finding stops
32
+ * the upload; the rule name and line are recorded, never the value.
33
+ *
34
+ * Versions: each upload of a changed plan writes the next
35
+ * `plan-attachments/plan-<taskId>-v<N>.md` beside the run state. Earlier
36
+ * versions are kept, here and on the issue. Uploading an unchanged plan that
37
+ * is already attached is a no-op, so a resumed step does not post twice.
38
+ * Before a Jira upload the issue's attachments are listed: a file with the
39
+ * same name and size is taken as already attached (an earlier upload whose
40
+ * response was lost), and a same-named file with other content moves the
41
+ * upload to the next free version.
42
+ *
43
+ * Hosts: the Jira upload goes to a configured host: `prefs.global.hosts.jira`
44
+ * or a `prefs.global.accounts[].jiraHost`. JIRA_HOST or ACCOUNT_JIRA_HOST may
45
+ * pick one of them, in every mode; any other value is refused. Host and token
46
+ * are one account's pair, never mixed: ACCOUNT_JIRA_TOKEN_KEY names its
47
+ * account by its prefix (`<Prefix>_Jira_..._Token` is account `<prefix>`, as
48
+ * account-resolver.sh derives it), and that account's host is used; with no
49
+ * key, `keychainMapping.jira` goes with `hosts.jira` only. A JIRA_TOKEN value
50
+ * is the caller's own pair with the host it chose.
51
+ * The GitHub comment goes through gh's default host: GH_HOST other than
52
+ * github.com is refused in an attended run and removed in one that cannot ask.
53
+ *
54
+ * The GitHub comment ends with a hidden marker, `<!-- multi-agent-plan:
55
+ * <taskId>:v<N>:<first 12 hex of the plan's sha256> -->`. The issue's comments
56
+ * are listed first, every page, and a comment carrying the same marker counts
57
+ * as attached; a listing that fails posts nothing. A gh call that times out
58
+ * or exits without an HTTP status is recorded with the status unknown and is
59
+ * not retried.
60
+ *
61
+ * Transport: fetch first. curl is the fallback only for a failure raised
62
+ * before the request went out (no fetch, connection refused, DNS, TLS); a
63
+ * timeout or any error after the request started is recorded as failed with
64
+ * the status unknown and is never resent, so one run cannot attach twice.
65
+ *
66
+ * Every outcome lands in `state.planAttachment.outcomes[]`: attached (with the
67
+ * attachment or comment id and URL), skipped (with the reason) or failed (with
68
+ * the HTTP status). A failure is reported, never fatal: every subcommand exits
69
+ * 0 except on a usage error.
70
+ *
71
+ * Usage:
72
+ * plan-attachment.mjs decide --state <agent-state.json> [--answer yes|no]
73
+ * plan-attachment.mjs upload --state <agent-state.json> --plan <plan.json> [--answer yes|no]
74
+ * plan-attachment.mjs line --state <agent-state.json>
75
+ *
76
+ * `decide` and `upload` print one JSON object. `line` prints the Phase 5
77
+ * report line, or nothing when there is no outcome.
78
+ *
79
+ * Env: JIRA_HOST, ACCOUNT_JIRA_HOST, ACCOUNT_JIRA_TOKEN_KEY (as under Hosts),
80
+ * JIRA_TOKEN (else the credential store under ACCOUNT_JIRA_TOKEN_KEY or
81
+ * keychainMapping.jira), GH_HOST, MULTI_AGENT_PREFS, MULTI_AGENT_UNATTENDED.
82
+ *
83
+ * Exit: 0 done (whatever the outcome) · 2 usage
84
+ *
85
+ * @module pipeline/scripts/plan-attachment
86
+ */
87
+
88
+ import { execFile, spawnSync } from "node:child_process";
89
+ import { createHash, randomBytes } from "node:crypto";
90
+ import {
91
+ existsSync,
92
+ mkdtempSync,
93
+ readdirSync,
94
+ readFileSync,
95
+ rmSync,
96
+ statSync,
97
+ writeFileSync,
98
+ } from "node:fs";
99
+ import { homedir, tmpdir } from "node:os";
100
+ import { basename, dirname, join } from "node:path";
101
+ import { fileURLToPath } from "node:url";
102
+ import { ArgsError, parseArgs } from "../lib/args.mjs";
103
+ import { exitOnHelp } from "../lib/cli-help.mjs";
104
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
105
+ import { scan } from "../lib/outbound-gate.mjs";
106
+ import { loadPrefs, prefsPath } from "../lib/prefs-value.mjs";
107
+ import { mkdirSafe, writeFileSafe } from "../lib/safe-write.mjs";
108
+ import { isUnattended } from "../lib/unattended.mjs";
109
+
110
+ exitOnHelp(import.meta.url);
111
+
112
+ const HERE = dirname(fileURLToPath(import.meta.url));
113
+ const SCRIPT = "plan-attachment.mjs";
114
+ export const SETTINGS = ["ask", "always", "never"];
115
+ const JIRA_KEY = /^[A-Z][A-Z0-9_]{0,31}-[1-9][0-9]{0,9}$/;
116
+ const GH_OWNER_REPO = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}$/;
117
+ const GITHUB_COMMENT_MAX = 65000;
118
+ const MAX_OUTCOMES = 50;
119
+ const TIMEOUT_MS = 30_000;
120
+ const GITHUB_PAGE = 100;
121
+ const GITHUB_MAX_PAGES = 50;
122
+
123
+ export const REASONS = {
124
+ never: "plan not attached: planAttachment=never",
125
+ invalidSetting: "plan not attached: planAttachment has an unsupported value",
126
+ askUnattended: "plan not attached: planAttachment=ask in an unattended run",
127
+ policyBlocks: `plan not attached: the unattended policy blocks ${SCRIPT} upload`,
128
+ declined: "plan not attached: declined at the prompt",
129
+ notApproved: "plan not attached: the plan has not passed the approval gate",
130
+ noPlan: "plan not attached: the plan file is missing or not valid JSON",
131
+ noHost: "plan not attached: no Jira host in prefs (global.hosts.jira)",
132
+ envHost: "plan not attached: the host in the environment is not a configured host",
133
+ accountMismatch: "plan not attached: the Jira host and token belong to different accounts",
134
+ insecureHost: "plan not attached: the Jira host is not https",
135
+ noToken: "plan not attached: no Jira token (onboard it with setup)",
136
+ badIssue: "plan not attached: the issue reference in the run state is malformed",
137
+ tooLarge: "plan not attached: the plan is larger than a GitHub comment allows",
138
+ };
139
+
140
+ /** Which issue the run started from, or null for a free-text run. */
141
+ export function issueTarget(state) {
142
+ const input = String(state?.inputType ?? "");
143
+ const jira = typeof state?.jiraId === "string" && state.jiraId ? state.jiraId : null;
144
+ const gh = state?.githubIssue && typeof state.githubIssue === "object" ? state.githubIssue : null;
145
+ if (input === "free-text") return null;
146
+ if (input.startsWith("github-") && gh) return { kind: "github", ...gh };
147
+ if (input.startsWith("jira-") && jira) return { kind: "jira", key: jira };
148
+ if (jira) return { kind: "jira", key: jira };
149
+ if (gh) return { kind: "github", ...gh };
150
+ return null;
151
+ }
152
+
153
+ /** The effective setting: the project override, then global, then "ask". */
154
+ export function planAttachmentSetting(prefs, project) {
155
+ const own = project ? prefs?.projects?.[project]?.planAttachment : undefined;
156
+ return own ?? prefs?.global?.planAttachment ?? "ask";
157
+ }
158
+
159
+ /** True when the policy keeps an unattended run from running `upload`. */
160
+ export function policyBlocksUpload(policy) {
161
+ if (!policy || typeof policy !== "object") return true;
162
+ const scripts = policy.publisherScripts ?? {};
163
+ if (!Object.hasOwn(scripts, SCRIPT)) return false;
164
+ const subs = scripts[SCRIPT];
165
+ return subs === null || (Array.isArray(subs) && subs.includes("upload"));
166
+ }
167
+
168
+ /**
169
+ * What to do, without doing it.
170
+ *
171
+ * @returns {{action: "none"|"skip"|"ask"|"attach", target: object|null, setting?: string, reason?: string}}
172
+ */
173
+ export function decide({ state, prefs, env = process.env, policy, answer }) {
174
+ const target = issueTarget(state);
175
+ if (!target) return { action: "none", target: null };
176
+ const setting = planAttachmentSetting(prefs, state?.project);
177
+ const skip = (reason) => ({ action: "skip", target, setting, reason });
178
+ if (!SETTINGS.includes(setting)) return skip(REASONS.invalidSetting);
179
+ if (setting === "never") return skip(REASONS.never);
180
+ const unattended = isUnattended(env);
181
+ const cannotAsk = unattended || state?.autopilot === true;
182
+ if (setting === "ask") {
183
+ if (cannotAsk) return skip(REASONS.askUnattended);
184
+ const given = answer ?? state?.planAttachment?.answer;
185
+ if (given === "no") return skip(REASONS.declined);
186
+ if (given !== "yes") return { action: "ask", target, setting };
187
+ }
188
+ if (unattended && policyBlocksUpload(policy)) return skip(REASONS.policyBlocks);
189
+ return { action: "attach", target, setting };
190
+ }
191
+
192
+ /**
193
+ * Whether the gate let the plan through, on the record the gate wrote. With
194
+ * `planWrittenMs`, a record older than that second is refused: it approved an
195
+ * earlier plan.
196
+ */
197
+ export function planApproved(state, { planWrittenMs } = {}) {
198
+ const gate = state?.phases?.["1"] ?? {};
199
+ const at = gate.planApprovedAt
200
+ ? gate.planApprovedAt
201
+ : state?.autopilot === true && typeof gate.gateSkippedAt === "string"
202
+ ? gate.gateSkippedAt
203
+ : "";
204
+ if (!at) return false;
205
+ if (planWrittenMs === undefined) return true;
206
+ const t = Date.parse(at);
207
+ return Number.isFinite(t) && t >= Math.floor(planWrittenMs / 1000) * 1000;
208
+ }
209
+
210
+ /** The approval line for the rendered plan. */
211
+ function approvalLabel(state) {
212
+ const gate = state?.phases?.["1"] ?? {};
213
+ return gate.planApprovedAt || `${gate.gateSkippedAt} (autopilot, gate skipped by policy)`;
214
+ }
215
+
216
+ /** A task id as a file name part: `#316` becomes `316`, `PROJ-1` stays. */
217
+ export function fileStem(taskId) {
218
+ const s = String(taskId ?? "")
219
+ .replace(/[^A-Za-z0-9._-]+/g, "-")
220
+ .replace(/^[-.]+|[-.]+$/g, "");
221
+ return s.slice(0, 80) || "task";
222
+ }
223
+
224
+ /** `plan-<stem>-v<N>.md` files in dir, highest version last. */
225
+ export function existingVersions(dir, stem) {
226
+ return existsSync(dir) ? versionsOf(readdirSync(dir), stem) : [];
227
+ }
228
+
229
+ /** The `plan-<stem>-v<N>.md` names among names, highest version last. */
230
+ export function versionsOf(names, stem) {
231
+ const re = new RegExp(`^plan-${stem.replace(/[.]/g, "\\.")}-v([1-9][0-9]{0,5})\\.md$`);
232
+ return names
233
+ .map((name) => {
234
+ const m = re.exec(name);
235
+ return m ? { name, version: Number(m[1]) } : null;
236
+ })
237
+ .filter(Boolean)
238
+ .sort((a, b) => a.version - b.version);
239
+ }
240
+
241
+ const list = (items) => (Array.isArray(items) ? items.filter((x) => x != null) : []);
242
+ const oneLine = (s) =>
243
+ String(s ?? "")
244
+ .replace(/\s+/g, " ")
245
+ .trim();
246
+
247
+ /** The approved plan as Markdown. */
248
+ export function renderPlanMarkdown({ plan, state, version, approvedAt }) {
249
+ const tasks = list(plan?.tasks);
250
+ const out = [`# Development plan: ${oneLine(state?.taskId)} (v${version})`, ""];
251
+ if (state?.title) out.push(`**Task:** ${oneLine(state.title)}`, "");
252
+ out.push(`**Approved:** ${approvedAt}`, `**Tasks:** ${tasks.length}`, "");
253
+ if (plan?.approach) out.push("## Approach", "", String(plan.approach).trim(), "");
254
+ out.push("## Tasks", "");
255
+ for (const t of tasks) {
256
+ out.push(`### ${oneLine(t.id)}: ${oneLine(t.title)}`, "");
257
+ if (t.type) out.push(`- Type: ${oneLine(t.type)}`);
258
+ const files = list(t.files);
259
+ if (files.length) out.push(`- Files: ${files.map((f) => `\`${oneLine(f)}\``).join(", ")}`);
260
+ const deps = list(t.dependsOn);
261
+ if (deps.length) out.push(`- Depends on: ${deps.map(oneLine).join(", ")}`);
262
+ const criteria = list(t.acceptanceCriteria);
263
+ if (criteria.length) {
264
+ out.push("- Acceptance criteria:");
265
+ for (const c of criteria) out.push(` - ${oneLine(typeof c === "string" ? c : c?.text)}`);
266
+ }
267
+ out.push("");
268
+ }
269
+ const focus = list(plan?.reviewFocus);
270
+ if (focus.length) {
271
+ out.push("## Review focus", "");
272
+ for (const f of focus) {
273
+ const text = typeof f === "string" ? f : (f?.input ?? f?.text ?? f?.description ?? "");
274
+ const owner = f?.ownerTaskId ? ` (${oneLine(f.ownerTaskId)})` : "";
275
+ out.push(`- ${oneLine(text)}${owner}`);
276
+ }
277
+ out.push("");
278
+ }
279
+ const constraints = list(plan?.globalConstraints);
280
+ if (constraints.length) {
281
+ out.push("## Global constraints", "");
282
+ for (const c of constraints) out.push(`- ${oneLine(c)}`);
283
+ out.push("");
284
+ }
285
+ return `${out.join("\n").trimEnd()}\n`;
286
+ }
287
+
288
+ const runAt = (text, i) => {
289
+ let j = i;
290
+ while (text[j] === "`") j += 1;
291
+ return j - i;
292
+ };
293
+
294
+ /**
295
+ * The [start, end) ranges GitHub renders as code. A backslash escapes the
296
+ * backtick after it. A run of backticks opens a span only when a run of the
297
+ * same length closes it, and an inline span ends at a blank line; a run of
298
+ * three or more at the start of a line is a fence, closed by a line starting
299
+ * with a run at least as long. Anything that does not close is text, so a
300
+ * doubtful case is neutralized rather than passed through.
301
+ */
302
+ export function codeRanges(text) {
303
+ const ranges = [];
304
+ let i = 0;
305
+ while (i < text.length) {
306
+ if (text[i] === "\\") {
307
+ i += 2;
308
+ continue;
309
+ }
310
+ if (text[i] !== "`") {
311
+ i += 1;
312
+ continue;
313
+ }
314
+ const run = runAt(text, i);
315
+ const lineStart = /(^|\n) {0,3}$/.test(text.slice(Math.max(0, i - 4), i)) || i === 0;
316
+ let end = -1;
317
+ if (run >= 3 && lineStart) {
318
+ const fence = new RegExp(`\\n {0,3}\`{${run},}[ \\t]*(?=\\n|$)`, "g");
319
+ fence.lastIndex = i + run;
320
+ const m = fence.exec(text);
321
+ if (m) end = m.index + m[0].length;
322
+ } else {
323
+ let k = i + run;
324
+ while (k < text.length) {
325
+ if (text[k] === "\n" && /^\n[ \t]*\n/.test(text.slice(k))) break;
326
+ if (text[k] !== "`") {
327
+ k += 1;
328
+ continue;
329
+ }
330
+ const close = runAt(text, k);
331
+ if (close === run) {
332
+ end = k + close;
333
+ break;
334
+ }
335
+ k += close;
336
+ }
337
+ }
338
+ if (end === -1) {
339
+ i += run;
340
+ continue;
341
+ }
342
+ ranges.push([i, end]);
343
+ i = end;
344
+ }
345
+ return ranges;
346
+ }
347
+
348
+ /**
349
+ * Text GitHub renders, made inert outside code: an `@name` would notify that
350
+ * account and a details or summary tag would end the block early. Code spans
351
+ * and fences are left as written; GitHub does neither inside them.
352
+ */
353
+ export function neutralizeForGithub(markdown) {
354
+ const text = String(markdown);
355
+ const inert = (part) =>
356
+ part.replace(/@(?=[A-Za-z0-9])/g, "@​").replace(/<(\/?)(details|summary)\b/gi, "&lt;$1$2");
357
+ let out = "";
358
+ let at = 0;
359
+ for (const [start, end] of codeRanges(text)) {
360
+ out += inert(text.slice(at, start)) + text.slice(start, end);
361
+ at = end;
362
+ }
363
+ return out + inert(text.slice(at));
364
+ }
365
+
366
+ /** The hidden line that identifies one plan version's comment on an issue. */
367
+ export function planMarker({ stem, version, markdown }) {
368
+ const sha = createHash("sha256").update(String(markdown)).digest("hex").slice(0, 12);
369
+ return `<!-- multi-agent-plan:${stem}:v${version}:${sha} -->`;
370
+ }
371
+
372
+ /** The one GitHub comment: a summary line, the plan inside <details>, the marker. */
373
+ export function githubCommentBody({ markdown, version, taskCount, approvedAt, marker }) {
374
+ return [
375
+ `**Approved development plan v${version}** (${taskCount} task${taskCount === 1 ? "" : "s"}, approved ${approvedAt})`,
376
+ "",
377
+ "<details>",
378
+ `<summary>Plan v${version}</summary>`,
379
+ "",
380
+ neutralizeForGithub(markdown).trimEnd(),
381
+ "",
382
+ "</details>",
383
+ "",
384
+ ...(marker ? [marker, ""] : []),
385
+ ].join("\n");
386
+ }
387
+
388
+ /** Every outbound-gate finding as `rule (line N)`; the value is never kept. */
389
+ export function secretFindings(text) {
390
+ return scan(text).map((f) => `${f.rule} (line ${f.line})`);
391
+ }
392
+
393
+ function hostUrl(raw) {
394
+ const s = String(raw ?? "").trim();
395
+ if (!s) return null;
396
+ try {
397
+ const url = new URL(/^[a-z]+:\/\//i.test(s) ? s : `https://${s}`);
398
+ return { url, base: url.origin + url.pathname.replace(/\/+$/, "") };
399
+ } catch {
400
+ return null;
401
+ }
402
+ }
403
+
404
+ /** The account a credential-store key belongs to, as account-resolver.sh names it. */
405
+ export function accountOfKey(key) {
406
+ const m = /^(.+?)_Jira_.+$/.exec(String(key ?? ""));
407
+ return m ? m[1].toLowerCase().replace(/_/g, "-") : null;
408
+ }
409
+
410
+ /**
411
+ * The Jira base URL and the token that goes with it, or a reason not to send.
412
+ * Host and token come from one account; see Hosts in the header.
413
+ *
414
+ * @returns {{base: string, token?: string, tokenKey?: string} | {reason: string}}
415
+ */
416
+ export function jiraBase(env, prefs) {
417
+ const global = hostUrl(prefs?.global?.hosts?.jira);
418
+ const accounts = list(prefs?.global?.accounts).filter((a) => typeof a?.id === "string");
419
+ const configured = [global, ...accounts.map((a) => hostUrl(a.jiraHost))].filter(Boolean);
420
+ const same = (x, y) => Boolean(x && y) && x.base.toLowerCase() === y.base.toLowerCase();
421
+
422
+ const raw = String(env.JIRA_HOST || env.ACCOUNT_JIRA_HOST || "").trim();
423
+ let fromEnv = null;
424
+ if (raw) {
425
+ const asked = hostUrl(raw);
426
+ fromEnv = configured.find((c) => same(c, asked)) ?? null;
427
+ if (!fromEnv) return { reason: REASONS.envHost };
428
+ }
429
+
430
+ let chosen;
431
+ let pair;
432
+ if (env.JIRA_TOKEN) {
433
+ chosen = fromEnv ?? global;
434
+ pair = { token: env.JIRA_TOKEN };
435
+ } else if (env.ACCOUNT_JIRA_TOKEN_KEY) {
436
+ const id = accountOfKey(env.ACCOUNT_JIRA_TOKEN_KEY);
437
+ if (!id) return { reason: REASONS.accountMismatch };
438
+ chosen = hostUrl(accounts.find((a) => a.id === id)?.jiraHost) ?? global;
439
+ if (fromEnv && !same(fromEnv, chosen)) return { reason: REASONS.accountMismatch };
440
+ pair = { tokenKey: env.ACCOUNT_JIRA_TOKEN_KEY };
441
+ } else {
442
+ if (fromEnv && !same(fromEnv, global)) return { reason: REASONS.accountMismatch };
443
+ chosen = global;
444
+ const key = prefs?.global?.keychainMapping?.jira;
445
+ pair = key ? { tokenKey: key } : {};
446
+ }
447
+ if (!chosen) return { reason: REASONS.noHost };
448
+ const { url, base } = chosen;
449
+ const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
450
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
451
+ return { reason: REASONS.insecureHost };
452
+ }
453
+ return { base, ...pair };
454
+ }
455
+
456
+ /**
457
+ * The environment gh runs with, or a reason not to run it. GH_HOST would send
458
+ * the comment and gh's token for that host elsewhere: an attended run refuses
459
+ * any value but github.com, a run that cannot ask drops the variable.
460
+ */
461
+ export function githubEnv(env, { unattended = isUnattended(env) } = {}) {
462
+ const out = { ...env };
463
+ const host = String(env.GH_HOST ?? "")
464
+ .trim()
465
+ .toLowerCase();
466
+ if (!host) return { env: out };
467
+ if (unattended) {
468
+ delete out.GH_HOST;
469
+ return { env: out };
470
+ }
471
+ return host === "github.com" ? { env: out } : { reason: REASONS.envHost };
472
+ }
473
+
474
+ function credentialStore(env) {
475
+ const home = env.HOME || homedir();
476
+ for (const c of [
477
+ join(HERE, "..", "lib", "credential-store.sh"),
478
+ join(home, ".claude", "lib", "credential-store.sh"),
479
+ ]) {
480
+ if (existsSync(c)) return c;
481
+ }
482
+ return null;
483
+ }
484
+
485
+ /**
486
+ * The token of the pair `jiraBase` chose: the caller's own value, or the
487
+ * credential store's entry under the paired key; never argv.
488
+ */
489
+ export async function jiraToken(pair, env, { store = credentialStore(env) } = {}) {
490
+ if (pair?.token) return pair.token;
491
+ const key = pair?.tokenKey;
492
+ if (!key || !store) return null;
493
+ const token = await new Promise((resolve) => {
494
+ execFile(
495
+ "bash",
496
+ [store, "get", key],
497
+ {
498
+ encoding: "utf8",
499
+ timeout: 10_000,
500
+ killSignal: "SIGKILL",
501
+ env: { PATH: process.env.PATH, ...env },
502
+ },
503
+ (err, stdout) => resolve(err ? "" : String(stdout || "").trim()),
504
+ );
505
+ });
506
+ return token || null;
507
+ }
508
+
509
+ function parseJiraAttachment(text) {
510
+ try {
511
+ const j = JSON.parse(text);
512
+ const a = Array.isArray(j) ? j[0] : null;
513
+ if (a && a.id != null) {
514
+ return { attachmentId: String(a.id), url: typeof a.content === "string" ? a.content : null };
515
+ }
516
+ } catch {
517
+ /* not JSON */
518
+ }
519
+ return null;
520
+ }
521
+
522
+ /** A request through curl, the token in a 0600 header file, never on argv. */
523
+ export function curlRequest({ method, url, token, file, filename }) {
524
+ const dir = mkdtempSync(join(tmpdir(), "plan-attach-"));
525
+ try {
526
+ const headers = join(dir, "headers");
527
+ writeFileSync(
528
+ headers,
529
+ `Authorization: Bearer ${token}\nX-Atlassian-Token: no-check\nAccept: application/json\n`,
530
+ { mode: 0o600 },
531
+ );
532
+ const upload = file ? ["-F", `file=@${file};type=text/markdown;filename=${filename}`] : [];
533
+ const r = spawnSync(
534
+ "curl",
535
+ [
536
+ "-sS",
537
+ "--max-time",
538
+ String(TIMEOUT_MS / 1000),
539
+ "-X",
540
+ method,
541
+ "-H",
542
+ `@${headers}`,
543
+ ...upload,
544
+ "-w",
545
+ "\n%{http_code}",
546
+ url,
547
+ ],
548
+ { encoding: "utf8", timeout: TIMEOUT_MS + 5000 },
549
+ );
550
+ if (r.error || r.status !== 0) return { failure: r.error?.code || `curl-exit-${r.status}` };
551
+ const out = String(r.stdout ?? "");
552
+ const cut = out.lastIndexOf("\n");
553
+ return { status: Number(out.slice(cut + 1)) || 0, body: out.slice(0, cut) };
554
+ } finally {
555
+ rmSync(dir, { recursive: true, force: true });
556
+ }
557
+ }
558
+
559
+ /** A multipart/form-data body holding one `file` part. */
560
+ export function multipart(filename, data) {
561
+ const boundary = `----plan-attachment-${randomBytes(12).toString("hex")}`;
562
+ const head =
563
+ `--${boundary}\r\n` +
564
+ `Content-Disposition: form-data; name="file"; filename="${filename}"\r\n` +
565
+ "Content-Type: text/markdown\r\n\r\n";
566
+ return {
567
+ type: `multipart/form-data; boundary=${boundary}`,
568
+ body: Buffer.concat([
569
+ Buffer.from(head),
570
+ Buffer.from(data),
571
+ Buffer.from(`\r\n--${boundary}--\r\n`),
572
+ ]),
573
+ };
574
+ }
575
+
576
+ const NOT_SENT_CODES = new Set([
577
+ "ECONNREFUSED",
578
+ "ENOTFOUND",
579
+ "EAI_AGAIN",
580
+ "EHOSTUNREACH",
581
+ "ENETUNREACH",
582
+ "UND_ERR_CONNECT_TIMEOUT",
583
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
584
+ "UNABLE_TO_GET_ISSUER_CERT",
585
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
586
+ "SELF_SIGNED_CERT_IN_CHAIN",
587
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
588
+ ]);
589
+
590
+ /**
591
+ * True only when fetch failed before the request left the machine: no
592
+ * connection (refused, DNS, unreachable, connect timeout) or a TLS handshake
593
+ * failure such as a corporate CA Node does not trust. A timeout, an abort or
594
+ * a socket error once connected may follow a request the server received.
595
+ */
596
+ export function failedBeforeSending(err) {
597
+ for (let e = err, depth = 0; e && depth < 4; e = e.cause, depth += 1) {
598
+ if (e.name === "TimeoutError" || e.name === "AbortError") return false;
599
+ const code = typeof e.code === "string" ? e.code : "";
600
+ if (NOT_SENT_CODES.has(code) || code.startsWith("CERT_") || code.startsWith("ERR_TLS_")) {
601
+ return true;
602
+ }
603
+ }
604
+ return false;
605
+ }
606
+
607
+ function failureName(err) {
608
+ for (let e = err, depth = 0; e && depth < 4; e = e.cause, depth += 1) {
609
+ if (e.name === "TimeoutError") return "timeout";
610
+ if (typeof e.code === "string" && e.code) return e.code;
611
+ }
612
+ return err?.name || "error";
613
+ }
614
+
615
+ /**
616
+ * One Jira request. fetch first; curl only when fetch is missing or failed
617
+ * before sending. Any other fetch failure comes back as `unknown`: the server
618
+ * may have acted on it, so it is not repeated.
619
+ */
620
+ async function jiraRequest({ method, url, token, file, filename, fetchImpl, curlImpl }) {
621
+ if (typeof fetchImpl === "function") {
622
+ try {
623
+ const form = file ? multipart(filename, readFileSync(file)) : null;
624
+ const r = await fetchImpl(url, {
625
+ method,
626
+ headers: {
627
+ Authorization: `Bearer ${token}`,
628
+ "X-Atlassian-Token": "no-check",
629
+ Accept: "application/json",
630
+ ...(form ? { "Content-Type": form.type } : {}),
631
+ },
632
+ ...(form ? { body: form.body } : {}),
633
+ redirect: "manual",
634
+ signal: AbortSignal.timeout(TIMEOUT_MS),
635
+ });
636
+ return { status: r.status, body: await r.text().catch(() => "") };
637
+ } catch (err) {
638
+ if (!failedBeforeSending(err)) return { failure: failureName(err), unknown: true };
639
+ }
640
+ }
641
+ return curlImpl({ method, url, token, file, filename });
642
+ }
643
+
644
+ const transportReason = (res) =>
645
+ `transport: ${res.failure}${res.unknown ? " (status unknown)" : ""}`;
646
+
647
+ /**
648
+ * The issue's attachments as `{id, filename, size, url}`, or a failed outcome.
649
+ */
650
+ export async function listJiraAttachments({
651
+ base,
652
+ key,
653
+ token,
654
+ fetchImpl = globalThis.fetch,
655
+ curlImpl = curlRequest,
656
+ }) {
657
+ const url = `${base}/rest/api/2/issue/${encodeURIComponent(key)}?fields=attachment`;
658
+ const res = await jiraRequest({ method: "GET", url, token, fetchImpl, curlImpl });
659
+ if (res.failure)
660
+ return { status: "failed", reason: `listing attachments, ${transportReason(res)}` };
661
+ if (res.status < 200 || res.status >= 300) return { status: "failed", httpStatus: res.status };
662
+ try {
663
+ const items = JSON.parse(res.body)?.fields?.attachment;
664
+ if (!Array.isArray(items)) throw new Error("no attachment list");
665
+ return {
666
+ attachments: items
667
+ .filter((a) => a && typeof a.filename === "string")
668
+ .map((a) => ({
669
+ id: a.id == null ? null : String(a.id),
670
+ filename: a.filename,
671
+ size: Number(a.size),
672
+ url: typeof a.content === "string" ? a.content : null,
673
+ })),
674
+ };
675
+ } catch {
676
+ return { status: "failed", httpStatus: res.status, reason: "unreadable Jira response" };
677
+ }
678
+ }
679
+
680
+ /** Upload one file as a Jira attachment; never sent twice by this call. */
681
+ export async function attachToJira({
682
+ base,
683
+ key,
684
+ token,
685
+ file,
686
+ filename,
687
+ fetchImpl = globalThis.fetch,
688
+ curlImpl = curlRequest,
689
+ }) {
690
+ const url = `${base}/rest/api/2/issue/${encodeURIComponent(key)}/attachments`;
691
+ const res = await jiraRequest({
692
+ method: "POST",
693
+ url,
694
+ token,
695
+ file,
696
+ filename,
697
+ fetchImpl,
698
+ curlImpl,
699
+ });
700
+ if (res.failure) return { status: "failed", reason: transportReason(res) };
701
+ if (res.status < 200 || res.status >= 300) return { status: "failed", httpStatus: res.status };
702
+ const a = parseJiraAttachment(res.body);
703
+ if (!a) return { status: "failed", httpStatus: res.status, reason: "unreadable Jira response" };
704
+ return { status: "attached", ...a };
705
+ }
706
+
707
+ function ghFailure(r, what) {
708
+ if (r.error) {
709
+ if (r.error.code === "ETIMEDOUT") return { reason: `${what}: timeout (status unknown)` };
710
+ return { reason: `${what}: ${r.error.code || "error"}` };
711
+ }
712
+ const m = /\(HTTP (\d{3})\)/.exec(String(r.stderr ?? ""));
713
+ return m
714
+ ? { httpStatus: Number(m[1]) }
715
+ : { reason: `${what}: gh exit ${r.status} (status unknown)` };
716
+ }
717
+
718
+ /**
719
+ * The issue comment carrying marker, `null` when there is none, or a failure.
720
+ * Every page is read, up to 5000 comments.
721
+ */
722
+ export function findGithubComment({
723
+ owner,
724
+ repo,
725
+ number,
726
+ marker,
727
+ gh = "gh",
728
+ env = process.env,
729
+ timeoutMs = TIMEOUT_MS,
730
+ }) {
731
+ for (let page = 1; page <= GITHUB_MAX_PAGES; page += 1) {
732
+ const r = spawnSync(
733
+ gh,
734
+ [
735
+ "api",
736
+ `repos/${owner}/${repo}/issues/${number}/comments?per_page=${GITHUB_PAGE}&page=${page}`,
737
+ ],
738
+ { encoding: "utf8", timeout: timeoutMs, env },
739
+ );
740
+ if (r.error || r.status !== 0) {
741
+ const f = ghFailure(r, "listing comments");
742
+ return { failure: f.reason ?? `listing comments: HTTP ${f.httpStatus}` };
743
+ }
744
+ let items;
745
+ try {
746
+ items = JSON.parse(r.stdout);
747
+ } catch {
748
+ return { failure: "listing comments: unreadable response" };
749
+ }
750
+ if (!Array.isArray(items)) return { failure: "listing comments: unreadable response" };
751
+ const hit = items.find((c) => typeof c?.body === "string" && c.body.includes(marker));
752
+ if (hit) {
753
+ return {
754
+ found: {
755
+ ...(hit.id != null ? { attachmentId: String(hit.id) } : {}),
756
+ ...(typeof hit.html_url === "string" ? { url: hit.html_url } : {}),
757
+ },
758
+ };
759
+ }
760
+ if (items.length < GITHUB_PAGE) return { found: null };
761
+ }
762
+ return { failure: "listing comments: more pages than read" };
763
+ }
764
+
765
+ /** One issue comment through `gh api`, the body read from a file; never retried. */
766
+ export function commentOnGithub({
767
+ owner,
768
+ repo,
769
+ number,
770
+ bodyFile,
771
+ gh = "gh",
772
+ env = process.env,
773
+ timeoutMs = TIMEOUT_MS,
774
+ }) {
775
+ const r = spawnSync(
776
+ gh,
777
+ [
778
+ "api",
779
+ "--method",
780
+ "POST",
781
+ `repos/${owner}/${repo}/issues/${number}/comments`,
782
+ "-F",
783
+ `body=@${bodyFile}`,
784
+ ],
785
+ { encoding: "utf8", timeout: timeoutMs, env },
786
+ );
787
+ if (r.error || r.status !== 0) return { status: "failed", ...ghFailure(r, "gh") };
788
+ try {
789
+ const j = JSON.parse(r.stdout);
790
+ return {
791
+ status: "attached",
792
+ attachmentId: String(j.id),
793
+ ...(typeof j.html_url === "string" ? { url: j.html_url } : {}),
794
+ };
795
+ } catch {
796
+ return { status: "attached" };
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Post the plan comment unless the issue already carries its marker. A failed
802
+ * listing posts nothing: the earlier comment may be there unseen.
803
+ */
804
+ export function postGithubPlan({ marker, ...target }) {
805
+ const listed = findGithubComment({ ...target, marker });
806
+ if (listed.failure) {
807
+ const unknown = listed.failure.includes("(status unknown)") ? "" : " (status unknown)";
808
+ return { status: "failed", reason: `${listed.failure}${unknown}` };
809
+ }
810
+ if (listed.found) return { status: "attached", ...listed.found, reason: "already on the issue" };
811
+ return commentOnGithub(target);
812
+ }
813
+
814
+ function readJson(path) {
815
+ try {
816
+ return JSON.parse(readFileSync(path, "utf8"));
817
+ } catch {
818
+ return null;
819
+ }
820
+ }
821
+
822
+ function loadPolicy() {
823
+ for (const p of [
824
+ join(HERE, "..", "schemas", "unattended-policy.json"),
825
+ join(HERE, "..", "pipeline", "schemas", "unattended-policy.json"),
826
+ ]) {
827
+ const j = readJson(p);
828
+ if (j) return j;
829
+ }
830
+ return null;
831
+ }
832
+
833
+ function writeState(statePath, patch) {
834
+ const r = spawnSync(process.execPath, [join(HERE, "write-state.mjs"), statePath], {
835
+ input: JSON.stringify(patch),
836
+ encoding: "utf8",
837
+ timeout: 30_000,
838
+ });
839
+ return r.status === 0;
840
+ }
841
+
842
+ const SAME_SKIP = ["status", "issue", "version", "reason"];
843
+
844
+ function record(statePath, state, outcome, extra = {}) {
845
+ const prior = list(state?.planAttachment?.outcomes);
846
+ const clean = Object.fromEntries(
847
+ Object.entries(outcome).filter(([, v]) => v !== undefined && v !== null),
848
+ );
849
+ const last = prior.at(-1);
850
+ if (clean.status === "skipped" && last && SAME_SKIP.every((k) => last[k] === clean[k])) {
851
+ return { ...clean, recorded: false };
852
+ }
853
+ const outcomes = [...prior, { ...clean, at: new Date().toISOString() }].slice(-MAX_OUTCOMES);
854
+ const answer = extra.answer ?? state?.planAttachment?.answer;
855
+ const planAttachment = { ...(answer ? { answer } : {}), outcomes };
856
+ const written = writeState(statePath, { planAttachment });
857
+ return { ...clean, recorded: written };
858
+ }
859
+
860
+ function targetLabel(t) {
861
+ if (!t) return "";
862
+ return t.kind === "jira" ? t.key : `${t.owner}/${t.repo}#${t.number}`;
863
+ }
864
+
865
+ /** The Phase 5 report line for the last outcome, or "" when there is none. */
866
+ export function reportLine(state) {
867
+ const last = list(state?.planAttachment?.outcomes).at(-1);
868
+ if (!last) return "";
869
+ const v = last.version ? `v${last.version} ` : "";
870
+ if (last.status === "attached") {
871
+ return `Plan: ${v}attached to ${last.issue ?? last.target}${last.url ? ` (${last.url})` : ""}`;
872
+ }
873
+ if (last.status === "failed") {
874
+ const why = last.httpStatus ? `HTTP ${last.httpStatus}` : (last.reason ?? "error");
875
+ return `Plan: ${v}upload failed (${why}), the run went on`;
876
+ }
877
+ const why = String(last.reason ?? "").replace(/^plan not attached: /, "");
878
+ return why ? `Plan: not attached (${why})` : "Plan: not attached";
879
+ }
880
+
881
+ async function upload({ statePath, planPath, answer, env }) {
882
+ const state = readJson(statePath) ?? {};
883
+ const prefs = loadPrefs(prefsPath(env), {});
884
+ const d = decide({ state, prefs, env, policy: loadPolicy(), answer });
885
+ if (d.action === "none") return { action: "none" };
886
+ const target = d.target;
887
+ const base = { target: target.kind, issue: targetLabel(target) };
888
+ const keepAnswer = answer ? { answer } : {};
889
+ const done = (outcome) => record(statePath, state, { ...base, ...outcome }, keepAnswer);
890
+ const skipped = (reason, extra = {}) => done({ status: "skipped", ...extra, reason });
891
+ if (d.action === "ask") return { action: "ask", ...base };
892
+ if (d.action === "skip") return skipped(d.reason);
893
+
894
+ const plan = planPath ? readJson(planPath) : null;
895
+ if (!plan || !Array.isArray(plan.tasks)) return skipped(REASONS.noPlan);
896
+ if (!planApproved(state, { planWrittenMs: statSync(planPath).mtimeMs })) {
897
+ return skipped(REASONS.notApproved);
898
+ }
899
+
900
+ const dir = join(dirname(statePath), "plan-attachments");
901
+ const stem = fileStem(state.taskId);
902
+ const latest = existingVersions(dir, stem).at(-1);
903
+ const approvedAt = approvalLabel(state);
904
+ const render = (n) => renderPlanMarkdown({ plan, state, version: n, approvedAt });
905
+
906
+ let version = (latest?.version ?? 0) + 1;
907
+ if (latest) {
908
+ const same = readFileSync(join(dir, latest.name), "utf8") === render(latest.version);
909
+ if (same) {
910
+ const prev = list(state?.planAttachment?.outcomes).findLast(
911
+ (o) => o.version === latest.version && o.issue === base.issue,
912
+ );
913
+ if (prev?.status === "attached") {
914
+ return { status: "unchanged", ...base, version: latest.version, recorded: false };
915
+ }
916
+ version = latest.version;
917
+ }
918
+ }
919
+ const scanned = (n) => {
920
+ const findings = secretFindings(render(n));
921
+ return findings.length
922
+ ? `plan not attached: the secret scan matched ${findings.join(", ")}`
923
+ : null;
924
+ };
925
+ const leak = scanned(version);
926
+ if (leak) return skipped(leak, { version });
927
+
928
+ const unattended = isUnattended(env) || state?.autopilot === true;
929
+ if (target.kind === "jira") {
930
+ if (!JIRA_KEY.test(target.key)) return skipped(REASONS.badIssue, { version });
931
+ const host = jiraBase(env, prefs);
932
+ if (host.reason) return skipped(host.reason, { version });
933
+ const token = await jiraToken(host, env);
934
+ if (!token) return skipped(REASONS.noToken, { version });
935
+ const conn = { base: host.base, key: target.key, token };
936
+
937
+ const listed = await listJiraAttachments(conn);
938
+ if (listed.status === "failed") {
939
+ const { status, ...why } = listed;
940
+ return done({ status, version, ...why });
941
+ }
942
+ const onIssue = listed.attachments;
943
+ const nameOf = (n) => `plan-${stem}-v${n}.md`;
944
+ const bytes = (n) => Buffer.byteLength(render(n));
945
+ const match = onIssue.find((a) => a.filename === nameOf(version));
946
+ if (match && match.size === bytes(version)) {
947
+ mkdirSafe(dir);
948
+ writeFileSafe(join(dir, nameOf(version)), render(version));
949
+ return done({
950
+ status: "attached",
951
+ version,
952
+ file: join(dir, nameOf(version)),
953
+ ...(match.id ? { attachmentId: match.id } : {}),
954
+ ...(match.url ? { url: match.url } : {}),
955
+ reason: "already on the issue",
956
+ });
957
+ }
958
+ if (match) {
959
+ const taken =
960
+ versionsOf(
961
+ onIssue.map((a) => a.filename),
962
+ stem,
963
+ ).at(-1)?.version ?? version;
964
+ version = Math.max(taken, version) + 1;
965
+ const again = scanned(version);
966
+ if (again) return skipped(again, { version });
967
+ }
968
+ mkdirSafe(dir);
969
+ const filename = nameOf(version);
970
+ const file = join(dir, filename);
971
+ writeFileSafe(file, render(version));
972
+ const r = await attachToJira({ ...conn, file, filename });
973
+ return done({ version, file, ...r });
974
+ }
975
+
976
+ const ownerRepo = `${target.owner}/${target.repo}`;
977
+ if (!GH_OWNER_REPO.test(ownerRepo) || !/^[1-9][0-9]{0,8}$/.test(String(target.number))) {
978
+ return skipped(REASONS.badIssue, { version });
979
+ }
980
+ const gh = githubEnv(env, { unattended });
981
+ if (gh.reason) return skipped(gh.reason, { version });
982
+ const markdown = render(version);
983
+ const marker = planMarker({ stem, version, markdown });
984
+ const body = githubCommentBody({
985
+ markdown,
986
+ version,
987
+ taskCount: plan.tasks.length,
988
+ approvedAt,
989
+ marker,
990
+ });
991
+ const bodyFindings = secretFindings(body);
992
+ if (bodyFindings.length) {
993
+ const reason = `plan not attached: the secret scan matched ${bodyFindings.join(", ")}`;
994
+ return skipped(reason, { version });
995
+ }
996
+ if (body.length > GITHUB_COMMENT_MAX) return skipped(REASONS.tooLarge, { version });
997
+ mkdirSafe(dir);
998
+ const filename = `plan-${stem}-v${version}.md`;
999
+ const file = join(dir, filename);
1000
+ writeFileSafe(file, markdown);
1001
+ const bodyFile = join(dir, `${basename(filename, ".md")}.comment.md`);
1002
+ writeFileSafe(bodyFile, body);
1003
+ const r = postGithubPlan({
1004
+ owner: target.owner,
1005
+ repo: target.repo,
1006
+ number: target.number,
1007
+ bodyFile,
1008
+ marker,
1009
+ env: gh.env,
1010
+ });
1011
+ return done({ version, file, ...r });
1012
+ }
1013
+
1014
+ function usage(msg) {
1015
+ process.stderr.write(`plan-attachment: ${msg}\n`);
1016
+ return 2;
1017
+ }
1018
+
1019
+ export async function main(argv, env = process.env) {
1020
+ const [sub, ...rest] = argv;
1021
+ if (!["decide", "upload", "line"].includes(sub)) {
1022
+ return usage("expected decide, upload or line");
1023
+ }
1024
+ const opts = {};
1025
+ try {
1026
+ parseArgs(rest, {
1027
+ strings: ["state", "plan", "answer"],
1028
+ unknown: "error",
1029
+ positionals: false,
1030
+ onArg: ({ flag, value }) => {
1031
+ opts[flag] = value;
1032
+ },
1033
+ });
1034
+ } catch (err) {
1035
+ if (!(err instanceof ArgsError)) throw err;
1036
+ return usage(`unexpected argument ${err.token}`);
1037
+ }
1038
+ if (!opts.state) return usage("--state is required");
1039
+ if (opts.answer !== undefined && !["yes", "no"].includes(opts.answer)) {
1040
+ return usage("--answer takes yes or no");
1041
+ }
1042
+ if (sub === "line") {
1043
+ const line = reportLine(readJson(opts.state));
1044
+ if (line) process.stdout.write(`${line}\n`);
1045
+ return 0;
1046
+ }
1047
+ if (sub === "decide") {
1048
+ const state = readJson(opts.state) ?? {};
1049
+ const prefs = loadPrefs(prefsPath(env), {});
1050
+ const d = decide({ state, prefs, env, policy: loadPolicy(), answer: opts.answer });
1051
+ let out = { action: d.action, ...(d.target ? { issue: targetLabel(d.target) } : {}) };
1052
+ if (d.action === "skip") {
1053
+ out = record(
1054
+ opts.state,
1055
+ state,
1056
+ {
1057
+ status: "skipped",
1058
+ target: d.target.kind,
1059
+ issue: targetLabel(d.target),
1060
+ reason: d.reason,
1061
+ },
1062
+ opts.answer ? { answer: opts.answer } : {},
1063
+ );
1064
+ out.action = "skip";
1065
+ }
1066
+ process.stdout.write(`${JSON.stringify(out)}\n`);
1067
+ return 0;
1068
+ }
1069
+ if (!opts.plan) return usage("upload needs --plan");
1070
+ let result;
1071
+ try {
1072
+ result = await upload({ statePath: opts.state, planPath: opts.plan, answer: opts.answer, env });
1073
+ } catch (err) {
1074
+ result = { status: "failed", reason: `internal: ${err?.code || err?.name || "error"}` };
1075
+ }
1076
+ process.stdout.write(`${JSON.stringify(result)}\n`);
1077
+ return 0;
1078
+ }
1079
+
1080
+ if (invokedDirectly(import.meta.url)) {
1081
+ main(process.argv.slice(2)).then((code) => process.exit(code));
1082
+ }