@sockulags/agent-os 0.15.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 -48
- 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/{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 +64 -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 +5 -2
- 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} +77 -42
- 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 +6 -1
- 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 -10
- 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/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 +48 -24
- 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/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
|
@@ -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()
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { 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 { editedPaths, globToRegExp, hook, isGitCommit, lockTest, scanSecrets, sessionContext } from './guards.mjs'
|
|
8
|
+
import { begin, clear } from './quality-delta.mjs'
|
|
9
|
+
|
|
10
|
+
function git(root, ...args) {
|
|
11
|
+
const result = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' })
|
|
12
|
+
assert.equal(result.status, 0, result.stderr)
|
|
13
|
+
return result.stdout
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function repository(guards = { schema: 1, protectedPaths: ['migrations/**'], secretScan: true }) {
|
|
17
|
+
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-guards-')))
|
|
18
|
+
git(root, 'init', '-q', '-b', '2026-11-csv-export-U1')
|
|
19
|
+
git(root, 'config', 'user.email', 'test@example.invalid')
|
|
20
|
+
git(root, 'config', 'user.name', 'Test')
|
|
21
|
+
const write = (relative, content) => {
|
|
22
|
+
fs.mkdirSync(path.dirname(path.join(root, relative)), { recursive: true })
|
|
23
|
+
fs.writeFileSync(path.join(root, relative), content)
|
|
24
|
+
}
|
|
25
|
+
if (guards) write('.agent-os/guards.json', JSON.stringify(guards))
|
|
26
|
+
write('intents/2026-11-csv-export/intent.md', '---\nid: 2026-11-csv-export\nstatus: accepted\nrev: 2\nsupersedes: null\n---\n# Export\n')
|
|
27
|
+
write('intents/2026-11-csv-export/spec.md', '---\nintent: 2026-11-csv-export\nrev: 1\nbuilt_on: intent@1\nstatus: accepted\n---\n# Export\n')
|
|
28
|
+
write('intents/2026-11-csv-export/plan.md', '---\nintent: 2026-11-csv-export\nrev: 1\nbuilt_on: spec@1\nstatus: accepted\nsource: files\n---\n## Units\n\n- [U1] Export endpoint\n\n### U1 Export endpoint\n')
|
|
29
|
+
write('tests/export.test.js', 'test("x", () => {})\n')
|
|
30
|
+
write('src/app.js', 'export const x = 1\n')
|
|
31
|
+
git(root, 'add', '-A')
|
|
32
|
+
git(root, 'commit', '-qm', 'init')
|
|
33
|
+
return { root, write }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const edit = (root, file, extra = {}) => ({
|
|
37
|
+
hook_event_name: 'PreToolUse', cwd: root, session_id: 'guards-test', tool_name: 'Edit', tool_input: { file_path: path.join(root, file) }, ...extra
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
test('glob matching follows segments', () => {
|
|
41
|
+
assert.ok(globToRegExp('migrations/**').test('migrations/2026/001.sql'))
|
|
42
|
+
assert.ok(globToRegExp('intents/*/spec.md').test('intents/2026-11-a/spec.md'))
|
|
43
|
+
assert.ok(!globToRegExp('intents/*/spec.md').test('intents/a/b/spec.md'))
|
|
44
|
+
assert.ok(globToRegExp('**/*.lock').test('a/b/c.lock'))
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test('edited paths come from Claude tool input and Codex patches', () => {
|
|
48
|
+
assert.deepEqual(editedPaths({ tool_input: { file_path: 'a.js' } }), ['a.js'])
|
|
49
|
+
const patch = '*** Begin Patch\n*** Update File: src/a.js\n@@\n*** Add File: src/b.js\n*** End Patch'
|
|
50
|
+
assert.deepEqual(editedPaths({ tool_input: { command: ['apply_patch', patch] } }), ['src/a.js', 'src/b.js'])
|
|
51
|
+
assert.ok(isGitCommit({ tool_input: { command: 'git add -A && git commit -m "x"' } }))
|
|
52
|
+
assert.ok(isGitCommit({ tool_input: { command: 'git -C repo commit -m x' } }))
|
|
53
|
+
assert.ok(!isGitCommit({ tool_input: { command: 'git log --grep commit' } }))
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
test('secret scan reports added secrets with location and skips placeholders', () => {
|
|
57
|
+
const diff = [
|
|
58
|
+
'+++ b/src/config.js',
|
|
59
|
+
'@@ -0,0 +1,3 @@',
|
|
60
|
+
'+const ok = 1',
|
|
61
|
+
"+const apiKey = 'AKIAABCDEFGHIJKLMNOP'",
|
|
62
|
+
"+const password = '<your-password-here>'"
|
|
63
|
+
].join('\n')
|
|
64
|
+
assert.deepEqual(scanSecrets(diff), [{ file: 'src/config.js', line: 2, label: 'AWS access key' }])
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test('hooks do nothing without guards.json', () => {
|
|
68
|
+
const { root } = repository(null)
|
|
69
|
+
assert.equal(hook(root, edit(root, 'migrations/001.sql')).exitCode, 0)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
test('protected paths ask on Claude and block on Codex', () => {
|
|
73
|
+
const { root } = repository()
|
|
74
|
+
const claude = hook(root, edit(root, 'migrations/001.sql'))
|
|
75
|
+
assert.equal(claude.exitCode, 0)
|
|
76
|
+
assert.equal(JSON.parse(claude.stdout).hookSpecificOutput.permissionDecision, 'ask')
|
|
77
|
+
const codex = hook(root, edit(root, 'migrations/001.sql', { turn_id: 't1' }))
|
|
78
|
+
assert.equal(codex.exitCode, 2)
|
|
79
|
+
assert.equal(hook(root, edit(root, 'src/app.js')).exitCode, 0)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
test('accepted intents and specs are frozen only during delivery', () => {
|
|
83
|
+
const { root } = repository()
|
|
84
|
+
const payload = edit(root, 'intents/2026-11-csv-export/spec.md')
|
|
85
|
+
assert.equal(hook(root, payload).exitCode, 0)
|
|
86
|
+
const env = { ...process.env, CODEX_THREAD_ID: '', CLAUDE_CODE_SESSION_ID: 'guards-test' }
|
|
87
|
+
begin(root, { env, detect: () => ({}) })
|
|
88
|
+
try {
|
|
89
|
+
const result = hook(root, payload, { env })
|
|
90
|
+
assert.equal(result.exitCode, 2)
|
|
91
|
+
assert.match(result.stderr, /delivery never edits it/)
|
|
92
|
+
} finally {
|
|
93
|
+
clear(root, { env })
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
test('a locked test blocks edits until unlocked', () => {
|
|
98
|
+
const { root } = repository()
|
|
99
|
+
lockTest(root, 'tests/export.test.js', { cwd: root })
|
|
100
|
+
const result = hook(root, edit(root, 'tests/export.test.js'))
|
|
101
|
+
assert.equal(result.exitCode, 2)
|
|
102
|
+
assert.match(result.stderr, /locked failing test/)
|
|
103
|
+
lockTest(root, 'tests/export.test.js', { lock: false, cwd: root })
|
|
104
|
+
assert.equal(hook(root, edit(root, 'tests/export.test.js')).exitCode, 0)
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
test('a commit that stages a secret is blocked', () => {
|
|
108
|
+
const { root, write } = repository()
|
|
109
|
+
write('src/config.js', "export const token = 'ghp_" + 'a'.repeat(36) + "'\n")
|
|
110
|
+
git(root, 'add', 'src/config.js')
|
|
111
|
+
const result = hook(root, { hook_event_name: 'PreToolUse', cwd: root, tool_name: 'Bash', tool_input: { command: 'git commit -m "add config"' } })
|
|
112
|
+
assert.equal(result.exitCode, 2)
|
|
113
|
+
assert.match(result.stderr, /src\/config\.js:1 \(GitHub token\)/)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('session context names the branch intent, stale files, and locks', () => {
|
|
117
|
+
const { root } = repository()
|
|
118
|
+
const context = sessionContext(root)
|
|
119
|
+
assert.match(context, /intent 2026-11-csv-export, unit U1 "Export endpoint" \(spec rev 1\)/)
|
|
120
|
+
assert.match(context, /Stale: intents\/2026-11-csv-export\/spec\.md is built on intent@1, but intent\.md is at rev 2/)
|
|
121
|
+
const result = hook(root, { hook_event_name: 'SessionStart', cwd: root })
|
|
122
|
+
assert.equal(result.stdout, context)
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
test('a command that stages and commits in one go is scanned before git add runs', () => {
|
|
126
|
+
const { root, write } = repository()
|
|
127
|
+
write('src/keys.js', "export const key = 'AKIAABCDEFGHIJKLMNOP'\n")
|
|
128
|
+
const result = hook(root, { hook_event_name: 'PreToolUse', cwd: root, tool_name: 'Bash', tool_input: { command: 'git add src/keys.js && git commit -m "keys"' } })
|
|
129
|
+
assert.equal(result.exitCode, 2)
|
|
130
|
+
assert.match(result.stderr, /src\/keys\.js:1 \(AWS access key\)/)
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
test('a malformed guards.json blocks edits except the one that repairs it', () => {
|
|
134
|
+
const { root, write } = repository()
|
|
135
|
+
write('.agent-os/guards.json', '{ broken')
|
|
136
|
+
assert.equal(hook(root, edit(root, 'src/app.js')).exitCode, 2)
|
|
137
|
+
assert.equal(hook(root, edit(root, '.agent-os/guards.json')).exitCode, 0)
|
|
138
|
+
})
|