@sockulags/agent-os 0.15.0 → 0.17.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.
- package/README.md +105 -59
- package/cli/doctor.mjs +351 -0
- package/cli/index.mjs +328 -151
- package/cli/index.test.mjs +436 -9
- package/package.json +5 -6
- package/plugins/agent-os-core/.claude-plugin/plugin.json +18 -0
- package/plugins/agent-os-core/.codex-plugin/plugin.json +24 -0
- package/plugins/agent-os-core/skills/capture-intent/SKILL.md +68 -0
- package/plugins/agent-os-core/skills/capture-intent/references/intent-template.md +47 -0
- package/plugins/agent-os-core/skills/explain-work/SKILL.md +42 -0
- package/{skills → plugins/agent-os-core/skills}/list-skills/SKILL.md +16 -7
- package/{skills → plugins/agent-os-core/skills}/plain-voice/SKILL.md +7 -4
- package/plugins/agent-os-core/skills/plan-work/SKILL.md +151 -0
- package/{skills → plugins/agent-os-core/skills}/plan-work/references/elicitation.md +7 -3
- package/plugins/agent-os-core/skills/plan-work/references/spec-template.md +65 -0
- package/plugins/agent-os-core/skills/record-lesson/SKILL.md +47 -0
- package/{skills → plugins/agent-os-core/skills}/scope-guard/SKILL.md +11 -6
- package/{skills → plugins/agent-os-core/skills}/verify-before-done/SKILL.md +6 -2
- package/plugins/agent-os-dev/.claude-plugin/plugin.json +18 -0
- package/plugins/agent-os-dev/.codex-plugin/plugin.json +24 -0
- package/plugins/agent-os-dev/hooks/hooks.json +42 -0
- package/{skills → plugins/agent-os-dev/skills}/batch-work/SKILL.md +6 -2
- package/{skills → plugins/agent-os-dev/skills}/check-work/SKILL.md +33 -14
- package/{skills/deliver-work/workflow.md → plugins/agent-os-dev/skills/deliver-work/SKILL.md} +126 -57
- package/plugins/agent-os-dev/skills/deliver-work/references/work-records.md +20 -0
- package/plugins/agent-os-dev/skills/design-work/SKILL.md +160 -0
- package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.mjs +233 -0
- package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.test.mjs +73 -0
- package/plugins/agent-os-dev/skills/diagnose-before-fix/SKILL.md +29 -0
- package/{skills → plugins/agent-os-dev/skills}/dispatch-next/SKILL.md +11 -3
- package/plugins/agent-os-dev/skills/init-agent-os/SKILL.md +131 -0
- package/plugins/agent-os-dev/skills/init-agent-os/policy.md +91 -0
- package/plugins/agent-os-dev/skills/init-agent-os/references/guards.md +40 -0
- package/plugins/agent-os-dev/skills/init-agent-os/references/repository-init.md +115 -0
- package/plugins/agent-os-dev/skills/init-agent-os/references/review-template.md +35 -0
- package/plugins/agent-os-dev/skills/init-agent-os/references/workflow-template.md +80 -0
- package/plugins/agent-os-dev/skills/init-agent-os/scripts/policy-block.mjs +187 -0
- package/plugins/agent-os-dev/skills/init-agent-os/templates/agent-review.yml +59 -0
- package/plugins/agent-os-dev/skills/init-agent-os/templates/lint-intents.yml +30 -0
- package/{skills → plugins/agent-os-dev/skills}/proportional-testing/SKILL.md +1 -1
- package/plugins/agent-os-dev/skills/quality-ratchet/SKILL.md +104 -0
- package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/project-controls.md +31 -3
- package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.mjs +145 -0
- package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.test.mjs +158 -0
- package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.mjs +372 -0
- package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.test.mjs +138 -0
- package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.mjs +322 -0
- package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.test.mjs +177 -0
- package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.mjs +59 -8
- package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.test.mjs +134 -8
- package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.mjs +296 -22
- package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.test.mjs +114 -6
- package/plugins/agent-os-dev/skills/shape-work/SKILL.md +135 -0
- package/plugins/agent-os-dev/skills/shape-work/references/implementation-issues.md +163 -0
- package/{skills/plan-work → plugins/agent-os-dev/skills/shape-work}/references/prototypes.md +9 -10
- package/plugins/agent-os-dev/skills/simplify/SKILL.md +91 -0
- package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.mjs +166 -0
- package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.test.mjs +49 -0
- package/policy.md +57 -30
- package/hooks/hooks.json +0 -17
- package/skills/deliver-work/SKILL.md +0 -12
- package/skills/diagnose-before-fix/SKILL.md +0 -24
- package/skills/explain-work/SKILL.md +0 -28
- package/skills/init-agent-os/SKILL.md +0 -55
- package/skills/init-agent-os/references/repository-init.md +0 -75
- package/skills/init-agent-os/scripts/policy-block.ps1 +0 -87
- package/skills/notice-lesson/SKILL.md +0 -20
- package/skills/plan-work/SKILL.md +0 -100
- package/skills/quality-ratchet/SKILL.md +0 -72
- package/skills/record-lesson/SKILL.md +0 -31
- package/skills/shape-work/SKILL.md +0 -71
- package/skills/shape-work/references/implementation-issues.md +0 -90
- package/skills/shape-work/references/mockups.md +0 -23
- package/skills/simplifier/SKILL.md +0 -35
- package/skills/simplifier-audit/SKILL.md +0 -30
- package/skills/simplifier-review/SKILL.md +0 -40
- package/skills/understand-work/SKILL.md +0 -32
- package/skills/understand-work/agents/openai.yaml +0 -2
- package/skills/writing-skills/SKILL.md +0 -68
- package/skills/writing-skills/agents/openai.yaml +0 -2
- /package/{skills/batch-work → plugins/agent-os-core/skills/capture-intent}/agents/openai.yaml +0 -0
- /package/{skills/deliver-work → plugins/agent-os-core/skills/explain-work}/agents/openai.yaml +0 -0
- /package/{skills/dispatch-next → plugins/agent-os-core/skills/list-skills}/agents/openai.yaml +0 -0
- /package/{skills → plugins/agent-os-core/skills}/plain-voice/references/tells.md +0 -0
- /package/{skills/explain-work → plugins/agent-os-core/skills/plan-work}/agents/openai.yaml +0 -0
- /package/{skills → plugins/agent-os-core/skills}/plan-work/references/map.md +0 -0
- /package/{skills/init-agent-os → plugins/agent-os-dev/skills/batch-work}/agents/openai.yaml +0 -0
- /package/{skills → plugins/agent-os-dev/skills}/batch-work/references/manifest.md +0 -0
- /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/manifest-hash.mjs +0 -0
- /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/test-manifest-hash.mjs +0 -0
- /package/{skills → plugins/agent-os-dev/skills}/check-work/references/findings.md +0 -0
- /package/{skills/list-skills → plugins/agent-os-dev/skills/deliver-work}/agents/openai.yaml +0 -0
- /package/{skills/plan-work → plugins/agent-os-dev/skills/design-work}/agents/openai.yaml +0 -0
- /package/{skills/record-lesson → plugins/agent-os-dev/skills/dispatch-next}/agents/openai.yaml +0 -0
- /package/{skills/shape-work → plugins/agent-os-dev/skills/init-agent-os}/agents/openai.yaml +0 -0
- /package/{skills → plugins/agent-os-dev/skills}/proportional-testing/references/strategy.md +0 -0
- /package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/structure.md +0 -0
- /package/{skills/simplifier-audit → plugins/agent-os-dev/skills/shape-work}/agents/openai.yaml +0 -0
- /package/{skills/simplifier → plugins/agent-os-dev/skills/simplify}/agents/openai.yaml +0 -0
package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.test.mjs
RENAMED
|
@@ -2,11 +2,18 @@ import assert from 'node:assert/strict'
|
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import os from 'node:os'
|
|
4
4
|
import path from 'node:path'
|
|
5
|
-
import { execFileSync } from 'node:child_process'
|
|
6
|
-
import test from 'node:test'
|
|
7
|
-
import {
|
|
5
|
+
import { execFileSync, spawnSync } from 'node:child_process'
|
|
6
|
+
import test, { after } from 'node:test'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
import { begin, check, finish, hook, clear, controlsTrustPlan, trustControls } from './quality-delta.mjs'
|
|
8
9
|
|
|
9
|
-
const
|
|
10
|
+
const trustRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-trust-'))
|
|
11
|
+
after(() => fs.rmSync(trustRoot, { recursive: true, force: true }))
|
|
12
|
+
const trustStore = path.join(trustRoot, 'trusted-controls.json')
|
|
13
|
+
const options = { detect: () => ({}), trustStore }
|
|
14
|
+
// CI=true trusts every control, so trust tests run as a developer machine.
|
|
15
|
+
const developerEnv = { ...process.env, CI: '' }
|
|
16
|
+
const trust = root => trustControls(controlsTrustPlan(root), { trustStore })
|
|
10
17
|
function fixture(t, checks = [], extra = {}) {
|
|
11
18
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-controls-'))
|
|
12
19
|
t.after(() => fs.rmSync(root, { recursive: true, force: true }))
|
|
@@ -19,6 +26,7 @@ function fixture(t, checks = [], extra = {}) {
|
|
|
19
26
|
write('tools/version', '1')
|
|
20
27
|
write('source.ts', 'export const value = 1\n')
|
|
21
28
|
write('verify.cjs', "const fs = require('fs'); fs.appendFileSync('counter', 'x'); if (fs.readFileSync('source.ts', 'utf8').includes('BROKEN')) process.exit(1)")
|
|
29
|
+
trust(root)
|
|
22
30
|
return { root, write, policy: JSON.parse(fs.readFileSync(path.join(root, '.agent-os/quality.json'))), count: () => fs.readFileSync(path.join(root, 'counter'), 'utf8').length }
|
|
23
31
|
}
|
|
24
32
|
const required = { id: 'verify', command: ['node', 'verify.cjs'], required: true }
|
|
@@ -39,6 +47,27 @@ test('required failures block repeatedly; fixed code passes and Stop never rerun
|
|
|
39
47
|
assert.ok(fs.existsSync(started.statePath + '.report.json'))
|
|
40
48
|
})
|
|
41
49
|
|
|
50
|
+
test('an unfixable required failure releases Stop to the user after the bounded limit', t => {
|
|
51
|
+
const f = fixture(t, [required])
|
|
52
|
+
begin(f.root, options)
|
|
53
|
+
f.write('source.ts', 'BROKEN')
|
|
54
|
+
assert.equal(check(f.root, options).status, 'blocked')
|
|
55
|
+
assert.equal(hook(f.root, { stop_hook_active: false }).decision, 'block')
|
|
56
|
+
assert.equal(hook(f.root, { stop_hook_active: true }).decision, 'block')
|
|
57
|
+
assert.equal(hook(f.root, { stop_hook_active: true }).decision, 'block')
|
|
58
|
+
const released = hook(f.root, { stop_hook_active: true })
|
|
59
|
+
assert.equal(released.decision, undefined)
|
|
60
|
+
assert.match(released.systemMessage, /verify: failed/)
|
|
61
|
+
assert.equal(hook(f.root, { stop_hook_active: false }).decision, undefined)
|
|
62
|
+
|
|
63
|
+
f.write('source.ts', 'BROKEN again')
|
|
64
|
+
assert.equal(check(f.root, options).status, 'blocked')
|
|
65
|
+
assert.equal(hook(f.root, { stop_hook_active: true }).decision, 'block')
|
|
66
|
+
f.write('source.ts', 'export const value = 3')
|
|
67
|
+
assert.equal(check(f.root, options).status, 'ok')
|
|
68
|
+
assert.deepEqual(hook(f.root), {})
|
|
69
|
+
})
|
|
70
|
+
|
|
42
71
|
test('advisory failures and new exception signals do not gate delivery', t => {
|
|
43
72
|
const f = fixture(t, [{ ...required, required: false }])
|
|
44
73
|
f.write('source.ts', '// @ts-ignore\nexport const value = 1')
|
|
@@ -91,6 +120,19 @@ test('dynamic checks and failed static checks are never reused', t => {
|
|
|
91
120
|
}
|
|
92
121
|
})
|
|
93
122
|
|
|
123
|
+
test('finish keeps the baseline while a required control fails and closes it once it passes', t => {
|
|
124
|
+
const f = fixture(t, [required])
|
|
125
|
+
const started = begin(f.root, options)
|
|
126
|
+
f.write('source.ts', 'BROKEN')
|
|
127
|
+
const refused = finish(f.root, options)
|
|
128
|
+
assert.equal(refused.closed, false)
|
|
129
|
+
assert.equal(refused.evidence.status, 'blocked')
|
|
130
|
+
assert.equal(fs.existsSync(started.statePath), true)
|
|
131
|
+
f.write('source.ts', 'export const value = 4')
|
|
132
|
+
assert.equal(finish(f.root, options).closed, true)
|
|
133
|
+
assert.equal(fs.existsSync(started.statePath), false)
|
|
134
|
+
})
|
|
135
|
+
|
|
94
136
|
test('policy changes require explicit acknowledgement and cannot be cleared silently', t => {
|
|
95
137
|
const f = fixture(t, [required], { protectedFiles: ['verify.cjs'] })
|
|
96
138
|
begin(f.root, options)
|
|
@@ -98,11 +140,72 @@ test('policy changes require explicit acknowledgement and cannot be cleared sile
|
|
|
98
140
|
assert.equal(check(f.root, options).status, 'blocked')
|
|
99
141
|
assert.throws(() => clear(f.root), /Policy changed|policy changed/)
|
|
100
142
|
assert.equal(hook(f.root).decision, 'block')
|
|
101
|
-
const accepted = check(f.root, { ...options, acceptPolicyChange: 'Authorized replacement of obsolete check' })
|
|
102
|
-
assert.equal(accepted.status, 'ok')
|
|
143
|
+
const accepted = check(f.root, { ...options, env: developerEnv, acceptPolicyChange: 'Authorized replacement of obsolete check' })
|
|
103
144
|
assert.match(accepted.controls.policyAcknowledgement.reason, /Authorized/)
|
|
104
|
-
|
|
105
|
-
assert.
|
|
145
|
+
// The acknowledged policy is a new signature, so its commands need the developer's trust again.
|
|
146
|
+
assert.equal(accepted.status, 'blocked')
|
|
147
|
+
assert.ok(accepted.controls.untrusted)
|
|
148
|
+
trust(f.root)
|
|
149
|
+
const trusted = check(f.root, { ...options, env: developerEnv })
|
|
150
|
+
assert.equal(trusted.status, 'ok')
|
|
151
|
+
assert.match(trusted.controls.policyAcknowledgement.reason, /Authorized/)
|
|
152
|
+
assert.deepEqual(hook(f.root, {}, { env: developerEnv }), {})
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
test('untrusted repository commands never run and block delivery until the developer trusts them', t => {
|
|
156
|
+
const f = fixture(t, [required])
|
|
157
|
+
const untrustedStore = path.join(trustRoot, `untrusted-${Date.now()}.json`)
|
|
158
|
+
const untrusted = { ...options, env: developerEnv, trustStore: untrustedStore }
|
|
159
|
+
const started = begin(f.root, untrusted)
|
|
160
|
+
const evidence = check(f.root, untrusted)
|
|
161
|
+
assert.equal(evidence.status, 'blocked')
|
|
162
|
+
assert.deepEqual(evidence.controls.results, [])
|
|
163
|
+
assert.deepEqual(evidence.controls.untrusted.commands, [{ id: 'verify', command: ['node', 'verify.cjs'] }])
|
|
164
|
+
const trustRootArgument = evidence.controls.untrusted.trustCommand.match(/ trust --root "(.*)"$/)?.[1]
|
|
165
|
+
assert.equal(fs.realpathSync(trustRootArgument), fs.realpathSync(f.root))
|
|
166
|
+
assert.equal(evidence.controls.untrusted.trustCommand.startsWith('& '), process.platform === 'win32')
|
|
167
|
+
assert.equal(fs.existsSync(path.join(f.root, 'counter')), false)
|
|
168
|
+
assert.equal(finish(f.root, untrusted).closed, false)
|
|
169
|
+
// Untrusted controls are the developer's decision, so Stop lets the turn end at once.
|
|
170
|
+
const released = hook(f.root, { stop_hook_active: false }, { env: developerEnv })
|
|
171
|
+
assert.equal(released.decision, undefined)
|
|
172
|
+
assert.match(released.systemMessage, /not trusted on this machine.*verify \["node","verify\.cjs"\].* trust --root /)
|
|
173
|
+
|
|
174
|
+
trustControls(controlsTrustPlan(f.root), { trustStore: untrustedStore })
|
|
175
|
+
assert.equal(finish(f.root, untrusted).closed, true)
|
|
176
|
+
assert.equal(f.count(), 1)
|
|
177
|
+
assert.equal(fs.existsSync(started.statePath), false)
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
test('a CI environment runs declared controls without a trust record', t => {
|
|
181
|
+
const f = fixture(t, [required])
|
|
182
|
+
const env = { ...process.env, CI: 'true' }
|
|
183
|
+
const untrusted = { ...options, env, trustStore: path.join(trustRoot, `ci-${Date.now()}.json`) }
|
|
184
|
+
begin(f.root, untrusted)
|
|
185
|
+
const evidence = check(f.root, untrusted)
|
|
186
|
+
assert.equal(evidence.status, 'ok')
|
|
187
|
+
assert.equal(evidence.controls.untrusted, null)
|
|
188
|
+
assert.equal(f.count(), 1)
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
test('trust is shared by linked worktrees of the same repository', t => {
|
|
192
|
+
const f = fixture(t, [required])
|
|
193
|
+
execFileSync('git', ['-C', f.root, '-c', 'user.name=t', '-c', 'user.email=t@t', 'add', '.'])
|
|
194
|
+
execFileSync('git', ['-C', f.root, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'fixture'])
|
|
195
|
+
const linked = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-controls-linked-'))
|
|
196
|
+
fs.rmSync(linked, { recursive: true })
|
|
197
|
+
t.after(() => fs.rmSync(linked, { recursive: true, force: true }))
|
|
198
|
+
execFileSync('git', ['-C', f.root, 'worktree', 'add', '-q', '-b', 'linked', linked])
|
|
199
|
+
assert.equal(controlsTrustPlan(linked).repository, controlsTrustPlan(f.root).repository)
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
test('the trust command refuses to record trust without an interactive terminal', t => {
|
|
203
|
+
const f = fixture(t, [required])
|
|
204
|
+
const runner = path.join(path.dirname(fileURLToPath(import.meta.url)), 'quality-delta.mjs')
|
|
205
|
+
const result = spawnSync(process.execPath, [runner, 'trust', '--root', f.root], { encoding: 'utf8', input: 'y\n' })
|
|
206
|
+
assert.equal(result.status, 2)
|
|
207
|
+
assert.match(result.stdout, /verify \(required\): \["node","verify.cjs"\]/)
|
|
208
|
+
assert.match(result.stderr, /interactive terminal/)
|
|
106
209
|
})
|
|
107
210
|
|
|
108
211
|
test('missing executable, missing tool inputs, timeout, and malformed policy cannot report success', t => {
|
|
@@ -173,3 +276,26 @@ test('external executable permission changes invalidate a cached pass', { skip:
|
|
|
173
276
|
assert.equal(hook(f.root).decision, 'block')
|
|
174
277
|
assert.equal(check(f.root, options).status, 'blocked')
|
|
175
278
|
})
|
|
279
|
+
|
|
280
|
+
test('stale control evidence is bounded at Stop', t => {
|
|
281
|
+
const f = fixture(t, [required])
|
|
282
|
+
begin(f.root, options)
|
|
283
|
+
assert.equal(check(f.root, options).status, 'ok')
|
|
284
|
+
const env = { ...process.env, CONTROL_FIXTURE: 'changed after check' }
|
|
285
|
+
assert.match(hook(f.root, { stop_hook_active: false }, { env }).reason, /control evidence is stale/)
|
|
286
|
+
assert.equal(hook(f.root, { stop_hook_active: true }, { env }).decision, 'block')
|
|
287
|
+
assert.equal(hook(f.root, { stop_hook_active: true }, { env }).decision, 'block')
|
|
288
|
+
assert.match(hook(f.root, { stop_hook_active: true }, { env }).systemMessage, /still stale/)
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
test('a released stale-check block does not use up the failing-controls budget', t => {
|
|
292
|
+
const f = fixture(t, [required])
|
|
293
|
+
begin(f.root, options)
|
|
294
|
+
f.write('source.ts', 'BROKEN')
|
|
295
|
+
assert.equal(hook(f.root, { stop_hook_active: false }).decision, 'block')
|
|
296
|
+
assert.equal(hook(f.root, { stop_hook_active: true }).decision, 'block')
|
|
297
|
+
assert.equal(hook(f.root, { stop_hook_active: true }).decision, 'block')
|
|
298
|
+
assert.match(hook(f.root, { stop_hook_active: true }).systemMessage, /has not run/)
|
|
299
|
+
assert.equal(check(f.root, options).status, 'blocked')
|
|
300
|
+
assert.match(hook(f.root, { stop_hook_active: false }).reason, /Project controls block delivery/)
|
|
301
|
+
})
|
|
@@ -5,12 +5,18 @@ import { createHash, randomUUID } from 'node:crypto'
|
|
|
5
5
|
import fs from 'node:fs'
|
|
6
6
|
import path from 'node:path'
|
|
7
7
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
prepareControls, runControls, scanSignals, signalDelta, blockingControls, POLICY_PATH,
|
|
10
|
+
readPolicy, controlSignature, controlsTrusted, recordControlsTrust, DEFAULT_TRUST_STORE
|
|
11
|
+
} from './project-controls.mjs'
|
|
12
|
+
import { complexityDelta, findLizard, lizardFunctions, withTemporaryFiles } from './analyzers.mjs'
|
|
9
13
|
|
|
10
14
|
export const STATE_SCHEMA = 2
|
|
11
15
|
export const STATE_FILE_NAME = '.agent-os-quality-ratchet.json'
|
|
12
16
|
export const QUALITY_HOOK_MARKER = '--agent-os-hook=quality-ratchet'
|
|
13
17
|
export const HOOK_TIMEOUT_SECONDS = 10
|
|
18
|
+
export const STOP_BLOCK_LIMIT = 3
|
|
19
|
+
export const STALE_STATE_DAYS = 14
|
|
14
20
|
|
|
15
21
|
const SOURCE_EXTENSIONS = new Set([
|
|
16
22
|
'.c', '.cc', '.cpp', '.cxx', '.cs', '.css', '.go', '.h', '.hpp', '.java', '.js', '.jsx',
|
|
@@ -184,7 +190,7 @@ function absolutePath(root, relativePath) {
|
|
|
184
190
|
return target
|
|
185
191
|
}
|
|
186
192
|
|
|
187
|
-
function isSourcePath(relativePath) {
|
|
193
|
+
export function isSourcePath(relativePath) {
|
|
188
194
|
const normalized = relativePath.replaceAll('\\', '/')
|
|
189
195
|
if (normalized.split('/').some((part) => ['.git', 'node_modules', 'dist', 'build', 'coverage'].includes(part))) {
|
|
190
196
|
return false
|
|
@@ -348,9 +354,17 @@ function normalizeAnalyzer(value, name) {
|
|
|
348
354
|
}
|
|
349
355
|
|
|
350
356
|
export function detectOptionalAnalyzers({ spawn = spawnSync } = {}) {
|
|
357
|
+
const lizard = findLizard({ spawn })
|
|
358
|
+
? {
|
|
359
|
+
status: 'integrated',
|
|
360
|
+
available: true,
|
|
361
|
+
integrated: true,
|
|
362
|
+
reason: 'lizard computes cyclomatic complexity deltas for touched source files.'
|
|
363
|
+
}
|
|
364
|
+
: unavailableAnalyzer('lizard is not installed; complexity deltas are unavailable and core Node evidence is used.')
|
|
351
365
|
return Object.fromEntries(OPTIONAL_ANALYZERS.map((name) => [
|
|
352
366
|
name,
|
|
353
|
-
commandDetected(name, spawn)
|
|
367
|
+
name === 'lizard' ? lizard : commandDetected(name, spawn)
|
|
354
368
|
? {
|
|
355
369
|
status: 'detected-not-integrated',
|
|
356
370
|
available: true,
|
|
@@ -510,6 +524,56 @@ function evidenceFor(state, candidate, dependencies, analyzers) {
|
|
|
510
524
|
}
|
|
511
525
|
}
|
|
512
526
|
|
|
527
|
+
// Entry content is recoverable only for paths that were clean at begin: the baseline stores
|
|
528
|
+
// hashes, not file contents. The working tree may hold either the filtered (line-ending converted)
|
|
529
|
+
// or the raw blob form, so the one matching the recorded hash is used.
|
|
530
|
+
function entryContent(root, entry, relativePath) {
|
|
531
|
+
const record = entry.files.find((file) => file.path === relativePath)
|
|
532
|
+
if (!record || record.kind !== 'file' || !entry.head || entry.dirtyPaths.includes(relativePath)) return null
|
|
533
|
+
const spec = `${entry.head}:${relativePath}`
|
|
534
|
+
for (const args of [['cat-file', '--filters', spec], ['cat-file', 'blob', spec]]) {
|
|
535
|
+
const content = runGit(root, args, { allowFailure: true })
|
|
536
|
+
if (content !== null && digest(content) === record.hash) return content
|
|
537
|
+
}
|
|
538
|
+
return null
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function complexityEvidence(root, entry, sourceFiles, analyze) {
|
|
542
|
+
const touched = [...sourceFiles.added, ...sourceFiles.changed].sort()
|
|
543
|
+
if (!touched.length) return { status: 'available', reason: 'No touched source files remain.', ...complexityDelta([], []), beforeUnavailable: [] }
|
|
544
|
+
try {
|
|
545
|
+
const after = analyze(root, touched)
|
|
546
|
+
if (after === null) {
|
|
547
|
+
return { status: 'unavailable', reason: 'lizard is not installed; complexity deltas were not computed.' }
|
|
548
|
+
}
|
|
549
|
+
const beforeFiles = sourceFiles.changed.map((relativePath) => [relativePath, entryContent(root, entry, relativePath)])
|
|
550
|
+
const known = beforeFiles.filter(([, content]) => content !== null)
|
|
551
|
+
const beforeUnavailable = beforeFiles.filter(([, content]) => content === null).map(([relativePath]) => relativePath)
|
|
552
|
+
const before = known.length ? withTemporaryFiles(known, (directory) => analyze(directory, known.map(([file]) => file))) : []
|
|
553
|
+
const comparable = after.filter((fn) => !beforeUnavailable.includes(fn.file))
|
|
554
|
+
return {
|
|
555
|
+
status: 'available',
|
|
556
|
+
reason: 'lizard cyclomatic complexity for touched source files.',
|
|
557
|
+
...complexityDelta(before, comparable),
|
|
558
|
+
beforeUnavailable
|
|
559
|
+
}
|
|
560
|
+
} catch (cause) {
|
|
561
|
+
return { status: 'unavailable', reason: `Complexity analysis failed: ${cause.message}` }
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function complexitySignals(complexity, policy) {
|
|
566
|
+
const threshold = policy.complexity?.threshold
|
|
567
|
+
if (!threshold || complexity.status !== 'available') return []
|
|
568
|
+
return complexity.functions.filter((fn) => fn.after > threshold).map((fn) => ({
|
|
569
|
+
path: fn.path,
|
|
570
|
+
line: fn.line,
|
|
571
|
+
rule: 'complexity',
|
|
572
|
+
text: `${fn.function} cyclomatic complexity ${fn.before ?? 'new'} -> ${fn.after} (threshold ${threshold})`,
|
|
573
|
+
required: policy.blockSignals.includes('complexity')
|
|
574
|
+
}))
|
|
575
|
+
}
|
|
576
|
+
|
|
513
577
|
function readState(context) {
|
|
514
578
|
if (!fs.existsSync(context.statePath)) return null
|
|
515
579
|
let state
|
|
@@ -577,8 +641,31 @@ function baselineState(context, candidate, dependencies, analyzers) {
|
|
|
577
641
|
}
|
|
578
642
|
}
|
|
579
643
|
|
|
644
|
+
// Baselines now outlive a single turn, so an attempt that never reached `finish` or `clear` leaves
|
|
645
|
+
// its state behind. Remove other sessions' state and reports untouched for STALE_STATE_DAYS.
|
|
646
|
+
function pruneStaleStates(context, now = Date.now()) {
|
|
647
|
+
let names
|
|
648
|
+
try {
|
|
649
|
+
names = fs.readdirSync(context.gitDir)
|
|
650
|
+
} catch {
|
|
651
|
+
return
|
|
652
|
+
}
|
|
653
|
+
const limit = STALE_STATE_DAYS * 24 * 60 * 60 * 1000
|
|
654
|
+
for (const name of names) {
|
|
655
|
+
if (!name.startsWith(`${STATE_FILE_NAME}.`)) continue
|
|
656
|
+
const file = path.join(context.gitDir, name)
|
|
657
|
+
if (file === context.statePath) continue
|
|
658
|
+
try {
|
|
659
|
+
if (now - fs.statSync(file).mtimeMs > limit) fs.rmSync(file, { force: true })
|
|
660
|
+
} catch {
|
|
661
|
+
// Another session may remove its own state concurrently.
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
580
666
|
export function begin(cwd = process.cwd(), { detect = detectOptionalAnalyzers, env = process.env } = {}) {
|
|
581
667
|
const context = repositoryContext(cwd, env)
|
|
668
|
+
pruneStaleStates(context)
|
|
582
669
|
if (fs.existsSync(context.statePath)) {
|
|
583
670
|
readState(context)
|
|
584
671
|
error(`An active quality ratchet baseline already exists for this session and worktree at ${context.statePath}. Run clear before beginning a new delivery.`, 'BASELINE_ACTIVE')
|
|
@@ -598,7 +685,21 @@ export function begin(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
|
|
|
598
685
|
}
|
|
599
686
|
}
|
|
600
687
|
|
|
601
|
-
|
|
688
|
+
function defaultComplexityAnalyzer() {
|
|
689
|
+
let launcher
|
|
690
|
+
return (cwd, files) => {
|
|
691
|
+
if (launcher === undefined) launcher = findLizard()
|
|
692
|
+
return lizardFunctions(cwd, files, { launcher })
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
export function check(cwd = process.cwd(), {
|
|
697
|
+
detect = detectOptionalAnalyzers,
|
|
698
|
+
env = process.env,
|
|
699
|
+
acceptPolicyChange = '',
|
|
700
|
+
analyzeComplexity = defaultComplexityAnalyzer(),
|
|
701
|
+
trustStore = DEFAULT_TRUST_STORE
|
|
702
|
+
} = {}) {
|
|
602
703
|
const context = repositoryContext(cwd, env)
|
|
603
704
|
const state = readState(context)
|
|
604
705
|
if (!state) error(`No active quality ratchet baseline exists for ${context.root}. Run begin before the first mutation.`, 'BASELINE_MISSING')
|
|
@@ -614,13 +715,25 @@ export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
|
|
|
614
715
|
const policyChanged = oldSignature ? oldSignature !== prepared.signature : fs.existsSync(path.join(context.root, POLICY_PATH))
|
|
615
716
|
if (acceptPolicyChange && !acceptPolicyChange.trim()) error('Policy acknowledgement requires a reason.', 'ARGUMENTS')
|
|
616
717
|
const accepted = policyChanged && Boolean(acceptPolicyChange.trim())
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
718
|
+
evidence.complexity = complexityEvidence(context.root, state.entry, evidence.sourceFiles, analyzeComplexity)
|
|
719
|
+
const signals = [
|
|
720
|
+
...signalDelta(state.entry.files, files).map(signal => ({
|
|
721
|
+
...signal, required: prepared.policy.blockSignals.includes(signal.rule)
|
|
722
|
+
})),
|
|
723
|
+
...complexitySignals(evidence.complexity, prepared.policy)
|
|
724
|
+
]
|
|
725
|
+
// CI already runs the repository's own code in a disposable checkout and cannot answer a prompt.
|
|
726
|
+
const ciEnvironment = ['true', '1'].includes(String(env.CI ?? '').toLowerCase())
|
|
727
|
+
const trusted = !prepared.policy.checks.length || ciEnvironment ||
|
|
728
|
+
controlsTrusted(repositoryIdentity(context.root), prepared.signature, trustStore)
|
|
729
|
+
const results = (policyChanged && !accepted) || !trusted ? [] : runControls(context.root, prepared, state.lastCheck?.evidence?.controls, env)
|
|
621
730
|
const after = configured ? prepareControls(context.root, snapshot(context.root).files, env) : prepared
|
|
622
731
|
evidence.controls = {
|
|
623
732
|
fingerprint: prepared.fingerprint, policyChanged: policyChanged && !accepted,
|
|
733
|
+
untrusted: trusted ? null : {
|
|
734
|
+
commands: prepared.policy.checks.map(entry => ({ id: entry.id, command: entry.command })),
|
|
735
|
+
trustCommand: developerTrustCommand(context.root)
|
|
736
|
+
},
|
|
624
737
|
policyAcknowledgement: accepted ? { before: oldSignature || null, after: prepared.signature, reason: acceptPolicyChange.trim() } : state.policyAcknowledgement || null,
|
|
625
738
|
stale: after.fingerprint !== prepared.fingerprint, results, signals
|
|
626
739
|
}
|
|
@@ -639,6 +752,35 @@ export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
|
|
|
639
752
|
return evidence
|
|
640
753
|
}
|
|
641
754
|
|
|
755
|
+
// Trust is shared by every worktree of one repository, so it keys on the common Git directory.
|
|
756
|
+
function repositoryIdentity(root) {
|
|
757
|
+
const common = path.resolve(root, runGit(root, ['rev-parse', '--git-common-dir']).trim())
|
|
758
|
+
let real = common
|
|
759
|
+
try {
|
|
760
|
+
real = fs.realpathSync(common)
|
|
761
|
+
} catch {
|
|
762
|
+
// Keep the resolved path when the directory cannot be canonicalized.
|
|
763
|
+
}
|
|
764
|
+
return normalizePath(real)
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
export function controlsTrustPlan(cwd = process.cwd()) {
|
|
768
|
+
const root = path.resolve(runGit(path.resolve(cwd), ['rev-parse', '--show-toplevel']).trim())
|
|
769
|
+
const policy = readPolicy(root)
|
|
770
|
+
return {
|
|
771
|
+
root,
|
|
772
|
+
repository: repositoryIdentity(root),
|
|
773
|
+
signature: controlSignature(root, policy),
|
|
774
|
+
checks: policy.checks.map(entry => ({ id: entry.id, command: entry.command, required: entry.required === true })),
|
|
775
|
+
protectedFiles: policy.protectedFiles
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
export function trustControls(plan, { trustStore = DEFAULT_TRUST_STORE } = {}) {
|
|
780
|
+
recordControlsTrust(plan.repository, plan.signature, plan.checks, trustStore)
|
|
781
|
+
return { trustStore, trusted: plan.checks.length }
|
|
782
|
+
}
|
|
783
|
+
|
|
642
784
|
export function clear(cwd = process.cwd(), { env = process.env } = {}) {
|
|
643
785
|
const context = repositoryContext(cwd, env)
|
|
644
786
|
const state = readState(context)
|
|
@@ -649,6 +791,16 @@ export function clear(cwd = process.cwd(), { env = process.env } = {}) {
|
|
|
649
791
|
return { statePath: context.statePath, cleared: true }
|
|
650
792
|
}
|
|
651
793
|
|
|
794
|
+
// Closes a delivered attempt: it records a fresh check and removes the baseline only when that
|
|
795
|
+
// check passes. A blocked check keeps the baseline so delivery stays blocked.
|
|
796
|
+
export function finish(cwd = process.cwd(), options = {}) {
|
|
797
|
+
const evidence = check(cwd, options)
|
|
798
|
+
const context = repositoryContext(cwd, options.env ?? process.env)
|
|
799
|
+
if (evidence.status !== 'ok') return { evidence, statePath: context.statePath, closed: false }
|
|
800
|
+
fs.rmSync(context.statePath, { force: true })
|
|
801
|
+
return { evidence, statePath: context.statePath, closed: true }
|
|
802
|
+
}
|
|
803
|
+
|
|
652
804
|
function allowResult() {
|
|
653
805
|
return {}
|
|
654
806
|
}
|
|
@@ -657,10 +809,47 @@ function blockResult(reason) {
|
|
|
657
809
|
return { decision: 'block', reason }
|
|
658
810
|
}
|
|
659
811
|
|
|
812
|
+
// Every Stop block is bounded. A check can stay stale or a required control can keep failing for
|
|
813
|
+
// reasons the agent cannot fix (a missing tool, a flaky dependency, a failing runner), and the
|
|
814
|
+
// host's own continuation cap resets whenever the agent calls a tool. After repeated re-entered
|
|
815
|
+
// Stops on the same unchanged candidate, the hook hands the decision to the user instead of
|
|
816
|
+
// looping. The baseline stays active, so `finish` still refuses delivery until a passing check.
|
|
817
|
+
function boundedBlockResult(context, state, kind, fingerprint, reason, releaseMessage, payload) {
|
|
818
|
+
const key = `${kind}:${fingerprint}`
|
|
819
|
+
const released = state.stopRelease?.key === key
|
|
820
|
+
const count = state.stopBlocks?.key === key ? state.stopBlocks.count + 1 : 1
|
|
821
|
+
if (released || (payload?.stop_hook_active === true && count > STOP_BLOCK_LIMIT)) {
|
|
822
|
+
if (!released) {
|
|
823
|
+
state.stopRelease = { key }
|
|
824
|
+
writeState(context, state)
|
|
825
|
+
}
|
|
826
|
+
return { systemMessage: `${releaseMessage} Stopping is allowed so you can decide how to proceed; the baseline stays active and delivery stays blocked until a passing check.` }
|
|
827
|
+
}
|
|
828
|
+
state.stopBlocks = { key, count }
|
|
829
|
+
writeState(context, state)
|
|
830
|
+
return blockResult(reason)
|
|
831
|
+
}
|
|
832
|
+
|
|
660
833
|
function lifecycleCommand(command) {
|
|
661
834
|
return `"${process.execPath}" "${fileURLToPath(import.meta.url)}" ${command}`
|
|
662
835
|
}
|
|
663
836
|
|
|
837
|
+
// A developer pastes this into their own terminal, so it names the worktree and, on Windows, uses
|
|
838
|
+
// the PowerShell call operator that a quoted executable path needs.
|
|
839
|
+
function developerTrustCommand(root) {
|
|
840
|
+
const command = `${lifecycleCommand('trust')} --root "${root}"`
|
|
841
|
+
return process.platform === 'win32' ? `& ${command}` : command
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// The guard hooks freeze accepted intents and specs only while a delivery baseline is active.
|
|
845
|
+
export function deliveryBaselineActive(cwd = process.cwd(), payload = {}, { env = process.env } = {}) {
|
|
846
|
+
try {
|
|
847
|
+
return fs.existsSync(repositoryContext(cwd, hookSessionEnvironment(payload, env)).statePath)
|
|
848
|
+
} catch {
|
|
849
|
+
return false
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
664
853
|
export function hook(cwd = process.cwd(), payload = {}, { env = process.env } = {}) {
|
|
665
854
|
let context
|
|
666
855
|
try {
|
|
@@ -677,8 +866,15 @@ export function hook(cwd = process.cwd(), payload = {}, { env = process.env } =
|
|
|
677
866
|
try {
|
|
678
867
|
candidate = candidateSnapshot(context.root, state.entry, { includeFiles: false })
|
|
679
868
|
} catch (cause) {
|
|
680
|
-
|
|
681
|
-
|
|
869
|
+
return boundedBlockResult(context, state, 'inspect', 'uninspectable',
|
|
870
|
+
`Quality ratchet could not inspect the candidate: ${cause.message}. Run the quality-ratchet check and retry.`,
|
|
871
|
+
`Quality ratchet still cannot inspect the candidate: ${cause.message}.`, payload)
|
|
872
|
+
}
|
|
873
|
+
// An inspection failure has no candidate fingerprint, so its bound resets once inspection works.
|
|
874
|
+
if ([state.stopRelease?.key, state.stopBlocks?.key].some((key) => key?.startsWith('inspect:'))) {
|
|
875
|
+
if (state.stopRelease?.key?.startsWith('inspect:')) delete state.stopRelease
|
|
876
|
+
if (state.stopBlocks?.key?.startsWith('inspect:')) delete state.stopBlocks
|
|
877
|
+
writeState(context, state)
|
|
682
878
|
}
|
|
683
879
|
const fresh = state.lastCheck?.candidateFingerprint === candidate.fingerprint
|
|
684
880
|
if (fresh) {
|
|
@@ -686,17 +882,35 @@ export function hook(cwd = process.cwd(), payload = {}, { env = process.env } =
|
|
|
686
882
|
const configured = fs.existsSync(path.join(context.root, POLICY_PATH)) || controls?.results?.length || controls?.policyChanged
|
|
687
883
|
if (configured) {
|
|
688
884
|
const prepared = prepareControls(context.root, snapshot(context.root).files, env)
|
|
689
|
-
if (!controls || prepared.fingerprint !== controls.fingerprint)
|
|
885
|
+
if (!controls || prepared.fingerprint !== controls.fingerprint) {
|
|
886
|
+
return boundedBlockResult(context, state, 'controls-stale', candidate.fingerprint,
|
|
887
|
+
`Project control evidence is stale. Run \`${lifecycleCommand('check')}\` before stopping.`,
|
|
888
|
+
'Quality ratchet: project control evidence is still stale for the unchanged candidate.', payload)
|
|
889
|
+
}
|
|
690
890
|
}
|
|
691
891
|
const blockers = blockingControls(controls)
|
|
692
|
-
|
|
693
|
-
|
|
892
|
+
// The agent cannot resolve untrusted controls, so blocking would only spend continuations.
|
|
893
|
+
if (controls?.untrusted && blockers.length === 1) {
|
|
894
|
+
return {
|
|
895
|
+
systemMessage: 'Quality ratchet: this repository declares project controls that are not trusted on this machine, so none ran: ' +
|
|
896
|
+
controls.untrusted.commands.map((entry) => `${entry.id} ${JSON.stringify(entry.command)}`).join('; ') +
|
|
897
|
+
`. To review and trust them, run in a terminal: ${controls.untrusted.trustCommand}. Delivery stays blocked until then.`
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
if (blockers.length) {
|
|
901
|
+
const summary = blockers.slice(0, 5).join('; ')
|
|
902
|
+
return boundedBlockResult(context, state, 'controls', candidate.fingerprint,
|
|
903
|
+
`Project controls block delivery: ${summary}. Fix the reported problem; do not rerun unchanged failing checks. If it cannot be fixed in this session, report the blocker and stop.`,
|
|
904
|
+
`Quality ratchet: required project controls still fail for the unchanged candidate: ${summary}.`, payload)
|
|
905
|
+
}
|
|
906
|
+
// A passing check keeps the baseline: a turn can end mid-delivery to ask the developer, and
|
|
907
|
+
// the next turn still compares against the exact entry state. `finish` or `clear` ends it.
|
|
694
908
|
return allowResult()
|
|
695
909
|
}
|
|
696
|
-
const
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
910
|
+
const missing = state.lastCheck ? 'is stale for the current candidate' : 'has not run for this candidate'
|
|
911
|
+
return boundedBlockResult(context, state, 'stale', candidate.fingerprint,
|
|
912
|
+
`Quality ratchet check ${missing}. Run \`${lifecycleCommand('check')}\` before stopping, also when you only pause to ask the developer; the baseline stays active across turns.`,
|
|
913
|
+
`Quality ratchet: the check ${missing} after repeated Stop blocks.`, payload)
|
|
700
914
|
} catch (cause) {
|
|
701
915
|
const reason = cause instanceof QualityRatchetError
|
|
702
916
|
? cause.message
|
|
@@ -709,6 +923,16 @@ function humanList(values) {
|
|
|
709
923
|
return values.length ? values.join(', ') : 'none'
|
|
710
924
|
}
|
|
711
925
|
|
|
926
|
+
function complexityLines(complexity) {
|
|
927
|
+
if (!complexity) return []
|
|
928
|
+
if (complexity.status !== 'available') return [`Complexity: unavailable (${complexity.reason})`]
|
|
929
|
+
return [
|
|
930
|
+
`Complexity (touched functions): ${complexity.increased} increased, ${complexity.added} new, ${complexity.decreased} decreased or removed; max ${complexity.maxAfter}`,
|
|
931
|
+
...complexity.functions.slice(0, 10).map((fn) => ` ${fn.path}:${fn.line} ${fn.function}: ${fn.before ?? 'new'} -> ${fn.after}`),
|
|
932
|
+
...(complexity.beforeUnavailable.length ? [` before unavailable (dirty at begin): ${humanList(complexity.beforeUnavailable)}`] : [])
|
|
933
|
+
]
|
|
934
|
+
}
|
|
935
|
+
|
|
712
936
|
export function formatEvidence(evidence) {
|
|
713
937
|
const lines = [
|
|
714
938
|
'Agent OS quality-ratchet evidence',
|
|
@@ -721,12 +945,18 @@ export function formatEvidence(evidence) {
|
|
|
721
945
|
`Touched legacy after: ${evidence.touchedLegacy.after.status} (${humanList(evidence.touchedLegacy.after.files)})`,
|
|
722
946
|
`Package dependencies: +${evidence.packageDependencies.added.length} -${evidence.packageDependencies.removed.length} ~${evidence.packageDependencies.updated.length} (${evidence.packageDependencies.status})`,
|
|
723
947
|
...OPTIONAL_ANALYZERS.map((name) => `Optional analyzer ${name}: ${evidence.optionalAnalyzers.candidate[name].status} — ${evidence.optionalAnalyzers.candidate[name].reason}`),
|
|
948
|
+
...complexityLines(evidence.complexity),
|
|
724
949
|
`Candidate fingerprint: ${evidence.candidateFingerprint}`,
|
|
725
950
|
...(evidence.controls ? [
|
|
726
951
|
`Project controls: ${evidence.status}; ${evidence.controls.results.length} checks; ${evidence.controls.signals.length} new advisory/required signals`,
|
|
727
952
|
...evidence.controls.results.filter(result => result.status !== 'passed').map(result => ` ${result.id}: ${result.status} ${result.detail || result.output?.slice(0, 500) || ''}`),
|
|
728
953
|
...evidence.controls.signals.filter(signal => !signal.required).slice(0, 5).map(signal => ` advisory: ${signal.path}:${signal.line} ${signal.rule}: ${signal.text}`),
|
|
729
954
|
...blockingControls(evidence.controls).slice(0, 5).map(reason => ` blocked: ${reason}`),
|
|
955
|
+
...(evidence.controls.untrusted ? [
|
|
956
|
+
' Untrusted repository commands that were not run:',
|
|
957
|
+
...evidence.controls.untrusted.commands.map(entry => ` ${entry.id}: ${JSON.stringify(entry.command)}`),
|
|
958
|
+
` The developer reviews and trusts them by running this in an interactive terminal: ${evidence.controls.untrusted.trustCommand}`
|
|
959
|
+
] : []),
|
|
730
960
|
`Full report: ${evidence.reportPath}; use --json for structured output.`
|
|
731
961
|
] : [])
|
|
732
962
|
]
|
|
@@ -742,7 +972,7 @@ function parseArguments(args) {
|
|
|
742
972
|
result.json = true
|
|
743
973
|
} else if (argument === '--accept-policy-change') {
|
|
744
974
|
const reason = args[++index]
|
|
745
|
-
if (result.command
|
|
975
|
+
if (!['check', 'finish'].includes(result.command) || !reason?.trim() || reason.startsWith('--')) error('--accept-policy-change requires check or finish and a reason.', 'ARGUMENTS')
|
|
746
976
|
result.acceptPolicyChange = reason
|
|
747
977
|
} else if (argument === '--root') {
|
|
748
978
|
const root = args[index + 1]
|
|
@@ -759,12 +989,41 @@ function parseArguments(args) {
|
|
|
759
989
|
}
|
|
760
990
|
index += 1
|
|
761
991
|
}
|
|
762
|
-
if (!['begin', 'check', 'clear', 'hook'].includes(result.command)) {
|
|
763
|
-
error(`Unknown command "${result.command}". Use begin, check, clear, or hook.`, 'ARGUMENTS')
|
|
992
|
+
if (!['begin', 'check', 'finish', 'clear', 'trust', 'hook'].includes(result.command)) {
|
|
993
|
+
error(`Unknown command "${result.command}". Use begin, check, finish, clear, trust, or hook.`, 'ARGUMENTS')
|
|
764
994
|
}
|
|
765
995
|
return result
|
|
766
996
|
}
|
|
767
997
|
|
|
998
|
+
// Trust is the developer's decision, so it needs an interactive terminal. An agent's shell tool has
|
|
999
|
+
// no TTY; this is a speed bump and a visible prompt, not a tamper-proof boundary.
|
|
1000
|
+
async function runTrust(root, { input = process.stdin, output = process.stdout } = {}) {
|
|
1001
|
+
const plan = controlsTrustPlan(root)
|
|
1002
|
+
if (!plan.checks.length) {
|
|
1003
|
+
output.write(`No project controls are declared in ${POLICY_PATH}.\n`)
|
|
1004
|
+
return
|
|
1005
|
+
}
|
|
1006
|
+
output.write(`Repository: ${plan.root}\nCommands declared in ${POLICY_PATH}:\n`)
|
|
1007
|
+
for (const entry of plan.checks) output.write(` ${entry.id}${entry.required ? ' (required)' : ''}: ${JSON.stringify(entry.command)}\n`)
|
|
1008
|
+
if (plan.protectedFiles.length) output.write(`Protected files: ${plan.protectedFiles.join(', ')}\n`)
|
|
1009
|
+
if (!input.isTTY || !output.isTTY) {
|
|
1010
|
+
error('trust must be run by the developer in an interactive terminal; an agent must not run it.', 'TRUST_INTERACTIVE')
|
|
1011
|
+
}
|
|
1012
|
+
const readline = await import('node:readline/promises')
|
|
1013
|
+
const prompt = readline.createInterface({ input, output })
|
|
1014
|
+
try {
|
|
1015
|
+
const answer = (await prompt.question('Run these commands during quality-ratchet check on this machine? [y/N] ')).trim().toLowerCase()
|
|
1016
|
+
if (answer !== 'y' && answer !== 'yes') {
|
|
1017
|
+
output.write('Not trusted. check will keep reporting these controls as untrusted.\n')
|
|
1018
|
+
return
|
|
1019
|
+
}
|
|
1020
|
+
} finally {
|
|
1021
|
+
prompt.close()
|
|
1022
|
+
}
|
|
1023
|
+
const result = trustControls(plan)
|
|
1024
|
+
output.write(`Trusted ${result.trusted} commands for this repository in ${result.trustStore}. Changing ${POLICY_PATH} or a protected file requires trusting again.\n`)
|
|
1025
|
+
}
|
|
1026
|
+
|
|
768
1027
|
function readHookPayload() {
|
|
769
1028
|
try {
|
|
770
1029
|
const input = fs.readFileSync(0, 'utf8').trim()
|
|
@@ -774,9 +1033,13 @@ function readHookPayload() {
|
|
|
774
1033
|
}
|
|
775
1034
|
}
|
|
776
1035
|
|
|
777
|
-
function main() {
|
|
1036
|
+
async function main() {
|
|
778
1037
|
try {
|
|
779
1038
|
const options = parseArguments(process.argv.slice(2))
|
|
1039
|
+
if (options.command === 'trust') {
|
|
1040
|
+
await runTrust(options.root)
|
|
1041
|
+
return
|
|
1042
|
+
}
|
|
780
1043
|
if (options.command === 'begin') {
|
|
781
1044
|
const result = begin(options.root)
|
|
782
1045
|
console.log(`Quality ratchet baseline started for ${result.fileCount} files (${result.fingerprint}). State: ${result.statePath}`)
|
|
@@ -788,6 +1051,17 @@ function main() {
|
|
|
788
1051
|
if (evidence.status !== 'ok') process.exitCode = 1
|
|
789
1052
|
return
|
|
790
1053
|
}
|
|
1054
|
+
if (options.command === 'finish') {
|
|
1055
|
+
const result = finish(options.root, { acceptPolicyChange: options.acceptPolicyChange })
|
|
1056
|
+
console.log(options.json ? JSON.stringify(result) : [
|
|
1057
|
+
formatEvidence(result.evidence),
|
|
1058
|
+
result.closed
|
|
1059
|
+
? `Quality ratchet baseline closed at ${result.statePath}.`
|
|
1060
|
+
: `Quality ratchet check is ${result.evidence.status}; the baseline stays active at ${result.statePath}.`
|
|
1061
|
+
].join('\n'))
|
|
1062
|
+
if (!result.closed) process.exitCode = 1
|
|
1063
|
+
return
|
|
1064
|
+
}
|
|
791
1065
|
if (options.command === 'clear') {
|
|
792
1066
|
const result = clear(options.root)
|
|
793
1067
|
console.log(`Quality ratchet baseline cleared at ${result.statePath}.`)
|
|
@@ -798,7 +1072,7 @@ function main() {
|
|
|
798
1072
|
console.log(JSON.stringify(result))
|
|
799
1073
|
} catch (cause) {
|
|
800
1074
|
console.error(`quality-ratchet: ${cause.message}`)
|
|
801
|
-
process.exitCode = cause instanceof QualityRatchetError && cause.code
|
|
1075
|
+
process.exitCode = cause instanceof QualityRatchetError && ['ARGUMENTS', 'TRUST_INTERACTIVE'].includes(cause.code) ? 2 : 1
|
|
802
1076
|
}
|
|
803
1077
|
}
|
|
804
1078
|
|