@plainconceptsplatform/agent-harness 3.3.0 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +454 -454
  3. package/cli/commands/join.js +259 -259
  4. package/cli/commands/migrate.js +310 -310
  5. package/cli/commands/shared.js +27 -27
  6. package/cli/commands/single.js +79 -79
  7. package/cli/commands/wizard.js +134 -134
  8. package/cli/fragments/ops-backlog/az.md +28 -28
  9. package/cli/fragments/ops-backlog/gh.md +28 -28
  10. package/cli/fragments/ops-backlog/jira.md +28 -28
  11. package/cli/fragments/ops-review/az.md +62 -62
  12. package/cli/fragments/ops-review/gh.md +51 -51
  13. package/cli/fragments/ops-review/gl.md +55 -55
  14. package/cli/fragments/ops-ship/gh.md +67 -67
  15. package/cli/fragments/ops-ship/gl.md +84 -84
  16. package/cli/index.js +116 -116
  17. package/cli/presets/clean.json +21 -21
  18. package/cli/presets/models.json +68 -68
  19. package/cli/presets/optimization.json +32 -32
  20. package/cli/presets/platforms.json +76 -76
  21. package/cli/presets/source.json +23 -23
  22. package/cli/steps/clean/index.js +120 -120
  23. package/cli/steps/copy/agents.js +120 -120
  24. package/cli/steps/copy/fullstack-engineer.js +89 -89
  25. package/cli/steps/copy/opencode-json.js +324 -324
  26. package/cli/steps/copy/skills.js +316 -307
  27. package/cli/steps/models/format.js +88 -88
  28. package/cli/steps/models/index.js +64 -64
  29. package/cli/steps/openspec/index.js +136 -136
  30. package/cli/steps/optimization/codegraph.js +141 -141
  31. package/cli/steps/optimization/detect.js +66 -66
  32. package/cli/steps/optimization/humanizer.js +17 -17
  33. package/cli/steps/optimization/index.js +158 -158
  34. package/cli/steps/optimization/memory.js +91 -91
  35. package/cli/steps/optimization/patch-guardrails.js +111 -111
  36. package/cli/steps/optimization/simple-english.js +17 -17
  37. package/cli/steps/optimization/skills-lock.js +30 -30
  38. package/cli/steps/platform/index.js +109 -109
  39. package/cli/steps/source/index.js +123 -123
  40. package/cli/utils/agent-color.js +111 -111
  41. package/cli/utils/copy.js +134 -134
  42. package/cli/utils/exec-spinner.js +47 -47
  43. package/cli/utils/exec.js +134 -134
  44. package/cli/utils/legacy-check.js +30 -30
  45. package/cli/utils/models-cache.js +58 -58
  46. package/cli/utils/models-pricing.js +42 -42
  47. package/cli/utils/paths.js +81 -80
  48. package/cli/utils/process.js +3 -3
  49. package/cli/utils/terminal.js +6 -6
  50. package/cli/utils/update-manifest.js +75 -75
  51. package/harness/.opencode/_gitignore +10 -9
  52. package/harness/.opencode/commands/ops-backlog.md +10 -10
  53. package/harness/.opencode/commands/ops-review.md +10 -8
  54. package/harness/.opencode/commands/ops-ship.md +9 -9
  55. package/harness/.opencode/commands/plan-archive.md +7 -5
  56. package/harness/.opencode/commands/plan-explore.md +11 -9
  57. package/harness/.opencode/commands/plan-propose.md +11 -9
  58. package/harness/.opencode/commands/plan-quick.md +7 -5
  59. package/harness/.opencode/commands/plan-story.md +11 -9
  60. package/harness/.opencode/commands/repo-audit.md +7 -5
  61. package/harness/.opencode/commands/repo-help.md +5 -5
  62. package/harness/.opencode/package.json +5 -5
  63. package/harness/.opencode/plugins/pc-subagent-monitor.js +184 -184
  64. package/harness/.opencode/plugins/pc-subagent-tiers.js +367 -354
  65. package/harness/.opencode/plugins/pc-system-reminders.js +386 -386
  66. package/harness/.opencode/scripts/check-diff.mjs +244 -244
  67. package/harness/.opencode/scripts/code-rules.mjs +288 -288
  68. package/harness/ARCHITECTURE.md +13 -13
  69. package/harness/DESIGN.md +13 -13
  70. package/harness/opencode.jsonc +36 -36
  71. package/harness/openspec/config.yaml +20 -20
  72. package/harness/skills-lock.json +17 -17
  73. package/package.json +12 -14
  74. package/skills/agent-harness-cli/SKILL.md +86 -86
  75. package/skills/pc-guardrails-generic/SKILL.md +53 -53
  76. package/skills/pc-guardrails-project/SKILL.md +8 -8
  77. package/skills/pc-make-architecture/structure-template.md +64 -64
  78. package/skills/pc-make-engineer/SKILL.md +59 -59
  79. package/skills/pc-make-engineer/template.md +36 -36
  80. package/skills/pc-make-guardrails/category-reference.md +112 -112
  81. package/skills/pc-make-merge-risk-assess/SKILL.md +70 -70
  82. package/skills/pc-make-merge-risk-assess/category-reference.md +114 -114
  83. package/skills/pc-ops-ship/SKILL.md +22 -22
  84. package/skills/pc-plan-apply/SKILL.md +86 -86
  85. package/skills/pc-plan-apply/simple-mode.md +21 -21
  86. package/skills/pc-plan-explore/SKILL.md +21 -21
  87. package/skills/pc-plan-goal/SKILL.md +91 -91
  88. package/skills/pc-plan-goal/failure-policy.md +30 -30
  89. package/skills/pc-plan-goal/output-mode.md +10 -10
  90. package/skills/pc-plan-propose/SKILL.md +125 -125
  91. package/skills/pc-plan-propose/task-annotation.md +39 -39
  92. package/skills/pc-plan-quick/SKILL.md +46 -46
  93. package/skills/pc-repo-audit/SKILL.md +44 -44
  94. package/skills/pc-repo-help/SKILL.md +87 -87
  95. package/skills/pc-repo-verify/SKILL.md +150 -150
@@ -1,244 +1,244 @@
1
- import { execFileSync } from 'node:child_process'
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import { pathToFileURL } from 'node:url'
5
- import { commentBlocks, countLines, isGenerated, kindOf, lineKinds, slopFindings, testStats } from './code-rules.mjs'
6
-
7
- export const DEFAULT_LIMITS = {
8
- commentRatio: 0.1,
9
- commentAllowance: 2,
10
- testRatio: 1,
11
- testAllowance: 40,
12
- casesPerKloc: 40,
13
- caseAllowance: 3,
14
- complexityBaseline: 'scripts/complexity-baseline.json',
15
- }
16
-
17
- const FIX = {
18
- 'comment-budget': 'Delete comments until the diff is within budget. Keep only one that explains a constraint the code cannot show: a third-party bug, an external contract, a legal requirement.',
19
- 'banner': 'Delete the separator.',
20
- 'region': 'Delete the region markers.',
21
- 'untracked-todo': 'Link an issue or delete the TODO.',
22
- 'restating-summary': 'Delete the doc comment: it repeats the name.',
23
- 'restating-jsdoc': 'Delete the doc comment: it repeats the name.',
24
- 'restating-param': 'Delete the parameter doc: it repeats the name.',
25
- 'filler-returns': 'Delete the returns doc: it says nothing the signature does not.',
26
- 'commented-out-code': 'Delete it; git keeps the history.',
27
- 'apologetic': 'Make the code right or delete the note.',
28
- 'history': 'Delete the incident story; it belongs in the commit message or the pull request.',
29
- 'essay': 'Cut the block to one line or delete it; long explanations belong in docs or the pull request.',
30
- 'internal-doc': 'Delete the doc comment: nothing outside the file calls this.',
31
- 'touched-file-slop': 'This file is in the diff, so leave it clean: delete the finding even though it predates the change.',
32
- 'touched-file-density': 'This file now has more comments per code line than before. Delete comments until it does not.',
33
- 'test-budget': 'Too much test code for the change. Keep the tests of the public contract; a bug fix gets one regression test.',
34
- 'case-budget': 'Too many test cases for the change. Merge or delete the ones that test internals or repeat each other.',
35
- 'test-skipped': 'Delete the skipped test or make it run.',
36
- 'test-focused': 'Remove .only / f-prefix: it hides every other test.',
37
- 'test-snapshot': 'Assert the values that matter instead of a snapshot.',
38
- 'test-no-assertion': 'Assert something, or delete the test.',
39
- 'test-mock-only': 'Assert on state or output, not only that a mock was called.',
40
- }
41
-
42
- const SUSPICIOUS = {
43
- skipped: 'test-skipped',
44
- focused: 'test-focused',
45
- snapshot: 'test-snapshot',
46
- noAssertion: 'test-no-assertion',
47
- mockOnly: 'test-mock-only',
48
- }
49
-
50
- const EMPTY_STATS = { cases: 0, skipped: 0, focused: 0, snapshot: 0, noAssertion: 0, mockOnly: 0 }
51
-
52
- // `tracked` holds the files a complexity gate has methods on record for. Their new lines buy twice
53
- // the test budget: that gate fails a method whose coverage drops, so a change there needs its new
54
- // branches tested, and trimming those tests to fit this budget is what broke Pliny-Bot #633.
55
- export function evaluate(files, limits = DEFAULT_LIMITS, tracked = new Set()) {
56
- const violations = []
57
- const add = (rule, file, line, detail) => violations.push({ rule, file, line, detail, fix: FIX[rule] })
58
- const totals = { sourceCode: 0, trackedCode: 0, testCode: 0, comments: 0, testLines: 0, cases: 0 }
59
- const commentsByFile = new Map()
60
-
61
- for (const file of files) {
62
- const kind = kindOf(file.path)
63
- if (!kind || isGenerated(file.after)) continue
64
- const kinds = lineKinds(file.after)
65
- for (const n of file.added) {
66
- const k = kinds[n - 1]
67
- if (k === 'comment') {
68
- totals.comments += 1
69
- commentsByFile.set(file.path, (commentsByFile.get(file.path) ?? 0) + 1)
70
- } else if (k === 'code') {
71
- if (kind !== 'source') totals.testCode += 1
72
- else {
73
- totals.sourceCode += 1
74
- if (tracked.has(file.path)) totals.trackedCode += 1
75
- }
76
- }
77
- }
78
-
79
- const findings = slopFindings(file.after)
80
- for (const f of findings) {
81
- if (file.added.has(f.line)) add(f.rule, file.path, f.line)
82
- else if (file.before != null) add('touched-file-slop', file.path, f.line, f.rule)
83
- }
84
- for (const block of commentBlocks(file.after)) {
85
- let touched = false
86
- for (let n = block.start; n <= block.end && !touched; n++) touched = file.added.has(n)
87
- if (touched) for (const rule of block.rules) add(rule, file.path, block.start)
88
- }
89
-
90
- const before = file.before == null ? { codeLines: 0, commentLines: 0 } : countLines(file.before)
91
- const after = countLines(file.after)
92
- if (kind === 'source') {
93
- const density = c => (c.codeLines > 0 ? c.commentLines / c.codeLines : c.commentLines > 0 ? Infinity : 0)
94
- if (file.before != null && after.commentLines > before.commentLines && density(after) > density(before)) {
95
- add('touched-file-density', file.path, undefined, `${before.commentLines}/${before.codeLines} -> ${after.commentLines}/${after.codeLines}`)
96
- }
97
- continue
98
- }
99
- totals.testLines += after.codeLines - before.codeLines
100
- const statsBefore = file.before == null ? EMPTY_STATS : testStats(file.path, file.before)
101
- const statsAfter = testStats(file.path, file.after)
102
- totals.cases += Math.max(0, statsAfter.cases - statsBefore.cases)
103
- for (const [key, rule] of Object.entries(SUSPICIOUS)) {
104
- const grew = statsAfter[key] - statsBefore[key]
105
- if (grew > 0) add(rule, file.path, undefined, `+${grew}`)
106
- }
107
- }
108
-
109
- const commentBudget = Math.max(limits.commentAllowance, Math.floor(limits.commentRatio * (totals.sourceCode + totals.testCode)))
110
- const testedCode = totals.sourceCode + totals.trackedCode
111
- const testBudget = Math.max(limits.testAllowance, Math.floor(limits.testRatio * testedCode))
112
- const caseBudget = Math.max(limits.caseAllowance, Math.floor((limits.casesPerKloc * testedCode) / 1000))
113
- if (totals.comments > commentBudget) {
114
- const where = [...commentsByFile].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([f, n]) => `${f} (${n})`).join(', ')
115
- add('comment-budget', undefined, undefined, `${totals.comments} comment lines added, budget ${commentBudget}: ${where}`)
116
- }
117
- if (totals.testLines > testBudget) {
118
- add('test-budget', undefined, undefined, `${totals.testLines} test lines added for ${totals.sourceCode} code lines, budget ${testBudget}`)
119
- }
120
- if (totals.cases > caseBudget) {
121
- add('case-budget', undefined, undefined, `${totals.cases} test cases added for ${totals.sourceCode} code lines, budget ${caseBudget}`)
122
- }
123
- return { totals, budgets: { comments: commentBudget, testLines: testBudget, cases: caseBudget }, violations }
124
- }
125
-
126
- export function addedLines(unifiedDiff) {
127
- const added = new Set()
128
- for (const m of unifiedDiff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) {
129
- const start = Number(m[1])
130
- const length = m[2] === undefined ? 1 : Number(m[2])
131
- for (let n = start; n < start + length; n++) added.add(n)
132
- }
133
- return added
134
- }
135
-
136
- function git(root, args) {
137
- return execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'] })
138
- }
139
-
140
- function tryGit(root, args) {
141
- try {
142
- return git(root, args).trim()
143
- } catch {
144
- return null
145
- }
146
- }
147
-
148
- function resolveBase(root, requested) {
149
- const candidates = requested ? [requested] : ['origin/HEAD', 'origin/main', 'origin/master', 'main', 'master']
150
- for (const ref of candidates) {
151
- const base = tryGit(root, ['merge-base', ref, 'HEAD'])
152
- if (base) return { ref, base }
153
- }
154
- return null
155
- }
156
-
157
- const normalize = text => text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
158
-
159
- export function collect(root, base) {
160
- const files = []
161
- const entries = git(root, ['diff', '--name-status', '-M', '-z', base]).split('\0').filter(Boolean)
162
- for (let i = 0; i < entries.length; ) {
163
- const status = entries[i]
164
- const renamed = status.startsWith('R') || status.startsWith('C')
165
- const from = entries[i + 1]
166
- const to = renamed ? entries[i + 2] : from
167
- i += renamed ? 3 : 2
168
- if (status === 'D' || !kindOf(to)) continue
169
- const full = path.join(root, to)
170
- if (!fs.existsSync(full)) continue
171
- const after = normalize(fs.readFileSync(full, 'utf8'))
172
- const before = status === 'A' ? null : normalize(git(root, ['show', `${base}:${from}`]))
173
- const diff = git(root, ['diff', '-U0', '--no-color', '--no-ext-diff', '-M', base, '--', ...new Set([from, to])])
174
- files.push({ path: to, before, after, added: addedLines(diff) })
175
- }
176
- for (const untracked of git(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean)) {
177
- if (!kindOf(untracked)) continue
178
- const after = normalize(fs.readFileSync(path.join(root, untracked), 'utf8'))
179
- const count = after.split('\n').length - (after.endsWith('\n') ? 1 : 0)
180
- files.push({ path: untracked, before: null, after, added: new Set(Array.from({ length: count }, (_, k) => k + 1)) })
181
- }
182
- return files
183
- }
184
-
185
- // Paths of the files a complexity gate tracks, from its baseline keyed `path::method`.
186
- export function trackedFiles(root, baseline) {
187
- try {
188
- const entries = Object.keys(JSON.parse(fs.readFileSync(path.join(root, baseline), 'utf8')))
189
- return new Set(entries.map(key => key.split('::')[0]))
190
- } catch {
191
- return new Set()
192
- }
193
- }
194
-
195
- function readLimits(root) {
196
- try {
197
- const config = JSON.parse(fs.readFileSync(path.join(root, '.opencode', 'harness.json'), 'utf8'))
198
- return { ...DEFAULT_LIMITS, ...config.codeRules }
199
- } catch {
200
- return DEFAULT_LIMITS
201
- }
202
- }
203
-
204
- function report(result, base) {
205
- const { totals, budgets, violations } = result
206
- const lines = [
207
- `check-diff against ${base.ref} (${base.base.slice(0, 7)}): ${violations.length === 0 ? 'clean' : `${violations.length} problem${violations.length === 1 ? '' : 's'}`}`,
208
- ` code lines added ${totals.sourceCode}, comment lines ${totals.comments}/${budgets.comments}, test lines ${totals.testLines}/${budgets.testLines}, test cases ${totals.cases}/${budgets.cases}`,
209
- ]
210
- const byRule = new Map()
211
- for (const v of violations) byRule.set(v.rule, [...(byRule.get(v.rule) ?? []), v])
212
- for (const [rule, list] of byRule) {
213
- lines.push('', `${rule}: ${FIX[rule]}`)
214
- for (const v of list.slice(0, 50)) {
215
- const where = v.file ? `${v.file}${v.line ? `:${v.line}` : ''}` : ''
216
- lines.push(` ${[where, v.detail].filter(Boolean).join(' ')}`)
217
- }
218
- if (list.length > 50) lines.push(` ... ${list.length - 50} more`)
219
- }
220
- return lines.join('\n')
221
- }
222
-
223
- function main(argv) {
224
- const option = name => {
225
- const i = argv.indexOf(`--${name}`)
226
- return i === -1 ? undefined : argv[i + 1]
227
- }
228
- const root = tryGit(process.cwd(), ['rev-parse', '--show-toplevel'])
229
- if (!root) {
230
- console.error('check-diff: not inside a git repository.')
231
- return 2
232
- }
233
- const base = resolveBase(root, option('base') ?? process.env.CHECK_DIFF_BASE)
234
- if (!base) {
235
- console.error('check-diff: no base to compare against. Pass --base <ref> or fetch origin.')
236
- return 2
237
- }
238
- const limits = readLimits(root)
239
- const result = evaluate(collect(root, base.base), limits, trackedFiles(root, limits.complexityBaseline))
240
- console.log(argv.includes('--json') ? JSON.stringify({ base, ...result }, null, 2) : report(result, base))
241
- return result.violations.length === 0 ? 0 : 1
242
- }
243
-
244
- if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = main(process.argv.slice(2))
1
+ import { execFileSync } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { commentBlocks, countLines, isGenerated, kindOf, lineKinds, slopFindings, testStats } from './code-rules.mjs'
6
+
7
+ export const DEFAULT_LIMITS = {
8
+ commentRatio: 0.1,
9
+ commentAllowance: 2,
10
+ testRatio: 1,
11
+ testAllowance: 40,
12
+ casesPerKloc: 40,
13
+ caseAllowance: 3,
14
+ complexityBaseline: 'scripts/complexity-baseline.json',
15
+ }
16
+
17
+ const FIX = {
18
+ 'comment-budget': 'Delete comments until the diff is within budget. Keep only one that explains a constraint the code cannot show: a third-party bug, an external contract, a legal requirement.',
19
+ 'banner': 'Delete the separator.',
20
+ 'region': 'Delete the region markers.',
21
+ 'untracked-todo': 'Link an issue or delete the TODO.',
22
+ 'restating-summary': 'Delete the doc comment: it repeats the name.',
23
+ 'restating-jsdoc': 'Delete the doc comment: it repeats the name.',
24
+ 'restating-param': 'Delete the parameter doc: it repeats the name.',
25
+ 'filler-returns': 'Delete the returns doc: it says nothing the signature does not.',
26
+ 'commented-out-code': 'Delete it; git keeps the history.',
27
+ 'apologetic': 'Make the code right or delete the note.',
28
+ 'history': 'Delete the incident story; it belongs in the commit message or the pull request.',
29
+ 'essay': 'Cut the block to one line or delete it; long explanations belong in docs or the pull request.',
30
+ 'internal-doc': 'Delete the doc comment: nothing outside the file calls this.',
31
+ 'touched-file-slop': 'This file is in the diff, so leave it clean: delete the finding even though it predates the change.',
32
+ 'touched-file-density': 'This file now has more comments per code line than before. Delete comments until it does not.',
33
+ 'test-budget': 'Too much test code for the change. Keep the tests of the public contract; a bug fix gets one regression test.',
34
+ 'case-budget': 'Too many test cases for the change. Merge or delete the ones that test internals or repeat each other.',
35
+ 'test-skipped': 'Delete the skipped test or make it run.',
36
+ 'test-focused': 'Remove .only / f-prefix: it hides every other test.',
37
+ 'test-snapshot': 'Assert the values that matter instead of a snapshot.',
38
+ 'test-no-assertion': 'Assert something, or delete the test.',
39
+ 'test-mock-only': 'Assert on state or output, not only that a mock was called.',
40
+ }
41
+
42
+ const SUSPICIOUS = {
43
+ skipped: 'test-skipped',
44
+ focused: 'test-focused',
45
+ snapshot: 'test-snapshot',
46
+ noAssertion: 'test-no-assertion',
47
+ mockOnly: 'test-mock-only',
48
+ }
49
+
50
+ const EMPTY_STATS = { cases: 0, skipped: 0, focused: 0, snapshot: 0, noAssertion: 0, mockOnly: 0 }
51
+
52
+ // `tracked` holds the files a complexity gate has methods on record for. Their new lines buy twice
53
+ // the test budget: that gate fails a method whose coverage drops, so a change there needs its new
54
+ // branches tested, and trimming those tests to fit this budget is what broke Pliny-Bot #633.
55
+ export function evaluate(files, limits = DEFAULT_LIMITS, tracked = new Set()) {
56
+ const violations = []
57
+ const add = (rule, file, line, detail) => violations.push({ rule, file, line, detail, fix: FIX[rule] })
58
+ const totals = { sourceCode: 0, trackedCode: 0, testCode: 0, comments: 0, testLines: 0, cases: 0 }
59
+ const commentsByFile = new Map()
60
+
61
+ for (const file of files) {
62
+ const kind = kindOf(file.path)
63
+ if (!kind || isGenerated(file.after)) continue
64
+ const kinds = lineKinds(file.after)
65
+ for (const n of file.added) {
66
+ const k = kinds[n - 1]
67
+ if (k === 'comment') {
68
+ totals.comments += 1
69
+ commentsByFile.set(file.path, (commentsByFile.get(file.path) ?? 0) + 1)
70
+ } else if (k === 'code') {
71
+ if (kind !== 'source') totals.testCode += 1
72
+ else {
73
+ totals.sourceCode += 1
74
+ if (tracked.has(file.path)) totals.trackedCode += 1
75
+ }
76
+ }
77
+ }
78
+
79
+ const findings = slopFindings(file.after)
80
+ for (const f of findings) {
81
+ if (file.added.has(f.line)) add(f.rule, file.path, f.line)
82
+ else if (file.before != null) add('touched-file-slop', file.path, f.line, f.rule)
83
+ }
84
+ for (const block of commentBlocks(file.after)) {
85
+ let touched = false
86
+ for (let n = block.start; n <= block.end && !touched; n++) touched = file.added.has(n)
87
+ if (touched) for (const rule of block.rules) add(rule, file.path, block.start)
88
+ }
89
+
90
+ const before = file.before == null ? { codeLines: 0, commentLines: 0 } : countLines(file.before)
91
+ const after = countLines(file.after)
92
+ if (kind === 'source') {
93
+ const density = c => (c.codeLines > 0 ? c.commentLines / c.codeLines : c.commentLines > 0 ? Infinity : 0)
94
+ if (file.before != null && after.commentLines > before.commentLines && density(after) > density(before)) {
95
+ add('touched-file-density', file.path, undefined, `${before.commentLines}/${before.codeLines} -> ${after.commentLines}/${after.codeLines}`)
96
+ }
97
+ continue
98
+ }
99
+ totals.testLines += after.codeLines - before.codeLines
100
+ const statsBefore = file.before == null ? EMPTY_STATS : testStats(file.path, file.before)
101
+ const statsAfter = testStats(file.path, file.after)
102
+ totals.cases += Math.max(0, statsAfter.cases - statsBefore.cases)
103
+ for (const [key, rule] of Object.entries(SUSPICIOUS)) {
104
+ const grew = statsAfter[key] - statsBefore[key]
105
+ if (grew > 0) add(rule, file.path, undefined, `+${grew}`)
106
+ }
107
+ }
108
+
109
+ const commentBudget = Math.max(limits.commentAllowance, Math.floor(limits.commentRatio * (totals.sourceCode + totals.testCode)))
110
+ const testedCode = totals.sourceCode + totals.trackedCode
111
+ const testBudget = Math.max(limits.testAllowance, Math.floor(limits.testRatio * testedCode))
112
+ const caseBudget = Math.max(limits.caseAllowance, Math.floor((limits.casesPerKloc * testedCode) / 1000))
113
+ if (totals.comments > commentBudget) {
114
+ const where = [...commentsByFile].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([f, n]) => `${f} (${n})`).join(', ')
115
+ add('comment-budget', undefined, undefined, `${totals.comments} comment lines added, budget ${commentBudget}: ${where}`)
116
+ }
117
+ if (totals.testLines > testBudget) {
118
+ add('test-budget', undefined, undefined, `${totals.testLines} test lines added for ${totals.sourceCode} code lines, budget ${testBudget}`)
119
+ }
120
+ if (totals.cases > caseBudget) {
121
+ add('case-budget', undefined, undefined, `${totals.cases} test cases added for ${totals.sourceCode} code lines, budget ${caseBudget}`)
122
+ }
123
+ return { totals, budgets: { comments: commentBudget, testLines: testBudget, cases: caseBudget }, violations }
124
+ }
125
+
126
+ export function addedLines(unifiedDiff) {
127
+ const added = new Set()
128
+ for (const m of unifiedDiff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) {
129
+ const start = Number(m[1])
130
+ const length = m[2] === undefined ? 1 : Number(m[2])
131
+ for (let n = start; n < start + length; n++) added.add(n)
132
+ }
133
+ return added
134
+ }
135
+
136
+ function git(root, args) {
137
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'] })
138
+ }
139
+
140
+ function tryGit(root, args) {
141
+ try {
142
+ return git(root, args).trim()
143
+ } catch {
144
+ return null
145
+ }
146
+ }
147
+
148
+ function resolveBase(root, requested) {
149
+ const candidates = requested ? [requested] : ['origin/HEAD', 'origin/main', 'origin/master', 'main', 'master']
150
+ for (const ref of candidates) {
151
+ const base = tryGit(root, ['merge-base', ref, 'HEAD'])
152
+ if (base) return { ref, base }
153
+ }
154
+ return null
155
+ }
156
+
157
+ const normalize = text => text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
158
+
159
+ export function collect(root, base) {
160
+ const files = []
161
+ const entries = git(root, ['diff', '--name-status', '-M', '-z', base]).split('\0').filter(Boolean)
162
+ for (let i = 0; i < entries.length; ) {
163
+ const status = entries[i]
164
+ const renamed = status.startsWith('R') || status.startsWith('C')
165
+ const from = entries[i + 1]
166
+ const to = renamed ? entries[i + 2] : from
167
+ i += renamed ? 3 : 2
168
+ if (status === 'D' || !kindOf(to)) continue
169
+ const full = path.join(root, to)
170
+ if (!fs.existsSync(full)) continue
171
+ const after = normalize(fs.readFileSync(full, 'utf8'))
172
+ const before = status === 'A' ? null : normalize(git(root, ['show', `${base}:${from}`]))
173
+ const diff = git(root, ['diff', '-U0', '--no-color', '--no-ext-diff', '-M', base, '--', ...new Set([from, to])])
174
+ files.push({ path: to, before, after, added: addedLines(diff) })
175
+ }
176
+ for (const untracked of git(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean)) {
177
+ if (!kindOf(untracked)) continue
178
+ const after = normalize(fs.readFileSync(path.join(root, untracked), 'utf8'))
179
+ const count = after.split('\n').length - (after.endsWith('\n') ? 1 : 0)
180
+ files.push({ path: untracked, before: null, after, added: new Set(Array.from({ length: count }, (_, k) => k + 1)) })
181
+ }
182
+ return files
183
+ }
184
+
185
+ // Paths of the files a complexity gate tracks, from its baseline keyed `path::method`.
186
+ export function trackedFiles(root, baseline) {
187
+ try {
188
+ const entries = Object.keys(JSON.parse(fs.readFileSync(path.join(root, baseline), 'utf8')))
189
+ return new Set(entries.map(key => key.split('::')[0]))
190
+ } catch {
191
+ return new Set()
192
+ }
193
+ }
194
+
195
+ function readLimits(root) {
196
+ try {
197
+ const config = JSON.parse(fs.readFileSync(path.join(root, '.opencode', 'harness.json'), 'utf8'))
198
+ return { ...DEFAULT_LIMITS, ...config.codeRules }
199
+ } catch {
200
+ return DEFAULT_LIMITS
201
+ }
202
+ }
203
+
204
+ function report(result, base) {
205
+ const { totals, budgets, violations } = result
206
+ const lines = [
207
+ `check-diff against ${base.ref} (${base.base.slice(0, 7)}): ${violations.length === 0 ? 'clean' : `${violations.length} problem${violations.length === 1 ? '' : 's'}`}`,
208
+ ` code lines added ${totals.sourceCode}, comment lines ${totals.comments}/${budgets.comments}, test lines ${totals.testLines}/${budgets.testLines}, test cases ${totals.cases}/${budgets.cases}`,
209
+ ]
210
+ const byRule = new Map()
211
+ for (const v of violations) byRule.set(v.rule, [...(byRule.get(v.rule) ?? []), v])
212
+ for (const [rule, list] of byRule) {
213
+ lines.push('', `${rule}: ${FIX[rule]}`)
214
+ for (const v of list.slice(0, 50)) {
215
+ const where = v.file ? `${v.file}${v.line ? `:${v.line}` : ''}` : ''
216
+ lines.push(` ${[where, v.detail].filter(Boolean).join(' ')}`)
217
+ }
218
+ if (list.length > 50) lines.push(` ... ${list.length - 50} more`)
219
+ }
220
+ return lines.join('\n')
221
+ }
222
+
223
+ function main(argv) {
224
+ const option = name => {
225
+ const i = argv.indexOf(`--${name}`)
226
+ return i === -1 ? undefined : argv[i + 1]
227
+ }
228
+ const root = tryGit(process.cwd(), ['rev-parse', '--show-toplevel'])
229
+ if (!root) {
230
+ console.error('check-diff: not inside a git repository.')
231
+ return 2
232
+ }
233
+ const base = resolveBase(root, option('base') ?? process.env.CHECK_DIFF_BASE)
234
+ if (!base) {
235
+ console.error('check-diff: no base to compare against. Pass --base <ref> or fetch origin.')
236
+ return 2
237
+ }
238
+ const limits = readLimits(root)
239
+ const result = evaluate(collect(root, base.base), limits, trackedFiles(root, limits.complexityBaseline))
240
+ console.log(argv.includes('--json') ? JSON.stringify({ base, ...result }, null, 2) : report(result, base))
241
+ return result.violations.length === 0 ? 0 : 1
242
+ }
243
+
244
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = main(process.argv.slice(2))