@plainconceptsplatform/agent-harness 3.5.0 → 3.6.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 (143) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +455 -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/update.js +121 -121
  8. package/cli/commands/wizard.js +134 -134
  9. package/cli/fragments/archive/az.md +97 -97
  10. package/cli/fragments/archive/gh.md +96 -96
  11. package/cli/fragments/archive/gl.md +96 -96
  12. package/cli/fragments/archive/none.md +75 -75
  13. package/cli/fragments/guardrails/codegraph.md +5 -5
  14. package/cli/fragments/guardrails/humanizer.md +4 -4
  15. package/cli/fragments/guardrails/memory.md +4 -4
  16. package/cli/fragments/guardrails/rtk.md +3 -3
  17. package/cli/fragments/guardrails/simple-english.md +4 -4
  18. package/cli/fragments/ops-backlog/az.md +28 -28
  19. package/cli/fragments/ops-backlog/gh.md +28 -28
  20. package/cli/fragments/ops-backlog/jira.md +28 -28
  21. package/cli/fragments/ops-review/az.md +62 -62
  22. package/cli/fragments/ops-review/gh.md +51 -51
  23. package/cli/fragments/ops-review/gl.md +55 -55
  24. package/cli/fragments/ops-ship/az.md +81 -81
  25. package/cli/fragments/ops-ship/gh.md +67 -67
  26. package/cli/fragments/ops-ship/gl.md +84 -84
  27. package/cli/index.js +116 -116
  28. package/cli/presets/agents-content.json +34 -34
  29. package/cli/presets/browser.json +10 -10
  30. package/cli/presets/clean.json +21 -21
  31. package/cli/presets/models.json +68 -68
  32. package/cli/presets/optimization.json +32 -32
  33. package/cli/presets/platforms.json +76 -76
  34. package/cli/presets/source.json +23 -23
  35. package/cli/steps/browser/index.js +48 -48
  36. package/cli/steps/clean/index.js +120 -120
  37. package/cli/steps/copy/agents.js +120 -120
  38. package/cli/steps/copy/commands.js +79 -79
  39. package/cli/steps/copy/fullstack-engineer.js +89 -89
  40. package/cli/steps/copy/index.js +88 -88
  41. package/cli/steps/copy/opencode-json.js +324 -324
  42. package/cli/steps/copy/skills.js +316 -316
  43. package/cli/steps/metadata/index.js +115 -115
  44. package/cli/steps/models/format.js +88 -88
  45. package/cli/steps/models/index.js +64 -64
  46. package/cli/steps/models/write.js +38 -38
  47. package/cli/steps/openspec/index.js +136 -136
  48. package/cli/steps/optimization/codegraph.js +141 -141
  49. package/cli/steps/optimization/detect.js +66 -66
  50. package/cli/steps/optimization/humanizer.js +17 -17
  51. package/cli/steps/optimization/index.js +158 -158
  52. package/cli/steps/optimization/memory.js +91 -91
  53. package/cli/steps/optimization/patch-guardrails.js +111 -111
  54. package/cli/steps/optimization/simple-english.js +17 -17
  55. package/cli/steps/optimization/skills-lock.js +30 -30
  56. package/cli/steps/platform/index.js +109 -109
  57. package/cli/steps/source/index.js +123 -123
  58. package/cli/utils/agent-color.js +111 -111
  59. package/cli/utils/copy.js +134 -134
  60. package/cli/utils/exec-spinner.js +47 -47
  61. package/cli/utils/exec.js +134 -134
  62. package/cli/utils/legacy-check.js +30 -30
  63. package/cli/utils/models-cache.js +58 -58
  64. package/cli/utils/models-pricing.js +42 -42
  65. package/cli/utils/paths.js +81 -81
  66. package/cli/utils/process.js +3 -3
  67. package/cli/utils/terminal.js +6 -6
  68. package/cli/utils/update-manifest.js +75 -75
  69. package/harness/.opencode/_gitignore +10 -10
  70. package/harness/.opencode/commands/init.md +5 -5
  71. package/harness/.opencode/commands/make-architecture.md +5 -5
  72. package/harness/.opencode/commands/make-design.md +5 -5
  73. package/harness/.opencode/commands/make-engineer.md +5 -5
  74. package/harness/.opencode/commands/make-guardrails.md +5 -5
  75. package/harness/.opencode/commands/make-user-model.md +5 -5
  76. package/harness/.opencode/commands/ops-backlog.md +10 -10
  77. package/harness/.opencode/commands/ops-review.md +10 -10
  78. package/harness/.opencode/commands/ops-ship.md +9 -9
  79. package/harness/.opencode/commands/plan-apply.md +9 -9
  80. package/harness/.opencode/commands/plan-archive.md +7 -7
  81. package/harness/.opencode/commands/plan-explore.md +11 -11
  82. package/harness/.opencode/commands/plan-goal.md +5 -5
  83. package/harness/.opencode/commands/plan-propose.md +11 -11
  84. package/harness/.opencode/commands/plan-quick.md +7 -7
  85. package/harness/.opencode/commands/plan-story.md +11 -11
  86. package/harness/.opencode/commands/repo-audit.md +7 -7
  87. package/harness/.opencode/commands/repo-help.md +5 -5
  88. package/harness/.opencode/commands/repo-initialize.md +5 -5
  89. package/harness/.opencode/commands/repo-onboard.md +5 -5
  90. package/harness/.opencode/commands/repo-verify.md +5 -5
  91. package/harness/.opencode/package.json +5 -5
  92. package/harness/.opencode/plugins/pc-commit-coauthor.js +41 -0
  93. package/harness/.opencode/plugins/pc-subagent-monitor.js +184 -184
  94. package/harness/.opencode/plugins/pc-subagent-tiers.js +367 -367
  95. package/harness/.opencode/plugins/pc-system-reminders.js +386 -386
  96. package/harness/.opencode/scripts/check-diff.mjs +252 -252
  97. package/harness/.opencode/scripts/code-rules.mjs +288 -288
  98. package/harness/AGENTS.md +49 -49
  99. package/harness/ARCHITECTURE.md +13 -13
  100. package/harness/DESIGN.md +13 -13
  101. package/harness/opencode.jsonc +36 -36
  102. package/harness/openspec/config.yaml +20 -20
  103. package/harness/skills-lock.json +17 -17
  104. package/package.json +14 -12
  105. package/skills/README.md +18 -18
  106. package/skills/agent-harness-cli/SKILL.md +86 -86
  107. package/skills/browser-automation/SKILL.md +72 -72
  108. package/skills/pc-guardrails-generic/SKILL.md +53 -53
  109. package/skills/pc-guardrails-project/SKILL.md +8 -8
  110. package/skills/pc-make-architecture/SKILL.md +32 -32
  111. package/skills/pc-make-architecture/structure-template.md +64 -64
  112. package/skills/pc-make-design/SKILL.md +45 -45
  113. package/skills/pc-make-engineer/SKILL.md +59 -59
  114. package/skills/pc-make-engineer/signal-mapping.md +53 -53
  115. package/skills/pc-make-engineer/template.md +36 -36
  116. package/skills/pc-make-guardrails/SKILL.md +44 -44
  117. package/skills/pc-make-guardrails/category-reference.md +112 -112
  118. package/skills/pc-make-merge-risk-assess/SKILL.md +70 -70
  119. package/skills/pc-make-merge-risk-assess/category-reference.md +114 -114
  120. package/skills/pc-make-user-model/SKILL.md +56 -56
  121. package/skills/pc-ops-ship/SKILL.md +22 -22
  122. package/skills/pc-plan-apply/SKILL.md +88 -88
  123. package/skills/pc-plan-apply/simple-mode.md +21 -21
  124. package/skills/pc-plan-archive/SKILL.md +66 -66
  125. package/skills/pc-plan-explore/SKILL.md +21 -21
  126. package/skills/pc-plan-goal/SKILL.md +91 -91
  127. package/skills/pc-plan-goal/branching.md +39 -39
  128. package/skills/pc-plan-goal/failure-policy.md +30 -30
  129. package/skills/pc-plan-goal/output-mode.md +10 -10
  130. package/skills/pc-plan-goal/output.md +71 -71
  131. package/skills/pc-plan-propose/SKILL.md +125 -125
  132. package/skills/pc-plan-propose/task-annotation.md +39 -39
  133. package/skills/pc-plan-quick/SKILL.md +46 -46
  134. package/skills/pc-plan-story/SKILL.md +93 -93
  135. package/skills/pc-repo-audit/SKILL.md +44 -44
  136. package/skills/pc-repo-help/SKILL.md +87 -87
  137. package/skills/pc-repo-initialize/SKILL.md +119 -119
  138. package/skills/pc-repo-onboard/SKILL.md +32 -32
  139. package/skills/pc-repo-verify/SKILL.md +150 -150
  140. package/skills/pc-userstory-az/SKILL.md +71 -71
  141. package/skills/pc-userstory-browser/SKILL.md +64 -64
  142. package/skills/pc-userstory-gh/SKILL.md +63 -63
  143. package/skills/pc-userstory-jira/SKILL.md +74 -74
@@ -1,252 +1,252 @@
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
- // A subagent checks only the files it owns while others edit the same tree: the budgets then fit its share.
186
- export function scope(files, paths) {
187
- if (!paths?.length) return files
188
- const norm = paths.map(p => p.replace(/\\/g, '/').replace(/^\.\//, ''))
189
- return files.filter(f => norm.some(p => f.path === p || f.path.startsWith(p.endsWith('/') ? p : `${p}/`)))
190
- }
191
-
192
- // Paths of the files a complexity gate tracks, from its baseline keyed `path::method`.
193
- export function trackedFiles(root, baseline) {
194
- try {
195
- const entries = Object.keys(JSON.parse(fs.readFileSync(path.join(root, baseline), 'utf8')))
196
- return new Set(entries.map(key => key.split('::')[0]))
197
- } catch {
198
- return new Set()
199
- }
200
- }
201
-
202
- function readLimits(root) {
203
- try {
204
- const config = JSON.parse(fs.readFileSync(path.join(root, '.opencode', 'harness.json'), 'utf8'))
205
- return { ...DEFAULT_LIMITS, ...config.codeRules }
206
- } catch {
207
- return DEFAULT_LIMITS
208
- }
209
- }
210
-
211
- function report(result, base) {
212
- const { totals, budgets, violations } = result
213
- const lines = [
214
- `check-diff against ${base.ref} (${base.base.slice(0, 7)}): ${violations.length === 0 ? 'clean' : `${violations.length} problem${violations.length === 1 ? '' : 's'}`}`,
215
- ` code lines added ${totals.sourceCode}, comment lines ${totals.comments}/${budgets.comments}, test lines ${totals.testLines}/${budgets.testLines}, test cases ${totals.cases}/${budgets.cases}`,
216
- ]
217
- const byRule = new Map()
218
- for (const v of violations) byRule.set(v.rule, [...(byRule.get(v.rule) ?? []), v])
219
- for (const [rule, list] of byRule) {
220
- lines.push('', `${rule}: ${FIX[rule]}`)
221
- for (const v of list.slice(0, 50)) {
222
- const where = v.file ? `${v.file}${v.line ? `:${v.line}` : ''}` : ''
223
- lines.push(` ${[where, v.detail].filter(Boolean).join(' ')}`)
224
- }
225
- if (list.length > 50) lines.push(` ... ${list.length - 50} more`)
226
- }
227
- return lines.join('\n')
228
- }
229
-
230
- function main(argv) {
231
- const option = name => {
232
- const i = argv.indexOf(`--${name}`)
233
- return i === -1 ? undefined : argv[i + 1]
234
- }
235
- const root = tryGit(process.cwd(), ['rev-parse', '--show-toplevel'])
236
- if (!root) {
237
- console.error('check-diff: not inside a git repository.')
238
- return 2
239
- }
240
- const base = resolveBase(root, option('base') ?? process.env.CHECK_DIFF_BASE)
241
- if (!base) {
242
- console.error('check-diff: no base to compare against. Pass --base <ref> or fetch origin.')
243
- return 2
244
- }
245
- const limits = readLimits(root)
246
- const paths = option('paths')?.split(',').map(p => p.trim()).filter(Boolean)
247
- const result = evaluate(scope(collect(root, base.base), paths), limits, trackedFiles(root, limits.complexityBaseline))
248
- console.log(argv.includes('--json') ? JSON.stringify({ base, ...result }, null, 2) : report(result, base))
249
- return result.violations.length === 0 ? 0 : 1
250
- }
251
-
252
- 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
+ // A subagent checks only the files it owns while others edit the same tree: the budgets then fit its share.
186
+ export function scope(files, paths) {
187
+ if (!paths?.length) return files
188
+ const norm = paths.map(p => p.replace(/\\/g, '/').replace(/^\.\//, ''))
189
+ return files.filter(f => norm.some(p => f.path === p || f.path.startsWith(p.endsWith('/') ? p : `${p}/`)))
190
+ }
191
+
192
+ // Paths of the files a complexity gate tracks, from its baseline keyed `path::method`.
193
+ export function trackedFiles(root, baseline) {
194
+ try {
195
+ const entries = Object.keys(JSON.parse(fs.readFileSync(path.join(root, baseline), 'utf8')))
196
+ return new Set(entries.map(key => key.split('::')[0]))
197
+ } catch {
198
+ return new Set()
199
+ }
200
+ }
201
+
202
+ function readLimits(root) {
203
+ try {
204
+ const config = JSON.parse(fs.readFileSync(path.join(root, '.opencode', 'harness.json'), 'utf8'))
205
+ return { ...DEFAULT_LIMITS, ...config.codeRules }
206
+ } catch {
207
+ return DEFAULT_LIMITS
208
+ }
209
+ }
210
+
211
+ function report(result, base) {
212
+ const { totals, budgets, violations } = result
213
+ const lines = [
214
+ `check-diff against ${base.ref} (${base.base.slice(0, 7)}): ${violations.length === 0 ? 'clean' : `${violations.length} problem${violations.length === 1 ? '' : 's'}`}`,
215
+ ` code lines added ${totals.sourceCode}, comment lines ${totals.comments}/${budgets.comments}, test lines ${totals.testLines}/${budgets.testLines}, test cases ${totals.cases}/${budgets.cases}`,
216
+ ]
217
+ const byRule = new Map()
218
+ for (const v of violations) byRule.set(v.rule, [...(byRule.get(v.rule) ?? []), v])
219
+ for (const [rule, list] of byRule) {
220
+ lines.push('', `${rule}: ${FIX[rule]}`)
221
+ for (const v of list.slice(0, 50)) {
222
+ const where = v.file ? `${v.file}${v.line ? `:${v.line}` : ''}` : ''
223
+ lines.push(` ${[where, v.detail].filter(Boolean).join(' ')}`)
224
+ }
225
+ if (list.length > 50) lines.push(` ... ${list.length - 50} more`)
226
+ }
227
+ return lines.join('\n')
228
+ }
229
+
230
+ function main(argv) {
231
+ const option = name => {
232
+ const i = argv.indexOf(`--${name}`)
233
+ return i === -1 ? undefined : argv[i + 1]
234
+ }
235
+ const root = tryGit(process.cwd(), ['rev-parse', '--show-toplevel'])
236
+ if (!root) {
237
+ console.error('check-diff: not inside a git repository.')
238
+ return 2
239
+ }
240
+ const base = resolveBase(root, option('base') ?? process.env.CHECK_DIFF_BASE)
241
+ if (!base) {
242
+ console.error('check-diff: no base to compare against. Pass --base <ref> or fetch origin.')
243
+ return 2
244
+ }
245
+ const limits = readLimits(root)
246
+ const paths = option('paths')?.split(',').map(p => p.trim()).filter(Boolean)
247
+ const result = evaluate(scope(collect(root, base.base), paths), limits, trackedFiles(root, limits.complexityBaseline))
248
+ console.log(argv.includes('--json') ? JSON.stringify({ base, ...result }, null, 2) : report(result, base))
249
+ return result.violations.length === 0 ? 0 : 1
250
+ }
251
+
252
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) process.exitCode = main(process.argv.slice(2))