@sockulags/agent-os 0.14.0 → 0.16.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 +102 -49
- package/cli/doctor.mjs +307 -0
- package/cli/index.mjs +328 -151
- package/cli/index.test.mjs +406 -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 +65 -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 +13 -6
- package/{skills → plugins/agent-os-core/skills}/plain-voice/SKILL.md +7 -4
- package/plugins/agent-os-core/skills/plan-work/SKILL.md +133 -0
- package/plugins/agent-os-core/skills/plan-work/references/elicitation.md +32 -0
- package/plugins/agent-os-core/skills/plan-work/references/map.md +108 -0
- package/plugins/agent-os-core/skills/plan-work/references/spec-template.md +64 -0
- package/plugins/agent-os-core/skills/record-lesson/SKILL.md +47 -0
- package/plugins/agent-os-core/skills/scope-guard/SKILL.md +53 -0
- 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 +9 -4
- package/{skills → plugins/agent-os-dev/skills}/batch-work/references/manifest.md +8 -0
- package/{skills → plugins/agent-os-dev/skills}/check-work/SKILL.md +31 -14
- package/{skills/deliver-work/workflow.md → plugins/agent-os-dev/skills/deliver-work/SKILL.md} +85 -17
- package/plugins/agent-os-dev/skills/design-work/SKILL.md +145 -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 +10 -4
- package/plugins/agent-os-dev/skills/init-agent-os/SKILL.md +121 -0
- package/plugins/agent-os-dev/skills/init-agent-os/policy.md +88 -0
- package/plugins/agent-os-dev/skills/init-agent-os/references/guards.md +39 -0
- package/{skills → plugins/agent-os-dev/skills}/init-agent-os/references/repository-init.md +41 -9
- package/plugins/agent-os-dev/skills/init-agent-os/references/review-template.md +35 -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 +103 -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 +172 -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 +124 -0
- package/plugins/agent-os-dev/skills/shape-work/references/implementation-issues.md +143 -0
- package/{skills/chart-work → plugins/agent-os-dev/skills/shape-work}/references/prototypes.md +11 -13
- 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 +53 -20
- package/hooks/hooks.json +0 -17
- package/skills/chart-work/SKILL.md +0 -42
- package/skills/chart-work/references/elicitation.md +0 -25
- package/skills/chart-work/references/map.md +0 -84
- package/skills/deliver-work/SKILL.md +0 -12
- package/skills/diagnose-before-fix/SKILL.md +0 -24
- package/skills/explain-work/SKILL.md +0 -27
- package/skills/guide-me/SKILL.md +0 -36
- package/skills/init-agent-os/SKILL.md +0 -54
- package/skills/init-agent-os/scripts/policy-block.ps1 +0 -87
- package/skills/notice-lesson/SKILL.md +0 -20
- package/skills/quality-ratchet/SKILL.md +0 -72
- package/skills/record-lesson/SKILL.md +0 -31
- package/skills/scope-guard/SKILL.md +0 -32
- package/skills/shape-work/SKILL.md +0 -48
- package/skills/shape-work/references/implementation-issues.md +0 -69
- package/skills/shape-work/references/mockups.md +0 -23
- package/skills/simplifier/SKILL.md +0 -35
- package/skills/simplifier/agents/openai.yaml +0 -2
- package/skills/simplifier-audit/SKILL.md +0 -30
- package/skills/simplifier-review/SKILL.md +0 -40
- package/skills/understand-work/SKILL.md +0 -31
- 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/chart-work → plugins/agent-os-core/skills/explain-work}/agents/openai.yaml +0 -0
- /package/{skills/deliver-work → 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/dispatch-next → plugins/agent-os-core/skills/plan-work}/agents/openai.yaml +0 -0
- /package/{skills/explain-work → plugins/agent-os-dev/skills/batch-work}/agents/openai.yaml +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/guide-me → plugins/agent-os-dev/skills/deliver-work}/agents/openai.yaml +0 -0
- /package/{skills/init-agent-os → plugins/agent-os-dev/skills/design-work}/agents/openai.yaml +0 -0
- /package/{skills/list-skills → plugins/agent-os-dev/skills/dispatch-next}/agents/openai.yaml +0 -0
- /package/{skills/record-lesson → 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 → plugins/agent-os-dev/skills}/shape-work/agents/openai.yaml +0 -0
- /package/{skills/simplifier-audit → plugins/agent-os-dev/skills/simplify}/agents/openai.yaml +0 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Optional deterministic analyzers. Agent OS never installs them; when one is missing its evidence
|
|
2
|
+
// is reported as unavailable and the core Node evidence still stands.
|
|
3
|
+
|
|
4
|
+
import { spawnSync } from 'node:child_process'
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import os from 'node:os'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
|
|
9
|
+
const LIZARD_LAUNCHERS = [['lizard'], ['python3', '-m', 'lizard'], ['python', '-m', 'lizard']]
|
|
10
|
+
const BATCH_SIZE = 200
|
|
11
|
+
const TIMEOUT_MS = 120000
|
|
12
|
+
|
|
13
|
+
function run(argv, cwd, spawn) {
|
|
14
|
+
return spawn(argv[0], argv.slice(1), {
|
|
15
|
+
cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024
|
|
16
|
+
})
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// `python -m lizard` imports from its working directory first, so a lizard.py in the repository
|
|
20
|
+
// would run. Every lizard process therefore starts in an empty temporary directory and receives
|
|
21
|
+
// absolute file paths.
|
|
22
|
+
function inNeutralDirectory(callback) {
|
|
23
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-lizard-'))
|
|
24
|
+
try {
|
|
25
|
+
return callback(directory)
|
|
26
|
+
} finally {
|
|
27
|
+
fs.rmSync(directory, { recursive: true, force: true })
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function findLizard({ spawn = spawnSync } = {}) {
|
|
32
|
+
return inNeutralDirectory((directory) => {
|
|
33
|
+
for (const launcher of LIZARD_LAUNCHERS) {
|
|
34
|
+
try {
|
|
35
|
+
if (run([...launcher, '--version'], directory, spawn).status === 0) return launcher
|
|
36
|
+
} catch { /* try the next launcher */ }
|
|
37
|
+
}
|
|
38
|
+
return null
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function csvFields(line) {
|
|
43
|
+
const fields = []
|
|
44
|
+
let field = ''
|
|
45
|
+
let quoted = false
|
|
46
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
47
|
+
const char = line[index]
|
|
48
|
+
if (quoted) {
|
|
49
|
+
if (char === '"' && line[index + 1] === '"') { field += '"'; index += 1 }
|
|
50
|
+
else if (char === '"') quoted = false
|
|
51
|
+
else field += char
|
|
52
|
+
} else if (char === '"') quoted = true
|
|
53
|
+
else if (char === ',') { fields.push(field); field = '' }
|
|
54
|
+
else field += char
|
|
55
|
+
}
|
|
56
|
+
fields.push(field)
|
|
57
|
+
return fields
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// lizard --csv columns: NLOC, CCN, tokens, parameters, length, location, file, function,
|
|
61
|
+
// long name, start line, end line.
|
|
62
|
+
export function parseLizardCsv(text) {
|
|
63
|
+
return text.split(/\r?\n/).filter(Boolean).flatMap((line) => {
|
|
64
|
+
const fields = csvFields(line)
|
|
65
|
+
const ccn = Number(fields[1])
|
|
66
|
+
if (fields.length < 11 || !Number.isInteger(ccn)) return []
|
|
67
|
+
return [{
|
|
68
|
+
file: fields[6].replaceAll('\\', '/'),
|
|
69
|
+
function: fields[7],
|
|
70
|
+
line: Number(fields[9]),
|
|
71
|
+
ccn,
|
|
72
|
+
nloc: Number(fields[0])
|
|
73
|
+
}]
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Runs lizard on repository-relative files under cwd. Returns null when lizard is unavailable.
|
|
78
|
+
export function lizardFunctions(cwd, files, { launcher = findLizard(), spawn = spawnSync } = {}) {
|
|
79
|
+
if (!launcher) return null
|
|
80
|
+
const root = path.resolve(cwd)
|
|
81
|
+
const relative = (file) => path.isAbsolute(file) ? path.relative(root, file).replaceAll('\\', '/') : file
|
|
82
|
+
return inNeutralDirectory((directory) => {
|
|
83
|
+
const functions = []
|
|
84
|
+
for (let start = 0; start < files.length; start += BATCH_SIZE) {
|
|
85
|
+
const batch = files.slice(start, start + BATCH_SIZE).map((file) => path.join(root, file))
|
|
86
|
+
const result = run([...launcher, '--csv', ...batch], directory, spawn)
|
|
87
|
+
if (result.error || result.status !== 0) {
|
|
88
|
+
throw new Error(`lizard failed: ${result.error?.message || result.stderr?.trim() || `exit ${result.status}`}`)
|
|
89
|
+
}
|
|
90
|
+
functions.push(...parseLizardCsv(result.stdout).map((fn) => ({ ...fn, file: relative(fn.file) })))
|
|
91
|
+
}
|
|
92
|
+
return functions
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Same-named functions in one file are told apart by their order of appearance.
|
|
97
|
+
function keyed(functions) {
|
|
98
|
+
const seen = new Map()
|
|
99
|
+
return functions.map((fn) => {
|
|
100
|
+
const base = `${fn.file}\0${fn.function}`
|
|
101
|
+
const count = seen.get(base) || 0
|
|
102
|
+
seen.set(base, count + 1)
|
|
103
|
+
return { key: `${base}\0${count}`, fn }
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function complexityDelta(before, after, { limit = 20 } = {}) {
|
|
108
|
+
const previous = new Map(keyed(before).map(({ key, fn }) => [key, fn.ccn]))
|
|
109
|
+
const rows = keyed(after).map(({ key, fn }) => ({
|
|
110
|
+
path: fn.file,
|
|
111
|
+
function: fn.function,
|
|
112
|
+
line: fn.line,
|
|
113
|
+
before: previous.has(key) ? previous.get(key) : null,
|
|
114
|
+
after: fn.ccn
|
|
115
|
+
}))
|
|
116
|
+
const increased = rows.filter((row) => row.before !== null && row.after > row.before)
|
|
117
|
+
const added = rows.filter((row) => row.before === null)
|
|
118
|
+
const afterKeys = new Set(keyed(after).map(({ key }) => key))
|
|
119
|
+
const decreased = rows.filter((row) => row.before !== null && row.after < row.before).length +
|
|
120
|
+
[...previous.keys()].filter((key) => !afterKeys.has(key)).length
|
|
121
|
+
const functions = [...increased, ...added.filter((row) => row.after > 1)]
|
|
122
|
+
.sort((left, right) => right.after - left.after || (right.after - (right.before ?? 1)) - (left.after - (left.before ?? 1)))
|
|
123
|
+
return {
|
|
124
|
+
increased: increased.length,
|
|
125
|
+
added: added.length,
|
|
126
|
+
decreased,
|
|
127
|
+
maxAfter: rows.reduce((max, row) => Math.max(max, row.after), 0),
|
|
128
|
+
functions: functions.slice(0, limit),
|
|
129
|
+
omitted: Math.max(0, functions.length - limit)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function withTemporaryFiles(files, callback) {
|
|
134
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-analyzer-'))
|
|
135
|
+
try {
|
|
136
|
+
for (const [relativePath, content] of files) {
|
|
137
|
+
const target = path.join(root, ...relativePath.split('/'))
|
|
138
|
+
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
139
|
+
fs.writeFileSync(target, content)
|
|
140
|
+
}
|
|
141
|
+
return callback(root)
|
|
142
|
+
} finally {
|
|
143
|
+
fs.rmSync(root, { recursive: true, force: true })
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { execFileSync, spawnSync } from 'node:child_process'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import os from 'node:os'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import test from 'node:test'
|
|
7
|
+
import { complexityDelta, findLizard, lizardFunctions, parseLizardCsv } from './analyzers.mjs'
|
|
8
|
+
import { begin, check, hook } from './quality-delta.mjs'
|
|
9
|
+
|
|
10
|
+
const options = { detect: () => ({}) }
|
|
11
|
+
|
|
12
|
+
// Deterministic stand-in for lizard: one function per file, complexity 1 + number of `if`.
|
|
13
|
+
function fakeAnalyzer(cwd, files) {
|
|
14
|
+
return files.map((file) => ({
|
|
15
|
+
file,
|
|
16
|
+
function: 'main',
|
|
17
|
+
line: 1,
|
|
18
|
+
ccn: 1 + (fs.readFileSync(path.join(cwd, file), 'utf8').match(/\bif\b/g) || []).length,
|
|
19
|
+
nloc: 1
|
|
20
|
+
}))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function repository(t, policy) {
|
|
24
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-analyzers-'))
|
|
25
|
+
t.after(() => fs.rmSync(root, { recursive: true, force: true }))
|
|
26
|
+
const git = (...args) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' })
|
|
27
|
+
git('init', '-q')
|
|
28
|
+
git('config', 'user.email', 'analyzers@example.invalid')
|
|
29
|
+
git('config', 'user.name', 'Analyzer Test')
|
|
30
|
+
fs.mkdirSync(path.join(root, 'src'))
|
|
31
|
+
fs.writeFileSync(path.join(root, 'src', 'legacy.js'), 'export function main(a) {\n return a\n}\n')
|
|
32
|
+
if (policy) {
|
|
33
|
+
fs.mkdirSync(path.join(root, '.agent-os'))
|
|
34
|
+
fs.writeFileSync(path.join(root, '.agent-os', 'quality.json'), JSON.stringify({ schema: 1, checks: [], ...policy }))
|
|
35
|
+
}
|
|
36
|
+
git('add', '.')
|
|
37
|
+
git('commit', '-qm', 'fixture')
|
|
38
|
+
return root
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const ifs = (count) => `export function main(a) {\n${' if (a) a++\n'.repeat(count)} return a\n}\n`
|
|
42
|
+
|
|
43
|
+
test('parses lizard CSV including quoted long names with commas', () => {
|
|
44
|
+
const functions = parseLizardCsv([
|
|
45
|
+
'6,2,17,2,6,"one@1-6@src/e.js","src/e.js","one","one ( a , b )",1,6',
|
|
46
|
+
'9,6,36,2,9,"branchy@1-9@src\\d.py","src\\d.py","branchy","branchy( a , b )",1,9',
|
|
47
|
+
'not,a,row'
|
|
48
|
+
].join('\r\n'))
|
|
49
|
+
assert.deepEqual(functions, [
|
|
50
|
+
{ file: 'src/e.js', function: 'one', line: 1, ccn: 2, nloc: 6 },
|
|
51
|
+
{ file: 'src/d.py', function: 'branchy', line: 1, ccn: 6, nloc: 9 }
|
|
52
|
+
])
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('complexity delta ranks increased and new functions and counts reductions', () => {
|
|
56
|
+
const fn = (file, name, ccn) => ({ file, function: name, line: 1, ccn, nloc: 1 })
|
|
57
|
+
const delta = complexityDelta(
|
|
58
|
+
[fn('a.js', 'same', 3), fn('a.js', 'grew', 2), fn('a.js', 'shrank', 9), fn('a.js', 'gone', 4)],
|
|
59
|
+
[fn('a.js', 'same', 3), fn('a.js', 'grew', 7), fn('a.js', 'shrank', 5), fn('a.js', 'fresh', 12), fn('a.js', 'trivial', 1)]
|
|
60
|
+
)
|
|
61
|
+
assert.deepEqual(delta.functions.map((row) => [row.function, row.before, row.after]), [
|
|
62
|
+
['fresh', null, 12],
|
|
63
|
+
['grew', 2, 7]
|
|
64
|
+
])
|
|
65
|
+
assert.equal(delta.increased, 1)
|
|
66
|
+
assert.equal(delta.added, 2)
|
|
67
|
+
assert.equal(delta.decreased, 2)
|
|
68
|
+
assert.equal(delta.maxAfter, 12)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('check reports complexity deltas against clean entry content', (t) => {
|
|
72
|
+
const root = repository(t)
|
|
73
|
+
begin(root, options)
|
|
74
|
+
fs.writeFileSync(path.join(root, 'src', 'legacy.js'), ifs(3))
|
|
75
|
+
fs.writeFileSync(path.join(root, 'src', 'new.js'), ifs(5))
|
|
76
|
+
const evidence = check(root, { ...options, analyzeComplexity: fakeAnalyzer })
|
|
77
|
+
assert.equal(evidence.complexity.status, 'available')
|
|
78
|
+
assert.deepEqual(evidence.complexity.functions.map((row) => [row.path, row.before, row.after]), [
|
|
79
|
+
['src/new.js', null, 6],
|
|
80
|
+
['src/legacy.js', 1, 4]
|
|
81
|
+
])
|
|
82
|
+
assert.deepEqual(evidence.complexity.beforeUnavailable, [])
|
|
83
|
+
assert.equal(evidence.status, 'ok')
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
test('a file dirty at begin has no recoverable before state', (t) => {
|
|
87
|
+
const root = repository(t)
|
|
88
|
+
fs.writeFileSync(path.join(root, 'src', 'legacy.js'), ifs(1))
|
|
89
|
+
begin(root, options)
|
|
90
|
+
fs.writeFileSync(path.join(root, 'src', 'legacy.js'), ifs(4))
|
|
91
|
+
const evidence = check(root, { ...options, analyzeComplexity: fakeAnalyzer })
|
|
92
|
+
assert.deepEqual(evidence.complexity.beforeUnavailable, ['src/legacy.js'])
|
|
93
|
+
assert.deepEqual(evidence.complexity.functions, [])
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
test('missing lizard is reported as unavailable without blocking', (t) => {
|
|
97
|
+
const root = repository(t)
|
|
98
|
+
begin(root, options)
|
|
99
|
+
fs.writeFileSync(path.join(root, 'src', 'legacy.js'), ifs(2))
|
|
100
|
+
const evidence = check(root, { ...options, analyzeComplexity: () => null })
|
|
101
|
+
assert.equal(evidence.complexity.status, 'unavailable')
|
|
102
|
+
assert.equal(evidence.status, 'ok')
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
test('a project complexity threshold is advisory unless selected in blockSignals', (t) => {
|
|
106
|
+
const advisory = repository(t, { complexity: { threshold: 3 } })
|
|
107
|
+
begin(advisory, options)
|
|
108
|
+
fs.writeFileSync(path.join(advisory, 'src', 'legacy.js'), ifs(4))
|
|
109
|
+
const advised = check(advisory, { ...options, analyzeComplexity: fakeAnalyzer })
|
|
110
|
+
assert.equal(advised.status, 'ok')
|
|
111
|
+
assert.equal(advised.controls.signals[0].rule, 'complexity')
|
|
112
|
+
assert.equal(advised.controls.signals[0].required, false)
|
|
113
|
+
|
|
114
|
+
const blocking = repository(t, { complexity: { threshold: 3 }, blockSignals: ['complexity'] })
|
|
115
|
+
begin(blocking, options)
|
|
116
|
+
fs.writeFileSync(path.join(blocking, 'src', 'legacy.js'), ifs(4))
|
|
117
|
+
assert.equal(check(blocking, { ...options, analyzeComplexity: fakeAnalyzer }).status, 'blocked')
|
|
118
|
+
assert.match(hook(blocking).reason, /src\/legacy.js:1 complexity/)
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
test('the complexity block rule requires a threshold', (t) => {
|
|
122
|
+
const root = repository(t, { blockSignals: ['complexity'] })
|
|
123
|
+
assert.throws(() => begin(root, options), /requires complexity.threshold/)
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
test('real lizard output feeds the same delta', { skip: !findLizard() && 'lizard is not installed' }, (t) => {
|
|
127
|
+
const root = repository(t)
|
|
128
|
+
fs.writeFileSync(path.join(root, 'src', 'two.js'), 'function two(a) {\n if (a > 1) {\n return 1\n }\n return 0\n}\n')
|
|
129
|
+
const functions = lizardFunctions(root, ['src/two.js'])
|
|
130
|
+
assert.deepEqual(functions.map((fn) => [fn.file, fn.function, fn.ccn]), [['src/two.js', 'two', 2]])
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
const python = ['python3', 'python'].find((name) => {
|
|
134
|
+
try {
|
|
135
|
+
return spawnSync(name, ['--version'], { encoding: 'utf8' }).status === 0
|
|
136
|
+
} catch {
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
test('a lizard.py in the repository never runs through python -m lizard', { skip: !python && 'python is not installed' }, (t) => {
|
|
142
|
+
const root = repository(t)
|
|
143
|
+
const marker = path.join(root, 'lizard-ran')
|
|
144
|
+
fs.writeFileSync(path.join(root, 'lizard.py'), `open(${JSON.stringify(marker)}, 'w').write('ran')\nprint('lizard 0.0.0')\n`)
|
|
145
|
+
const previous = process.cwd()
|
|
146
|
+
process.chdir(root)
|
|
147
|
+
try {
|
|
148
|
+
findLizard()
|
|
149
|
+
try {
|
|
150
|
+
lizardFunctions(root, ['src/legacy.js'], { launcher: [python, '-m', 'lizard'] })
|
|
151
|
+
} catch {
|
|
152
|
+
// Without a real lizard module the run fails; it must not import the repository's file.
|
|
153
|
+
}
|
|
154
|
+
} finally {
|
|
155
|
+
process.chdir(previous)
|
|
156
|
+
}
|
|
157
|
+
assert.equal(fs.existsSync(marker), false)
|
|
158
|
+
})
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Agent OS guard hooks. Reads .agent-os/guards.json, Git, and intent files; never runs a command the
|
|
3
|
+
// repository declares. Without guards.json every hook is a no-op.
|
|
4
|
+
//
|
|
5
|
+
// node guards.mjs hook --agent-os-hook=guards SessionStart context or PreToolUse blocks (stdin payload)
|
|
6
|
+
// node guards.mjs lock-test <path> [--root <dir>]
|
|
7
|
+
// node guards.mjs unlock-test <path> [--root <dir>]
|
|
8
|
+
// node guards.mjs status [--root <dir>]
|
|
9
|
+
|
|
10
|
+
import { spawnSync } from 'node:child_process'
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import { pathToFileURL } from 'node:url'
|
|
14
|
+
import { listIntents, parseFrontmatter, parseUnits, staleness } from './intent-files.mjs'
|
|
15
|
+
import { deliveryBaselineActive } from './quality-delta.mjs'
|
|
16
|
+
|
|
17
|
+
export const GUARDS_HOOK_MARKER = '--agent-os-hook=guards'
|
|
18
|
+
export const GUARDS_PATH = '.agent-os/guards.json'
|
|
19
|
+
export const LOCKS_FILE = 'agent-os-test-locks.json'
|
|
20
|
+
export const GUARDS_TIMEOUT_SECONDS = 10
|
|
21
|
+
|
|
22
|
+
const SECRET_PATTERNS = [
|
|
23
|
+
['private key', /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/],
|
|
24
|
+
['AWS access key', /\bAKIA[0-9A-Z]{16}\b/],
|
|
25
|
+
['GitHub token', /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})\b/],
|
|
26
|
+
['Slack token', /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/],
|
|
27
|
+
['Anthropic key', /\bsk-ant-[A-Za-z0-9_-]{20,}/],
|
|
28
|
+
['OpenAI key', /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}/],
|
|
29
|
+
['Stripe live key', /\b[rs]k_live_[A-Za-z0-9]{20,}\b/],
|
|
30
|
+
['Google API key', /\bAIza[0-9A-Za-z_-]{35}\b/],
|
|
31
|
+
['hard-coded credential', /\b(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret)\b["']?\s*[:=]\s*["'][^"'\s]{12,}["']/i]
|
|
32
|
+
]
|
|
33
|
+
const PLACEHOLDER = /(?:example|changeme|placeholder|dummy|sample|xxxx|<[^>]*>|\$\{|process\.env|os\.environ|getenv)/i
|
|
34
|
+
|
|
35
|
+
export class GuardsError extends Error {}
|
|
36
|
+
|
|
37
|
+
function git(root, args) {
|
|
38
|
+
const result = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
|
39
|
+
return result.status === 0 ? result.stdout : null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function repositoryRoot(cwd) {
|
|
43
|
+
const top = git(path.resolve(cwd), ['rev-parse', '--show-toplevel'])
|
|
44
|
+
return top ? path.resolve(top.trim()) : null
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function gitDir(root) {
|
|
48
|
+
const value = git(root, ['rev-parse', '--git-dir'])?.trim()
|
|
49
|
+
if (!value) return null
|
|
50
|
+
return path.isAbsolute(value) ? path.normalize(value) : path.resolve(root, value)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function readGuards(root) {
|
|
54
|
+
const file = path.join(root, GUARDS_PATH)
|
|
55
|
+
if (!fs.existsSync(file)) return null
|
|
56
|
+
let value
|
|
57
|
+
try {
|
|
58
|
+
value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
59
|
+
} catch (cause) {
|
|
60
|
+
throw new GuardsError(`${GUARDS_PATH} is not valid JSON: ${cause.message}`)
|
|
61
|
+
}
|
|
62
|
+
const list = (key) => (Array.isArray(value?.[key]) ? value[key].filter((item) => typeof item === 'string') : [])
|
|
63
|
+
return {
|
|
64
|
+
protectedPaths: list('protectedPaths'),
|
|
65
|
+
frozen: Array.isArray(value?.frozen) ? list('frozen') : ['intents/*/intent.md', 'intents/*/spec.md', 'intents/*/plan.md'],
|
|
66
|
+
secretScan: value?.secretScan === true
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function globToRegExp(glob) {
|
|
71
|
+
let pattern = ''
|
|
72
|
+
const text = glob.replaceAll('\\', '/').replace(/^\.\//, '')
|
|
73
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
74
|
+
const char = text[index]
|
|
75
|
+
if (char === '*' && text[index + 1] === '*') {
|
|
76
|
+
if (text[index + 2] === '/') {
|
|
77
|
+
pattern += '(?:.*/)?'
|
|
78
|
+
index += 2
|
|
79
|
+
} else {
|
|
80
|
+
pattern += '.*'
|
|
81
|
+
index += 1
|
|
82
|
+
}
|
|
83
|
+
} else if (char === '*') pattern += '[^/]*'
|
|
84
|
+
else if (char === '?') pattern += '[^/]'
|
|
85
|
+
else pattern += char.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
86
|
+
}
|
|
87
|
+
return new RegExp(`^${pattern}$`)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Windows and macOS file systems ignore case by default, so `Migrations/1.sql` is the same file.
|
|
91
|
+
const caseInsensitive = ['win32', 'darwin'].includes(process.platform)
|
|
92
|
+
const comparable = (value) => (caseInsensitive ? value.toLowerCase() : value)
|
|
93
|
+
|
|
94
|
+
export function matchesAny(relative, globs) {
|
|
95
|
+
return globs.find((glob) => globToRegExp(comparable(glob)).test(comparable(relative))) ?? null
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function relativeTo(root, cwd, file) {
|
|
99
|
+
const absolute = path.resolve(cwd, file)
|
|
100
|
+
const relative = path.relative(root, absolute)
|
|
101
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null
|
|
102
|
+
return relative.split(path.sep).join('/')
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function commandText(input) {
|
|
106
|
+
const command = input?.command ?? input?.cmd
|
|
107
|
+
if (Array.isArray(command)) return command.join(' ')
|
|
108
|
+
return typeof command === 'string' ? command : ''
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// File targets of an edit: Claude tool inputs carry a path; Codex apply_patch carries patch headers.
|
|
112
|
+
export function editedPaths(payload) {
|
|
113
|
+
const input = payload?.tool_input ?? {}
|
|
114
|
+
const paths = []
|
|
115
|
+
for (const key of ['file_path', 'path', 'notebook_path']) {
|
|
116
|
+
if (typeof input[key] === 'string' && input[key]) paths.push(input[key])
|
|
117
|
+
}
|
|
118
|
+
const texts = [input.patch, input.input, commandText(input)].filter((value) => typeof value === 'string')
|
|
119
|
+
for (const text of texts) {
|
|
120
|
+
if (!text.includes('*** Begin Patch')) continue
|
|
121
|
+
for (const match of text.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$|^\*\*\* Move to: (.+)$/gm)) {
|
|
122
|
+
paths.push((match[1] ?? match[2]).trim())
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return [...new Set(paths)]
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function isGitCommit(payload) {
|
|
129
|
+
return /(?:^|[;&|(]\s*|\s)git(?:\s+-C\s+\S+)?\s+commit\b/.test(commandText(payload?.tool_input))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// The hook runs before the command, so a `git add` in the same command has not staged anything yet.
|
|
133
|
+
function stagesInCommand(payload) {
|
|
134
|
+
return /(?:^|[;&|(]\s*|\s)git(?:\s+-C\s+\S+)?\s+(?:add|stage)\b/.test(commandText(payload?.tool_input))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Untracked files read as additions so a secret in a file the same command stages is still found.
|
|
138
|
+
function untrackedAsDiff(root) {
|
|
139
|
+
const listed = git(root, ['ls-files', '--others', '--exclude-standard', '-z']) ?? ''
|
|
140
|
+
const parts = []
|
|
141
|
+
for (const relative of listed.split('\0').filter(Boolean).slice(0, 500)) {
|
|
142
|
+
let content
|
|
143
|
+
try {
|
|
144
|
+
const file = path.join(root, relative)
|
|
145
|
+
if (fs.statSync(file).size > 1024 * 1024) continue
|
|
146
|
+
content = fs.readFileSync(file)
|
|
147
|
+
} catch {
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
if (content.includes(0)) continue
|
|
151
|
+
const lines = content.toString('utf8').replace(/\r\n/g, '\n').split('\n')
|
|
152
|
+
parts.push(`+++ b/${relative}`, `@@ -0,0 +1,${lines.length} @@`, ...lines.map((line) => `+${line}`))
|
|
153
|
+
}
|
|
154
|
+
return parts.join('\n')
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function readLocks(root) {
|
|
158
|
+
const dir = gitDir(root)
|
|
159
|
+
if (!dir) return { file: null, locks: [] }
|
|
160
|
+
const file = path.join(dir, LOCKS_FILE)
|
|
161
|
+
try {
|
|
162
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
163
|
+
return { file, locks: Array.isArray(value?.locks) ? value.locks.filter((item) => typeof item === 'string') : [] }
|
|
164
|
+
} catch {
|
|
165
|
+
return { file, locks: [] }
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function writeLocks(file, locks) {
|
|
170
|
+
fs.writeFileSync(file, JSON.stringify({ schema: 1, locks: [...new Set(locks)].sort() }, null, 2) + '\n')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function lockTest(root, file, { lock = true, cwd = process.cwd() } = {}) {
|
|
174
|
+
const relative = relativeTo(root, cwd, file)
|
|
175
|
+
if (!relative) throw new GuardsError(`${file} is not inside ${root}`)
|
|
176
|
+
if (lock && !fs.existsSync(path.join(root, relative))) throw new GuardsError(`${relative} does not exist`)
|
|
177
|
+
const { file: store, locks } = readLocks(root)
|
|
178
|
+
if (!store) throw new GuardsError(`${root} is not a Git worktree`)
|
|
179
|
+
const next = lock ? [...locks, relative] : locks.filter((item) => item !== relative)
|
|
180
|
+
writeLocks(store, next)
|
|
181
|
+
return { relative, locks: [...new Set(next)].sort() }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function fileStatus(root, relative) {
|
|
185
|
+
try {
|
|
186
|
+
return parseFrontmatter(fs.readFileSync(path.join(root, relative), 'utf8'))?.data?.status ?? null
|
|
187
|
+
} catch {
|
|
188
|
+
return null
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function scanSecrets(diff) {
|
|
193
|
+
const findings = []
|
|
194
|
+
let file = null
|
|
195
|
+
let line = 0
|
|
196
|
+
for (const text of String(diff).split('\n')) {
|
|
197
|
+
if (text.startsWith('+++ ')) {
|
|
198
|
+
file = text.slice(4).replace(/^b\//, '')
|
|
199
|
+
continue
|
|
200
|
+
}
|
|
201
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(text)
|
|
202
|
+
if (hunk) {
|
|
203
|
+
line = Number(hunk[1])
|
|
204
|
+
continue
|
|
205
|
+
}
|
|
206
|
+
if (text.startsWith('+') && !text.startsWith('+++')) {
|
|
207
|
+
const added = text.slice(1)
|
|
208
|
+
for (const [label, pattern] of SECRET_PATTERNS) {
|
|
209
|
+
const match = pattern.exec(added)
|
|
210
|
+
if (match && !PLACEHOLDER.test(match[0])) {
|
|
211
|
+
findings.push({ file, line, label })
|
|
212
|
+
break
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
line += 1
|
|
216
|
+
} else if (!text.startsWith('-')) {
|
|
217
|
+
line += 1
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return findings
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const allow = () => ({ exitCode: 0, stdout: '', stderr: '' })
|
|
224
|
+
const block = (message) => ({ exitCode: 2, stdout: '', stderr: `Agent OS guard: ${message}\n` })
|
|
225
|
+
|
|
226
|
+
// Claude asks the developer; Codex has no ask decision, so it blocks with the same instruction.
|
|
227
|
+
function ask(payload, message) {
|
|
228
|
+
const codex = typeof payload?.turn_id === 'string' && payload.turn_id.trim()
|
|
229
|
+
if (codex) return block(`${message} Ask the developer; they can make this edit themselves or remove the path from ${GUARDS_PATH}.`)
|
|
230
|
+
return {
|
|
231
|
+
exitCode: 0,
|
|
232
|
+
stdout: JSON.stringify({
|
|
233
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: `Agent OS guard: ${message}` }
|
|
234
|
+
}) + '\n',
|
|
235
|
+
stderr: ''
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function preToolUse(root, guards, payload, { env = process.env, cwd = root } = {}) {
|
|
240
|
+
const paths = editedPaths(payload).map((file) => relativeTo(root, cwd, file)).filter(Boolean)
|
|
241
|
+
const { locks } = readLocks(root)
|
|
242
|
+
const delivering = paths.length > 0 && deliveryBaselineActive(cwd, payload, { env })
|
|
243
|
+
for (const relative of paths) {
|
|
244
|
+
if (locks.some((lock) => comparable(lock) === comparable(relative))) {
|
|
245
|
+
return block(`${relative} is a locked failing test. Fix the code until it passes; changing the test needs the developer's explicit agreement and \`guards.mjs unlock-test ${relative}\`.`)
|
|
246
|
+
}
|
|
247
|
+
if (delivering && matchesAny(relative, guards.frozen) && fileStatus(root, relative) === 'accepted') {
|
|
248
|
+
return block(`${relative} is accepted and delivery never edits it. A needed change goes back through plan-work or shape-work in its own review.`)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
for (const relative of paths) {
|
|
252
|
+
const glob = matchesAny(relative, guards.protectedPaths)
|
|
253
|
+
if (glob) return ask(payload, `${relative} is protected by "${glob}" in ${GUARDS_PATH}.`)
|
|
254
|
+
}
|
|
255
|
+
if (guards.secretScan && isGitCommit(payload)) {
|
|
256
|
+
const all = /\scommit\b[^;&|]*\s(?:-a|--all|-[A-Za-z]*a[A-Za-z]*)\b/.test(commandText(payload.tool_input))
|
|
257
|
+
const staging = stagesInCommand(payload)
|
|
258
|
+
// With HEAD missing in a new repository, the index diff is still the best available view.
|
|
259
|
+
const tracked = git(root, all || staging ? ['diff', 'HEAD', '-U0', '--no-color'] : ['diff', '--cached', '-U0', '--no-color']) ??
|
|
260
|
+
git(root, ['diff', '--cached', '-U0', '--no-color'])
|
|
261
|
+
const diff = [tracked ?? '', staging ? untrackedAsDiff(root) : ''].join('\n')
|
|
262
|
+
const findings = scanSecrets(diff)
|
|
263
|
+
if (findings.length) {
|
|
264
|
+
const list = findings.slice(0, 5).map((item) => `${item.file}:${item.line} (${item.label})`).join(', ')
|
|
265
|
+
return block(`the commit adds what looks like a secret: ${list}. Remove it and load it from the environment instead; a false positive is the developer's call.`)
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return allow()
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function currentBranch(root) {
|
|
272
|
+
return git(root, ['rev-parse', '--abbrev-ref', 'HEAD'])?.trim() ?? ''
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function sessionContext(root) {
|
|
276
|
+
const folders = listIntents(root)
|
|
277
|
+
if (!folders.length) return ''
|
|
278
|
+
const branch = currentBranch(root)
|
|
279
|
+
const lines = []
|
|
280
|
+
for (const folder of folders) {
|
|
281
|
+
const units = parseUnits(folder.files['plan.md']?.body ?? '') ?? []
|
|
282
|
+
const unit = units.find((item) => branch.includes(item.key) && (branch.includes(folder.id) || !/^U\d+$/.test(item.key)))
|
|
283
|
+
if (!unit && !branch.includes(folder.id)) continue
|
|
284
|
+
const spec = folder.files['spec.md']?.data
|
|
285
|
+
lines.push(`Branch ${branch} belongs to intent ${folder.id}` +
|
|
286
|
+
(unit ? `, unit ${unit.key} "${unit.title}"` : '') +
|
|
287
|
+
(spec ? ` (spec rev ${spec.rev ?? '?'})` : ' (no spec yet)') + '.')
|
|
288
|
+
}
|
|
289
|
+
const stale = folders.flatMap((folder) => staleness(folder))
|
|
290
|
+
for (const item of stale.slice(0, 5)) {
|
|
291
|
+
lines.push(`Stale: ${item.file} is built on ${item.kind}@${item.builtOn}, but ${item.kind}.md is at rev ${item.current}; reconsider it before delivering from it.`)
|
|
292
|
+
}
|
|
293
|
+
const { locks } = readLocks(root)
|
|
294
|
+
if (locks.length) lines.push(`Locked failing tests: ${locks.join(', ')}.`)
|
|
295
|
+
return lines.length ? `Agent OS context:\n- ${lines.join('\n- ')}\n` : ''
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export function hook(cwd, payload = {}, { env = process.env } = {}) {
|
|
299
|
+
const event = payload?.hook_event_name
|
|
300
|
+
// Most tool calls are neither edits nor commits; answer them before touching Git.
|
|
301
|
+
if (event === 'PreToolUse' && editedPaths(payload).length === 0 && !isGitCommit(payload)) return allow()
|
|
302
|
+
const root = repositoryRoot(payload?.cwd || cwd)
|
|
303
|
+
if (!root) return allow()
|
|
304
|
+
let guards
|
|
305
|
+
try {
|
|
306
|
+
guards = readGuards(root)
|
|
307
|
+
} catch (cause) {
|
|
308
|
+
if (event !== 'PreToolUse') return allow()
|
|
309
|
+
// Never block the one edit that repairs the configuration.
|
|
310
|
+
const targets = editedPaths(payload).map((file) => relativeTo(root, payload?.cwd || cwd, file))
|
|
311
|
+
if (targets.length && targets.every((target) => target === GUARDS_PATH)) return allow()
|
|
312
|
+
return block(`${cause.message}. Fix ${GUARDS_PATH} first; edits to it are allowed.`)
|
|
313
|
+
}
|
|
314
|
+
if (!guards) return allow()
|
|
315
|
+
if (event === 'SessionStart') {
|
|
316
|
+
return { exitCode: 0, stdout: sessionContext(root), stderr: '' }
|
|
317
|
+
}
|
|
318
|
+
if (event === 'PreToolUse') return preToolUse(root, guards, payload, { env, cwd: payload?.cwd || cwd })
|
|
319
|
+
return allow()
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function readStdin() {
|
|
323
|
+
try {
|
|
324
|
+
return fs.readFileSync(0, 'utf8')
|
|
325
|
+
} catch {
|
|
326
|
+
return ''
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function option(args, name) {
|
|
331
|
+
const index = args.indexOf(name)
|
|
332
|
+
return index >= 0 ? args[index + 1] : null
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function main(argv = process.argv.slice(2)) {
|
|
336
|
+
const [command, target] = argv
|
|
337
|
+
try {
|
|
338
|
+
if (command === 'hook') {
|
|
339
|
+
let payload = {}
|
|
340
|
+
try {
|
|
341
|
+
payload = JSON.parse(readStdin() || '{}')
|
|
342
|
+
} catch {
|
|
343
|
+
payload = {}
|
|
344
|
+
}
|
|
345
|
+
const result = hook(process.cwd(), payload)
|
|
346
|
+
if (result.stdout) process.stdout.write(result.stdout)
|
|
347
|
+
if (result.stderr) process.stderr.write(result.stderr)
|
|
348
|
+
process.exitCode = result.exitCode
|
|
349
|
+
return
|
|
350
|
+
}
|
|
351
|
+
const root = repositoryRoot(option(argv, '--root') || process.cwd())
|
|
352
|
+
if (!root) throw new GuardsError('not inside a Git worktree')
|
|
353
|
+
if (command === 'lock-test' || command === 'unlock-test') {
|
|
354
|
+
if (!target || target.startsWith('--')) throw new GuardsError(`${command} needs a test path`)
|
|
355
|
+
const result = lockTest(root, target, { lock: command === 'lock-test' })
|
|
356
|
+
console.log(`${command === 'lock-test' ? 'Locked' : 'Unlocked'} ${result.relative}. Locked tests: ${result.locks.join(', ') || 'none'}.`)
|
|
357
|
+
return
|
|
358
|
+
}
|
|
359
|
+
if (command === 'status') {
|
|
360
|
+
const guards = readGuards(root)
|
|
361
|
+
console.log(guards ? `Guards active from ${GUARDS_PATH}.` : `No ${GUARDS_PATH}; guard hooks do nothing here.`)
|
|
362
|
+
process.stdout.write(sessionContext(root))
|
|
363
|
+
return
|
|
364
|
+
}
|
|
365
|
+
throw new GuardsError('Use hook, lock-test <path>, unlock-test <path>, or status.')
|
|
366
|
+
} catch (cause) {
|
|
367
|
+
console.error(`guards: ${cause.message}`)
|
|
368
|
+
process.exitCode = 1
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main()
|