@1aboveio/engineering-skills 0.0.0-stage → 0.1.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 (233) hide show
  1. package/README.md +28 -2
  2. package/package.json +33 -4
  3. package/skills/better-review/LICENSE +3 -0
  4. package/skills/better-review/SKILL.md +249 -0
  5. package/skills/better-review/agents/openai.yaml +9 -0
  6. package/skills/better-review/references/domain-hazards.md +53 -0
  7. package/skills/better-review/references/passes.md +147 -0
  8. package/skills/better-review/references/result.md +151 -0
  9. package/skills/better-review/release-check.mjs +93 -0
  10. package/skills/better-review/scripts/pr-context.mjs +212 -0
  11. package/skills/better-review/scripts/pr-context.test.mjs +168 -0
  12. package/skills/better-review/scripts/rereview-scope.mjs +503 -0
  13. package/skills/better-review/scripts/rereview-scope.test.mjs +587 -0
  14. package/skills/better-review/scripts/scan-diff.mjs +365 -0
  15. package/skills/better-review/scripts/scan-diff.test.mjs +414 -0
  16. package/skills/better-review/scripts/vendor-sync.test.mjs +96 -0
  17. package/skills/e2e-test/LICENSE +3 -0
  18. package/skills/e2e-test/SKILL.md +98 -0
  19. package/skills/e2e-test/assets/ci-gates.cloudbuild.yaml +24 -0
  20. package/skills/e2e-test/references/authoring/auth-flows.md +159 -0
  21. package/skills/e2e-test/references/authoring/playwright-config.md +73 -0
  22. package/skills/e2e-test/references/authoring/playwright-patterns.md +144 -0
  23. package/skills/e2e-test/references/ci-integration.md +25 -0
  24. package/skills/e2e-test/references/ci-playwright-container.md +290 -0
  25. package/skills/e2e-test/references/presentation-sweep.md +104 -0
  26. package/skills/e2e-test/references/reviewing.md +41 -0
  27. package/skills/e2e-test/references/route-manifest.md +51 -0
  28. package/skills/e2e-test/release-check.mjs +93 -0
  29. package/skills/e2e-test/scripts/detect-routes-nextjs.mjs +200 -0
  30. package/skills/e2e-test/scripts/presentation-checks.mjs +171 -0
  31. package/skills/e2e-test/scripts/presentation-checks.test.mjs +106 -0
  32. package/skills/e2e-test/scripts/presentation-perceivability.mjs +179 -0
  33. package/skills/e2e-test/scripts/presentation-perceivability.test.mjs +117 -0
  34. package/skills/e2e-test/scripts/presentation-reachability.mjs +154 -0
  35. package/skills/e2e-test/scripts/presentation-reachability.test.mjs +69 -0
  36. package/skills/e2e-test/scripts/presentation-render-health.mjs +141 -0
  37. package/skills/e2e-test/scripts/presentation-render-health.test.mjs +98 -0
  38. package/skills/e2e-test/scripts/presentation-sweep.mjs +147 -0
  39. package/skills/e2e-test/scripts/presentation-sweep.test.mjs +71 -0
  40. package/skills/e2e-test/scripts/presentation-temporal.mjs +127 -0
  41. package/skills/e2e-test/scripts/presentation-temporal.test.mjs +59 -0
  42. package/skills/e2e-test/scripts/project-route-manifest.mjs +82 -0
  43. package/skills/e2e-test/scripts/project-route-manifest.test.mjs +76 -0
  44. package/skills/e2e-test/scripts/validate-manifest.mjs +106 -0
  45. package/skills/engineering-runtime/LICENSE +3 -0
  46. package/skills/engineering-runtime/SKILL.md +11 -0
  47. package/skills/engineering-runtime/agents/openai.yaml +6 -0
  48. package/skills/engineering-runtime/coherence/workflow.json +597 -0
  49. package/skills/engineering-runtime/engineering-runtime.test.mjs +68 -0
  50. package/skills/engineering-runtime/release-check.mjs +93 -0
  51. package/skills/engineering-runtime/scripts/exact-head-artifact.mjs +131 -0
  52. package/skills/engineering-runtime/scripts/head-check-set.mjs +398 -0
  53. package/skills/engineering-runtime/scripts/invocation-policy.mjs +187 -0
  54. package/skills/engineering-runtime/scripts/invocation-policy.test.mjs +95 -0
  55. package/skills/engineering-runtime/scripts/main-module.mjs +79 -0
  56. package/skills/engineering-runtime/scripts/main-module.test.mjs +288 -0
  57. package/skills/engineering-runtime/scripts/mergify-yaml.mjs +11 -0
  58. package/skills/engineering-runtime/scripts/package-lock.json +43 -0
  59. package/skills/engineering-runtime/scripts/package.json +10 -0
  60. package/skills/engineering-runtime/scripts/required-check-plan.mjs +223 -0
  61. package/skills/engineering-runtime/scripts/required-check-plan.test.mjs +96 -0
  62. package/skills/engineering-runtime/scripts/review-completion.mjs +56 -0
  63. package/skills/engineering-runtime/scripts/workflow-coherence.mjs +595 -0
  64. package/skills/engineering-runtime/scripts/workflow-policy.mjs +189 -0
  65. package/skills/engineering-runtime/scripts/yaml-mapping.mjs +18 -0
  66. package/skills/ensure-coverage/LICENSE +3 -0
  67. package/skills/ensure-coverage/SKILL.md +129 -0
  68. package/skills/ensure-coverage/references/breadth/coverage-ledger.md +92 -0
  69. package/skills/ensure-coverage/references/breadth/inventory-contract.md +85 -0
  70. package/skills/ensure-coverage/references/breadth/surface-baseline.md +44 -0
  71. package/skills/ensure-coverage/references/breadth/surface-discovery.md +16 -0
  72. package/skills/ensure-coverage/references/depth/characterization.md +68 -0
  73. package/skills/ensure-coverage/references/depth/coverage.config.example.json +19 -0
  74. package/skills/ensure-coverage/references/depth/grading.md +35 -0
  75. package/skills/ensure-coverage/references/depth/mock-policy.md +57 -0
  76. package/skills/ensure-coverage/references/depth/test-smells.md +39 -0
  77. package/skills/ensure-coverage/references/enforcement/ci-contract.md +44 -0
  78. package/skills/ensure-coverage/references/examples/coverage-ledger.md +110 -0
  79. package/skills/ensure-coverage/references/examples/refund-flow.md +35 -0
  80. package/skills/ensure-coverage/references/presentation/axis.md +64 -0
  81. package/skills/ensure-coverage/references/process/audit-mode.md +27 -0
  82. package/skills/ensure-coverage/references/process/output-template.md +139 -0
  83. package/skills/ensure-coverage/references/process/test-strategy.md +56 -0
  84. package/skills/ensure-coverage/release-check.mjs +93 -0
  85. package/skills/ensure-coverage/schemas/coverage-config.schema.json +67 -0
  86. package/skills/ensure-coverage/schemas/coverage-file.schema.json +140 -0
  87. package/skills/ensure-coverage/scripts/README.md +99 -0
  88. package/skills/ensure-coverage/scripts/adapters/nextjs-inventory.mjs +182 -0
  89. package/skills/ensure-coverage/scripts/adapters/nextjs-inventory.test.mjs +96 -0
  90. package/skills/ensure-coverage/scripts/check-quarantine-expiry.mjs +105 -0
  91. package/skills/ensure-coverage/scripts/check-quarantine-expiry.test.mjs +47 -0
  92. package/skills/ensure-coverage/scripts/ci-audit.mjs +137 -0
  93. package/skills/ensure-coverage/scripts/ci-audit.test.mjs +86 -0
  94. package/skills/ensure-coverage/scripts/coverage-ledger.mjs +674 -0
  95. package/skills/ensure-coverage/scripts/coverage-ledger.test.mjs +447 -0
  96. package/skills/ensure-coverage/scripts/design-parity.mjs +591 -0
  97. package/skills/ensure-coverage/scripts/design-parity.test.mjs +552 -0
  98. package/skills/ensure-coverage/scripts/lint-tests.mjs +282 -0
  99. package/skills/ensure-coverage/scripts/lint-tests.test.mjs +289 -0
  100. package/skills/ensure-coverage/scripts/mock-policy-config.mjs +176 -0
  101. package/skills/ensure-coverage/scripts/mock-policy-config.test.mjs +119 -0
  102. package/skills/ensure-coverage/scripts/package.json +19 -0
  103. package/skills/golden-path/LICENSE +3 -0
  104. package/skills/golden-path/SKILL.md +230 -0
  105. package/skills/golden-path/agents/openai.yaml +3 -0
  106. package/skills/golden-path/assets/golden-paths.example.json +57 -0
  107. package/skills/golden-path/references/contract.md +239 -0
  108. package/skills/golden-path/references/migration.md +111 -0
  109. package/skills/golden-path/release-check.mjs +93 -0
  110. package/skills/golden-path/scripts/golden-path-core.mjs +1779 -0
  111. package/skills/golden-path/scripts/golden-path.mjs +6 -0
  112. package/skills/golden-path/scripts/golden-path.test.mjs +1457 -0
  113. package/skills/harness-runtime/LICENSE +3 -0
  114. package/skills/harness-runtime/SKILL.md +19 -0
  115. package/skills/harness-runtime/agents/openai.yaml +6 -0
  116. package/skills/harness-runtime/bin/discover-models.mjs +4 -0
  117. package/skills/harness-runtime/bin/model-catalog.mjs +4 -0
  118. package/skills/harness-runtime/contracts.md +15 -0
  119. package/skills/harness-runtime/discover-models.mjs +392 -0
  120. package/skills/harness-runtime/discover-models.test.mjs +363 -0
  121. package/skills/harness-runtime/fixtures/native-question-schemas.json +33 -0
  122. package/skills/harness-runtime/fixtures/question-responses.json +54 -0
  123. package/skills/harness-runtime/harness-runtime.test.mjs +967 -0
  124. package/skills/harness-runtime/index.mjs +767 -0
  125. package/skills/harness-runtime/model-catalog-seed.test.mjs +829 -0
  126. package/skills/harness-runtime/model-catalog.mjs +787 -0
  127. package/skills/harness-runtime/model-catalog.test.mjs +366 -0
  128. package/skills/harness-runtime/native-question-contracts.md +37 -0
  129. package/skills/harness-runtime/references/model-catalog-seed.json +408 -0
  130. package/skills/harness-runtime/references/model-catalog.md +57 -0
  131. package/skills/harness-runtime/release-check.mjs +93 -0
  132. package/skills/resolve-issues/LICENSE +3 -0
  133. package/skills/resolve-issues/SKILL.md +250 -0
  134. package/skills/resolve-issues/agents/openai.yaml +9 -0
  135. package/skills/resolve-issues/plugin-hooks.json +17 -0
  136. package/skills/resolve-issues/references/canary.md +28 -0
  137. package/skills/resolve-issues/references/ci.md +105 -0
  138. package/skills/resolve-issues/references/done.md +25 -0
  139. package/skills/resolve-issues/references/dropbox.md +90 -0
  140. package/skills/resolve-issues/references/expire.md +318 -0
  141. package/skills/resolve-issues/references/exploration.md +202 -0
  142. package/skills/resolve-issues/references/implementation.md +303 -0
  143. package/skills/resolve-issues/references/preflight.md +445 -0
  144. package/skills/resolve-issues/references/review.md +228 -0
  145. package/skills/resolve-issues/references/shared-modules.md +44 -0
  146. package/skills/resolve-issues/references/task-plan.md +264 -0
  147. package/skills/resolve-issues/release-check.mjs +93 -0
  148. package/skills/resolve-issues/scripts/cleanup-runs.mjs +364 -0
  149. package/skills/resolve-issues/scripts/cleanup-runs.test.mjs +280 -0
  150. package/skills/resolve-issues/scripts/discover-models.mjs +9 -0
  151. package/skills/resolve-issues/scripts/dropbox.mjs +473 -0
  152. package/skills/resolve-issues/scripts/dropbox.test.mjs +346 -0
  153. package/skills/resolve-issues/scripts/findings-reuse.mjs +98 -0
  154. package/skills/resolve-issues/scripts/findings-reuse.test.mjs +88 -0
  155. package/skills/resolve-issues/scripts/github-reviews.mjs +384 -0
  156. package/skills/resolve-issues/scripts/github-reviews.test.mjs +264 -0
  157. package/skills/resolve-issues/scripts/install-hooks.mjs +135 -0
  158. package/skills/resolve-issues/scripts/install-hooks.test.mjs +79 -0
  159. package/skills/resolve-issues/scripts/issue-tree.mjs +162 -0
  160. package/skills/resolve-issues/scripts/issue-tree.test.mjs +107 -0
  161. package/skills/resolve-issues/scripts/manual-invocation.test.mjs +14 -0
  162. package/skills/resolve-issues/scripts/model-catalog.mjs +9 -0
  163. package/skills/resolve-issues/scripts/next-actions-capacity.test.mjs +149 -0
  164. package/skills/resolve-issues/scripts/next-actions.mjs +856 -0
  165. package/skills/resolve-issues/scripts/next-actions.test.mjs +915 -0
  166. package/skills/resolve-issues/scripts/plan-sync.mjs +269 -0
  167. package/skills/resolve-issues/scripts/plan-sync.test.mjs +156 -0
  168. package/skills/resolve-issues/scripts/preflight-models.mjs +736 -0
  169. package/skills/resolve-issues/scripts/preflight-models.test.mjs +448 -0
  170. package/skills/resolve-issues/scripts/ready-check.mjs +185 -0
  171. package/skills/resolve-issues/scripts/ready-check.test.mjs +217 -0
  172. package/skills/resolve-issues/scripts/rehydrate.mjs +98 -0
  173. package/skills/resolve-issues/scripts/rehydrate.test.mjs +91 -0
  174. package/skills/resolve-issues/scripts/review-verdict.mjs +509 -0
  175. package/skills/resolve-issues/scripts/review-verdict.test.mjs +1060 -0
  176. package/skills/resolve-issues/scripts/size-check.mjs +492 -0
  177. package/skills/resolve-issues/scripts/size-check.test.mjs +458 -0
  178. package/skills/resolve-release/LICENSE +3 -0
  179. package/skills/resolve-release/SKILL.md +215 -0
  180. package/skills/resolve-release/agents/openai.yaml +8 -0
  181. package/skills/resolve-release/flows/cloud-run-canary.md +13 -0
  182. package/skills/resolve-release/flows/cloud-run.md +7 -0
  183. package/skills/resolve-release/flows/root-tag-npm.md +13 -0
  184. package/skills/resolve-release/flows/workspace-npm.md +22 -0
  185. package/skills/resolve-release/references/canary.md +51 -0
  186. package/skills/resolve-release/references/candidate.md +41 -0
  187. package/skills/resolve-release/references/cut.md +131 -0
  188. package/skills/resolve-release/references/dark-launch.md +66 -0
  189. package/skills/resolve-release/references/flows.md +150 -0
  190. package/skills/resolve-release/references/preflight.md +154 -0
  191. package/skills/resolve-release/references/prepared-metadata.md +260 -0
  192. package/skills/resolve-release/references/promotion.md +82 -0
  193. package/skills/resolve-release/references/publish.md +232 -0
  194. package/skills/resolve-release/references/workspace-npm.md +103 -0
  195. package/skills/resolve-release/release-check.mjs +93 -0
  196. package/skills/resolve-release/scripts/apply.mjs +212 -0
  197. package/skills/resolve-release/scripts/apply.test.mjs +99 -0
  198. package/skills/resolve-release/scripts/dark-flags.mjs +134 -0
  199. package/skills/resolve-release/scripts/dark-flags.test.mjs +100 -0
  200. package/skills/resolve-release/scripts/flow.mjs +500 -0
  201. package/skills/resolve-release/scripts/flow.test.mjs +340 -0
  202. package/skills/resolve-release/scripts/green-head.mjs +231 -0
  203. package/skills/resolve-release/scripts/green-head.test.mjs +101 -0
  204. package/skills/resolve-release/scripts/npm-version-absence.mjs +138 -0
  205. package/skills/resolve-release/scripts/npm-version-absence.test.mjs +426 -0
  206. package/skills/resolve-release/scripts/plan-npm.test.mjs +659 -0
  207. package/skills/resolve-release/scripts/plan-toml-boundary.test.mjs +317 -0
  208. package/skills/resolve-release/scripts/plan-uv.test.mjs +291 -0
  209. package/skills/resolve-release/scripts/plan.mjs +806 -0
  210. package/skills/resolve-release/scripts/plan.test.mjs +428 -0
  211. package/skills/rush-issues/LICENSE +3 -0
  212. package/skills/rush-issues/SKILL.md +58 -0
  213. package/skills/rush-issues/agents/openai.yaml +8 -0
  214. package/skills/rush-issues/rehydrate.mjs +10 -0
  215. package/skills/rush-issues/release-check.mjs +93 -0
  216. package/skills/rush-release/LICENSE +3 -0
  217. package/skills/rush-release/SKILL.md +35 -0
  218. package/skills/rush-release/agents/openai.yaml +8 -0
  219. package/skills/rush-release/release-check.mjs +93 -0
  220. package/skills/test-quality/LICENSE +3 -0
  221. package/skills/test-quality/SKILL.md +79 -0
  222. package/skills/test-quality/references/audit.md +80 -0
  223. package/skills/test-quality/references/lint.md +24 -0
  224. package/skills/test-quality/references/principles.md +143 -0
  225. package/skills/test-quality/references/testing-conventions.md +9 -0
  226. package/skills/test-quality/release-check.mjs +93 -0
  227. package/skills/test-quality/scripts/lint-tests.mjs +574 -0
  228. package/skills/test-quality/scripts/lint-tests.test.mjs +591 -0
  229. package/skills/test-quality/scripts/mock-policy-config.mjs +176 -0
  230. package/skills/test-quality/scripts/mock-policy-config.test.mjs +119 -0
  231. package/skills/test-quality/scripts/persist-conventions-core.mjs +116 -0
  232. package/skills/test-quality/scripts/persist-conventions.mjs +17 -0
  233. package/skills/test-quality/scripts/persist-conventions.test.mjs +104 -0
@@ -0,0 +1,473 @@
1
+ #!/usr/bin/env node
2
+ // Collect a run's small, non-blocking problems in one file and post them as grouped issues
3
+ // after the main work is done.
4
+ //
5
+ // dropbox.mjs check --git <workspace> --base <ref> --file <path> [--line <n>]
6
+ // dropbox.mjs add --dropbox <run>/dropbox.json --unit <id> --source review|implementer
7
+ // --kind <kind> --file <path> [--line <n>] --summary <text> [--pr <url>]
8
+ // [--finding <id>] [--severity P2] [--blocks <#n|owner/name#n|url>]...
9
+ // [--decision] [--git <workspace> --base <ref>]
10
+ // dropbox.mjs from-review --dropbox <run>/dropbox.json --review <run>/reviews/<unit>-r<N>.json
11
+ // [--pr <url>] [--git <review clone> --base <ref>]
12
+ // dropbox.mjs plan --dropbox <run>/dropbox.json [--git <dir> --ref <origin/target>]
13
+ // dropbox.mjs post --dropbox <run>/dropbox.json --repo <owner/name> [--git <dir> --ref <origin/target>]
14
+ // [--only G1,G2 | --ids D3,D4] [--label ready-for-agent]
15
+ // dropbox.mjs mark --dropbox <run>/dropbox.json --id <D3> (--drop <reason> | --decision)
16
+ // dropbox.mjs pending --runs <repo>/.resolve-issues/rush
17
+ //
18
+ // check: is the location inside the unit's own change (lines the diff from the merge-base with
19
+ // --base adds or changes, working tree included; a file the diff adds counts whole; without
20
+ // --line, any change to the file counts)? Prints { inDiff, do }: `inDiff` true means fix it in this unit.
21
+ // add: append one entry; the coordinator is the only writer. An implementer entry inside the
22
+ // unit's diff is refused (`refused` in the output) because the unit caused it. A review entry inside the diff
23
+ // is kept and marked `inDiff`: the review loop never fixes P2. The same location, kind and
24
+ // summary (or, for a review, the same unit and finding id) is one entry. `--decision` records
25
+ // a question for the human: never posted, listed in the handback. Prints { id, duplicate, inDiff }.
26
+ // from-review: add every P2 in a review result that has no followUpUrl or dropboxId, and
27
+ // write the entry id back to the finding as `dropboxId`, so review-verdict.mjs sees it disposed.
28
+ // P3 is skipped: never added, never filed.
29
+ // The unit's diff is taken at the review's `head`, so the clone's checkout does not matter.
30
+ // plan: print the issues `post` would file. Entries group by parent PR, and entries on the
31
+ // same file with the same kind join one group across PRs. With --git and --ref, an entry whose
32
+ // file no longer exists at --ref is dropped.
33
+ // post: file each pending group as one issue labeled --label (default ready-for-agent). An entry
34
+ // already in an open issue (matched by its fingerprint marker) is not filed again. Writes each
35
+ // entry's `postedUrl` back. --only posts the named groups; --ids posts just those entries,
36
+ // grouped among themselves (file an urgent entry now). Decisions are never posted.
37
+ // mark: drop an entry (with the reason) or turn it into a decision, after routing it.
38
+ // pending: list runs whose dropbox still has unposted entries (decisions excluded: they are
39
+ // reported in their own run's handback). Prints { runs }: empty when none.
40
+ //
41
+ // Exit 0 whenever it ran and answered (the outcome is in the output); exit 2 for a bad command,
42
+ // an unreadable file, or a git or gh failure.
43
+
44
+ import { execFileSync } from 'node:child_process'
45
+ import { createHash } from 'node:crypto'
46
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
47
+ import { join } from 'node:path'
48
+
49
+ import { isMainModule } from '../../engineering-runtime/scripts/main-module.mjs'
50
+
51
+ export const DROPBOX_VERSION = 1
52
+ export const DEFAULT_LABEL = 'ready-for-agent'
53
+ export const KINDS = Object.freeze(['bug', 'test', 'docs', 'typing', 'refactor', 'ci', 'perf', 'other'])
54
+ export const SOURCES = Object.freeze(['review', 'implementer'])
55
+ const SUMMARY_MAX = 280
56
+ const MARKER = 'dropbox-fp'
57
+
58
+ export class DropboxError extends Error {}
59
+
60
+ const isText = (value) => typeof value === 'string' && value.trim() !== ''
61
+
62
+ // --- the unit's diff ---------------------------------------------------------------------
63
+
64
+ function realGit(dir, args) {
65
+ try {
66
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
67
+ } catch (error) {
68
+ throw new DropboxError(`git ${args[0]} failed in ${dir}: ${String(error.stderr || error.message).trim()}`)
69
+ }
70
+ }
71
+
72
+ // New-side line ranges from `git diff -U0` hunks; a pure deletion adds no lines.
73
+ export function changedRanges(diffText) {
74
+ const ranges = []
75
+ for (const m of diffText.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) {
76
+ const start = Number(m[1])
77
+ const count = m[2] === undefined ? 1 : Number(m[2])
78
+ if (count > 0) ranges.push([start, start + count - 1])
79
+ }
80
+ return ranges
81
+ }
82
+
83
+ // Without `head`, the working tree is compared, so an implementer's uncommitted work counts.
84
+ // A file the unit added or deleted counts whole. A file that exists neither at the merge-base nor
85
+ // in the unit is a wrong path, never "outside the diff".
86
+ export function inUnitDiff({ dir, base, head, file, line }, git = realGit) {
87
+ if (line !== undefined && !(Number.isSafeInteger(line) && line >= 1)) throw new DropboxError('--line must be a positive integer')
88
+ let mergeBase
89
+ try {
90
+ mergeBase = git(dir, ['merge-base', base, head ?? 'HEAD']).trim()
91
+ } catch (error) {
92
+ throw new DropboxError(`${error.message}\nFetch the PR head and the base into ${dir} first.`)
93
+ }
94
+ const range = head ? [mergeBase, head] : [mergeBase]
95
+ const status = git(dir, ['diff', '--name-status', ...range, '--', file]).trim()
96
+ if (!status) {
97
+ const exists = (rev) => { try { git(dir, ['cat-file', '-e', `${rev}:${file}`]); return true } catch { return false } }
98
+ if (!exists(mergeBase) && !exists(head ?? 'HEAD')) throw new DropboxError(`${file} exists neither at the merge-base nor in the unit; give a repository-relative path, without :line`)
99
+ return false
100
+ }
101
+ if (/^[AD]\s/.test(status) || line === undefined) return true
102
+ return changedRanges(git(dir, ['diff', '-U0', '--no-color', ...range, '--', file]))
103
+ .some(([from, to]) => line >= from && line <= to)
104
+ }
105
+
106
+ // --- the dropbox file ----------------------------------------------------------------------
107
+
108
+ export function emptyDropbox() {
109
+ return { version: DROPBOX_VERSION, entries: [] }
110
+ }
111
+
112
+ export function readDropbox(path) {
113
+ if (!existsSync(path)) return emptyDropbox()
114
+ let box
115
+ try {
116
+ box = JSON.parse(readFileSync(path, 'utf8'))
117
+ } catch (error) {
118
+ throw new DropboxError(`cannot read ${path}: ${error.message}`)
119
+ }
120
+ if (box?.version !== DROPBOX_VERSION || !Array.isArray(box.entries)) throw new DropboxError(`${path} is not a version ${DROPBOX_VERSION} dropbox`)
121
+ return box
122
+ }
123
+
124
+ const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`)
125
+
126
+ // Local absolute paths never reach a public issue.
127
+ export function sanitize(text) {
128
+ const clean = String(text).replace(/(?<![\w.~-])(?:\/Users|\/home|\/private\/tmp|\/tmp|[A-Z]:\\Users)[/\\][^\s`'")\]]+/g, '<local path>').replace(/\s+/g, ' ').trim()
129
+ return clean.length > SUMMARY_MAX ? `${clean.slice(0, SUMMARY_MAX - 1)}…` : clean
130
+ }
131
+
132
+ // Lines shift between runs, so the line is not part of what makes two entries the same problem.
133
+ export function fingerprint({ file, kind, summary }) {
134
+ const key = [file ?? '', kind, sanitize(summary).toLowerCase()].join('\u0000')
135
+ return createHash('sha256').update(key).digest('hex').slice(0, 12)
136
+ }
137
+
138
+ function validateEntry(input) {
139
+ const problems = []
140
+ if (!isText(input.unit)) problems.push('--unit is required')
141
+ if (!SOURCES.includes(input.source)) problems.push(`--source must be one of ${SOURCES.join(', ')}`)
142
+ if (!input.decision && !KINDS.includes(input.kind)) problems.push(`--kind must be one of ${KINDS.join(', ')}`)
143
+ if (!input.decision && !isText(input.file)) problems.push('--file is required: an entry an agent can fix names where it is')
144
+ if (isText(input.file) && (/^(?:\/|[A-Za-z]:[\\/]|~)/.test(input.file) || /:\d+$/.test(input.file))) problems.push('--file must be repository-relative, with the line in --line')
145
+ if (input.line !== undefined && !(Number.isSafeInteger(input.line) && input.line >= 1)) problems.push('--line must be a positive integer')
146
+ if (!isText(input.summary)) problems.push('--summary is required')
147
+ if (input.severity !== undefined && input.severity !== 'P2') problems.push('--severity must be P2; a P0/P1 never goes in the dropbox and a P3 is skipped')
148
+ if (problems.length) throw new DropboxError(problems.join('\n'))
149
+ }
150
+
151
+ // Adds one entry, or returns the existing one it duplicates. `inDiff` is computed by the
152
+ // caller (null when no workspace was given).
153
+ export function addEntry(box, input, inDiff = null) {
154
+ validateEntry(input)
155
+ if (input.source === 'implementer' && inDiff === true) {
156
+ return { refused: true, reason: 'inside the unit\'s own change: fix it in this unit' }
157
+ }
158
+ const entry = {
159
+ route: input.decision ? 'decision' : 'dropbox',
160
+ unit: input.unit,
161
+ source: input.source,
162
+ kind: input.decision ? 'decision' : input.kind,
163
+ file: input.file ?? null,
164
+ line: input.line ?? null,
165
+ summary: sanitize(input.summary),
166
+ pr: input.pr ?? null,
167
+ finding: input.finding ?? null,
168
+ severity: input.severity ?? null,
169
+ blocks: (input.blocks ?? []).map((ref) => (/^\d+$/.test(String(ref)) ? `#${ref}` : String(ref))),
170
+ inDiff,
171
+ }
172
+ entry.fingerprint = fingerprint(entry)
173
+ const same = box.entries.find((e) => e.fingerprint === entry.fingerprint
174
+ || (entry.finding && e.source === 'review' && e.unit === entry.unit && e.finding === entry.finding))
175
+ if (same) {
176
+ for (const ref of entry.blocks) if (!same.blocks.includes(ref)) same.blocks.push(ref)
177
+ return { id: same.id, duplicate: true, inDiff: same.inDiff }
178
+ }
179
+ entry.id = `D${box.entries.length + 1}`
180
+ entry.status = 'pending'
181
+ box.entries.push({ id: entry.id, ...entry })
182
+ return { id: entry.id, duplicate: false, inDiff }
183
+ }
184
+
185
+ // --- grouping and posting -----------------------------------------------------------------
186
+
187
+ // Groups by parent PR; the same file and kind join across PRs. A group's id follows its first
188
+ // entry's (D3 leads G3), so `plan` and `post` name the same group even after some are filed.
189
+ export function groupEntries(entries) {
190
+ const parent = entries.map((_, i) => i)
191
+ const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])))
192
+ const link = (keyOf) => {
193
+ const first = new Map()
194
+ entries.forEach((e, i) => {
195
+ const key = keyOf(e)
196
+ if (key === null) return
197
+ if (first.has(key)) parent[find(i)] = find(first.get(key))
198
+ else first.set(key, i)
199
+ })
200
+ }
201
+ link((e) => e.pr || null)
202
+ link((e) => (e.file ? `${e.file}\u0000${e.kind}` : null))
203
+ const groups = new Map()
204
+ entries.forEach((e, i) => {
205
+ const root = find(i)
206
+ if (!groups.has(root)) groups.set(root, [])
207
+ groups.get(root).push(e)
208
+ })
209
+ return [...groups.values()].map((members) => ({ id: members[0].id.replace(/^D/, 'G'), entries: members }))
210
+ }
211
+
212
+ const prRef = (url) => {
213
+ const m = String(url ?? '').match(/\/pull\/(\d+)/)
214
+ return m ? `#${m[1]}` : null
215
+ }
216
+ const issueRef = (ref) => {
217
+ const url = String(ref).match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/)
218
+ return url ? `${url[1]}#${url[2]}` : String(ref)
219
+ }
220
+
221
+ export function issueFor(group) {
222
+ const { entries } = group
223
+ const prs = [...new Set(entries.map((e) => prRef(e.pr)).filter(Boolean))]
224
+ const kinds = [...new Set(entries.map((e) => e.kind))]
225
+ const files = [...new Set(entries.map((e) => e.file))]
226
+ let title
227
+ if (entries.length === 1) title = entries[0].summary
228
+ else if (files.length === 1) title = `${entries.length} ${kinds.join('/')} follow-ups in ${files[0]}`
229
+ else if (prs.length === 1) title = `${entries.length} follow-ups from ${prs[0]}`
230
+ else title = `${entries.length} ${kinds.join('/')} follow-ups`
231
+ title = title.length > 120 ? `${title.slice(0, 119)}…` : title
232
+
233
+ const lines = ['Non-blocking problems found while delivering other work. Each is outside the change that found it, or a review note the review loop does not fix.', '']
234
+ for (const e of entries) {
235
+ const where = e.line ? `${e.file}:${e.line}` : e.file
236
+ const from = [prRef(e.pr) && `from ${prRef(e.pr)}`, e.finding && `finding ${e.finding}`, e.inDiff && 'added by that PR'].filter(Boolean).join(', ')
237
+ lines.push(`- [ ] \`${where}\` (${e.kind}) ${e.summary}${from ? ` (${from})` : ''}`)
238
+ }
239
+ const blocks = [...new Set(entries.flatMap((e) => e.blocks.map(issueRef)))]
240
+ if (blocks.length) lines.push('', ...blocks.map((ref) => `Blocks ${ref}`))
241
+ lines.push('', `<!-- ${entries.map((e) => `${MARKER}:${e.fingerprint}`).join(' ')} -->`)
242
+ return { title, body: lines.join('\n') }
243
+ }
244
+
245
+ // Entries still to post, after dropping those whose file is gone at `ref`.
246
+ export function planPost(box, { dir, ref } = {}, git = realGit) {
247
+ if (Boolean(dir) !== Boolean(ref)) throw new DropboxError('give --git and --ref together, or neither')
248
+ const dropped = []
249
+ for (const e of box.entries) {
250
+ if (e.status !== 'pending' || e.route !== 'dropbox' || !dir || !ref) continue
251
+ try {
252
+ git(dir, ['cat-file', '-e', `${ref}:${e.file}`])
253
+ } catch {
254
+ e.status = 'dropped'
255
+ e.reason = `${e.file} no longer exists at ${ref}`
256
+ dropped.push(e.id)
257
+ }
258
+ }
259
+ const pending = box.entries.filter((e) => e.status === 'pending' && e.route === 'dropbox')
260
+ const groups = groupEntries(pending).map((g) => ({ ...g, issue: issueFor(g) }))
261
+ const decisions = box.entries.filter((e) => e.route === 'decision')
262
+ return { groups, dropped, decisions }
263
+ }
264
+
265
+ function realGh(args, input) {
266
+ try {
267
+ return execFileSync('gh', args, { encoding: 'utf8', input, stdio: ['pipe', 'pipe', 'pipe'] })
268
+ } catch (error) {
269
+ throw new DropboxError(`gh ${args[0]} ${args[1] ?? ''} failed: ${String(error.stderr || error.message).trim()}`)
270
+ }
271
+ }
272
+
273
+ // Fingerprint -> URL of the open issue that already carries it.
274
+ // Read by label, not by search: GitHub search does not reliably match text inside a comment.
275
+ export function filedFingerprints(repo, label = DEFAULT_LABEL, gh = realGh) {
276
+ const issues = JSON.parse(gh(['issue', 'list', '-R', repo, '--state', 'open', '--label', label, '--limit', '1000', '--json', 'url,body']))
277
+ const filed = new Map()
278
+ const marker = new RegExp(`${MARKER}:([0-9a-f]{12})`, 'g')
279
+ for (const issue of issues) for (const m of String(issue.body ?? '').matchAll(marker)) filed.set(m[1], issue.url)
280
+ return filed
281
+ }
282
+
283
+ export function post(box, { repo, dir, ref, only, ids, label = DEFAULT_LABEL }, { gh = realGh, git = realGit } = {}) {
284
+ if (!/^[^/\s]+\/[^/\s]+$/.test(repo ?? '')) throw new DropboxError('--repo <owner/name> is required')
285
+ if (only && ids) throw new DropboxError('give --only or --ids, not both')
286
+ for (const id of ids ?? []) {
287
+ const e = box.entries.find((x) => x.id === id)
288
+ if (!e) throw new DropboxError(`no entry ${id}`)
289
+ if (e.route !== 'dropbox') throw new DropboxError(`${id} is a decision; decisions are reported in the handback, never posted`)
290
+ }
291
+ // Group ids are the ones `plan` printed: resolve --only before skipping filed entries.
292
+ const { groups: planned, dropped, decisions } = planPost(box, { dir, ref }, git)
293
+ for (const id of only ?? []) if (!planned.some((g) => g.id === id)) throw new DropboxError(`no group ${id}; run plan again`)
294
+ const chosen = ids ?? (only ? planned.filter((g) => only.includes(g.id)).flatMap((g) => g.entries.map((e) => e.id)) : null)
295
+ const filed = filedFingerprints(repo, label, gh)
296
+ const known = []
297
+ for (const e of box.entries) {
298
+ if (e.status === 'pending' && e.route === 'dropbox' && filed.has(e.fingerprint)) {
299
+ e.status = 'posted'
300
+ e.postedUrl = filed.get(e.fingerprint)
301
+ known.push(e.id)
302
+ }
303
+ }
304
+ const remaining = box.entries.filter((e) => e.status === 'pending' && e.route === 'dropbox' && (!chosen || chosen.includes(e.id)))
305
+ const groups = groupEntries(remaining).map((g) => ({ ...g, issue: issueFor(g) }))
306
+ const posted = []
307
+ for (const group of groups) {
308
+ const url = gh(['issue', 'create', '-R', repo, '--title', group.issue.title, '--label', label, '--body-file', '-'], group.issue.body).trim()
309
+ for (const e of group.entries) {
310
+ e.status = 'posted'
311
+ e.postedUrl = url
312
+ }
313
+ posted.push({ group: group.id, url, entries: group.entries.map((e) => e.id) })
314
+ }
315
+ return { posted, alreadyFiled: known, dropped, decisions: decisions.map(({ id, unit, summary }) => ({ id, unit, summary })) }
316
+ }
317
+
318
+ export function markEntry(box, { id, drop, decision }) {
319
+ const e = box.entries.find((x) => x.id === id)
320
+ if (!e) throw new DropboxError(`no entry ${id}`)
321
+ if (e.status === 'posted') throw new DropboxError(`${id} is already posted at ${e.postedUrl}`)
322
+ if (isText(drop) === Boolean(decision)) throw new DropboxError('mark needs --drop <reason> or --decision')
323
+ if (decision) e.route = 'decision'
324
+ else {
325
+ e.status = 'dropped'
326
+ e.reason = sanitize(drop)
327
+ }
328
+ return { id, status: e.status, route: e.route }
329
+ }
330
+
331
+ // --- review results -------------------------------------------------------------------------
332
+
333
+ export function fromReview(box, review, { pr, inDiffOf = () => null } = {}) {
334
+ const added = []
335
+ for (const f of Array.isArray(review?.findings) ? review.findings : []) {
336
+ if (f?.severity !== 'P2' || isText(f.followUpUrl) || isText(f.dropboxId)) continue
337
+ const input = {
338
+ unit: String(review.unit ?? ''),
339
+ source: 'review',
340
+ kind: KINDS.includes(f.kind) ? f.kind : kindOfPass(f.pass),
341
+ file: f.file,
342
+ line: Number.isSafeInteger(f.line) ? f.line : undefined,
343
+ summary: f.summary,
344
+ pr,
345
+ finding: f.id,
346
+ severity: f.severity,
347
+ }
348
+ const result = addEntry(box, input, isText(f.file) ? inDiffOf(f.file, input.line, review.head) : null)
349
+ f.dropboxId = result.id
350
+ added.push(result.id)
351
+ }
352
+ return added
353
+ }
354
+
355
+ function kindOfPass(pass) {
356
+ return { correctness: 'bug', tests: 'test', standards: 'refactor', spec: 'other' }[pass] ?? 'other'
357
+ }
358
+
359
+ // --- other runs -----------------------------------------------------------------------------
360
+
361
+ export function pendingRuns(runsDir) {
362
+ if (!existsSync(runsDir)) return []
363
+ const out = []
364
+ for (const entry of readdirSync(runsDir, { withFileTypes: true })) {
365
+ const path = join(runsDir, entry.name, 'dropbox.json')
366
+ if (!entry.isDirectory() || !existsSync(path)) continue
367
+ const box = readDropbox(path)
368
+ const pending = box.entries.filter((e) => e.status === 'pending' && e.route === 'dropbox')
369
+ if (pending.length) out.push({ run: entry.name, dropbox: path, pending: pending.length })
370
+ }
371
+ return out
372
+ }
373
+
374
+ // --- command line ---------------------------------------------------------------------------
375
+
376
+ const USAGE = 'usage: dropbox.mjs check|add|from-review|plan|post|mark|pending [options]; see the header'
377
+
378
+ export function parseArgs(argv) {
379
+ const [command, ...rest] = argv
380
+ const opts = { command, blocks: [] }
381
+ for (let i = 0; i < rest.length; i++) {
382
+ const flag = rest[i]
383
+ if (!flag.startsWith('--')) throw new DropboxError(USAGE)
384
+ const key = flag.slice(2)
385
+ if (key === 'decision') { opts.decision = true; continue }
386
+ const value = rest[++i]
387
+ if (value === undefined) throw new DropboxError(`${flag} needs a value`)
388
+ if (key === 'blocks') opts.blocks.push(value)
389
+ else opts[key] = value
390
+ }
391
+ if (opts.line !== undefined) opts.line = Number(opts.line)
392
+ if (opts.only !== undefined) opts.only = opts.only.split(',')
393
+ if (opts.ids !== undefined) opts.ids = opts.ids.split(',')
394
+ return opts
395
+ }
396
+
397
+ function need(opts, ...keys) {
398
+ const missing = keys.filter((k) => !isText(opts[k]))
399
+ if (missing.length) throw new DropboxError(`${opts.command} needs ${missing.map((k) => `--${k}`).join(', ')}`)
400
+ }
401
+
402
+ export function run(opts, deps = {}) {
403
+ const git = deps.git ?? realGit
404
+ const diffCheck = (file, line, head) => (opts.git && opts.base ? inUnitDiff({ dir: opts.git, base: opts.base, head, file, line }, git) : null)
405
+ switch (opts.command) {
406
+ case 'check': {
407
+ need(opts, 'git', 'base', 'file')
408
+ validateEntry({ unit: '-', source: 'implementer', kind: 'other', summary: '-', file: opts.file, line: opts.line })
409
+ const inside = inUnitDiff({ dir: opts.git, base: opts.base, file: opts.file, line: opts.line }, git)
410
+ return { out: { inDiff: inside, do: inside ? 'fix it in this unit' : 'outside this unit: it may go in the dropbox' } }
411
+ }
412
+ case 'add': {
413
+ need(opts, 'dropbox')
414
+ if (opts.source === 'implementer' && !opts.decision) need(opts, 'git', 'base')
415
+ const box = readDropbox(opts.dropbox)
416
+ const inDiff = opts.file ? diffCheck(opts.file, opts.line) : null
417
+ const result = addEntry(box, opts, inDiff)
418
+ if (result.refused) return { out: result }
419
+ writeJson(opts.dropbox, box)
420
+ return { out: result }
421
+ }
422
+ case 'from-review': {
423
+ need(opts, 'dropbox', 'review')
424
+ const box = readDropbox(opts.dropbox)
425
+ let review
426
+ try {
427
+ review = JSON.parse(readFileSync(opts.review, 'utf8'))
428
+ } catch (error) {
429
+ throw new DropboxError(`cannot read ${opts.review}: ${error.message}`)
430
+ }
431
+ const added = fromReview(box, review, { pr: opts.pr, inDiffOf: diffCheck })
432
+ writeJson(opts.dropbox, box)
433
+ writeJson(opts.review, review)
434
+ return { out: { added } }
435
+ }
436
+ case 'plan': {
437
+ need(opts, 'dropbox')
438
+ const box = readDropbox(opts.dropbox)
439
+ return { out: planPost(box, { dir: opts.git, ref: opts.ref }, git) }
440
+ }
441
+ case 'post': {
442
+ need(opts, 'dropbox', 'repo')
443
+ const box = readDropbox(opts.dropbox)
444
+ const result = post(box, { ...opts, dir: opts.git }, { gh: deps.gh ?? realGh, git })
445
+ writeJson(opts.dropbox, box)
446
+ return { out: result }
447
+ }
448
+ case 'mark': {
449
+ need(opts, 'dropbox', 'id')
450
+ const box = readDropbox(opts.dropbox)
451
+ const result = markEntry(box, opts)
452
+ writeJson(opts.dropbox, box)
453
+ return { out: result }
454
+ }
455
+ case 'pending': {
456
+ need(opts, 'runs')
457
+ const runs = pendingRuns(opts.runs)
458
+ return { out: { runs } }
459
+ }
460
+ default:
461
+ throw new DropboxError(USAGE)
462
+ }
463
+ }
464
+
465
+ if (isMainModule(import.meta.url)) {
466
+ try {
467
+ const { out } = run(parseArgs(process.argv.slice(2)))
468
+ process.stdout.write(`${JSON.stringify(out, null, 2)}\n`)
469
+ } catch (error) {
470
+ process.stderr.write(`${error instanceof DropboxError ? error.message : error.stack}\n`)
471
+ process.exitCode = 2
472
+ }
473
+ }