@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.
Files changed (99) hide show
  1. package/README.md +105 -59
  2. package/cli/doctor.mjs +351 -0
  3. package/cli/index.mjs +328 -151
  4. package/cli/index.test.mjs +436 -9
  5. package/package.json +5 -6
  6. package/plugins/agent-os-core/.claude-plugin/plugin.json +18 -0
  7. package/plugins/agent-os-core/.codex-plugin/plugin.json +24 -0
  8. package/plugins/agent-os-core/skills/capture-intent/SKILL.md +68 -0
  9. package/plugins/agent-os-core/skills/capture-intent/references/intent-template.md +47 -0
  10. package/plugins/agent-os-core/skills/explain-work/SKILL.md +42 -0
  11. package/{skills → plugins/agent-os-core/skills}/list-skills/SKILL.md +16 -7
  12. package/{skills → plugins/agent-os-core/skills}/plain-voice/SKILL.md +7 -4
  13. package/plugins/agent-os-core/skills/plan-work/SKILL.md +151 -0
  14. package/{skills → plugins/agent-os-core/skills}/plan-work/references/elicitation.md +7 -3
  15. package/plugins/agent-os-core/skills/plan-work/references/spec-template.md +65 -0
  16. package/plugins/agent-os-core/skills/record-lesson/SKILL.md +47 -0
  17. package/{skills → plugins/agent-os-core/skills}/scope-guard/SKILL.md +11 -6
  18. package/{skills → plugins/agent-os-core/skills}/verify-before-done/SKILL.md +6 -2
  19. package/plugins/agent-os-dev/.claude-plugin/plugin.json +18 -0
  20. package/plugins/agent-os-dev/.codex-plugin/plugin.json +24 -0
  21. package/plugins/agent-os-dev/hooks/hooks.json +42 -0
  22. package/{skills → plugins/agent-os-dev/skills}/batch-work/SKILL.md +6 -2
  23. package/{skills → plugins/agent-os-dev/skills}/check-work/SKILL.md +33 -14
  24. package/{skills/deliver-work/workflow.md → plugins/agent-os-dev/skills/deliver-work/SKILL.md} +126 -57
  25. package/plugins/agent-os-dev/skills/deliver-work/references/work-records.md +20 -0
  26. package/plugins/agent-os-dev/skills/design-work/SKILL.md +160 -0
  27. package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.mjs +233 -0
  28. package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.test.mjs +73 -0
  29. package/plugins/agent-os-dev/skills/diagnose-before-fix/SKILL.md +29 -0
  30. package/{skills → plugins/agent-os-dev/skills}/dispatch-next/SKILL.md +11 -3
  31. package/plugins/agent-os-dev/skills/init-agent-os/SKILL.md +131 -0
  32. package/plugins/agent-os-dev/skills/init-agent-os/policy.md +91 -0
  33. package/plugins/agent-os-dev/skills/init-agent-os/references/guards.md +40 -0
  34. package/plugins/agent-os-dev/skills/init-agent-os/references/repository-init.md +115 -0
  35. package/plugins/agent-os-dev/skills/init-agent-os/references/review-template.md +35 -0
  36. package/plugins/agent-os-dev/skills/init-agent-os/references/workflow-template.md +80 -0
  37. package/plugins/agent-os-dev/skills/init-agent-os/scripts/policy-block.mjs +187 -0
  38. package/plugins/agent-os-dev/skills/init-agent-os/templates/agent-review.yml +59 -0
  39. package/plugins/agent-os-dev/skills/init-agent-os/templates/lint-intents.yml +30 -0
  40. package/{skills → plugins/agent-os-dev/skills}/proportional-testing/SKILL.md +1 -1
  41. package/plugins/agent-os-dev/skills/quality-ratchet/SKILL.md +104 -0
  42. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/project-controls.md +31 -3
  43. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.mjs +145 -0
  44. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.test.mjs +158 -0
  45. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.mjs +372 -0
  46. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.test.mjs +138 -0
  47. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.mjs +322 -0
  48. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.test.mjs +177 -0
  49. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.mjs +59 -8
  50. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.test.mjs +134 -8
  51. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.mjs +296 -22
  52. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.test.mjs +114 -6
  53. package/plugins/agent-os-dev/skills/shape-work/SKILL.md +135 -0
  54. package/plugins/agent-os-dev/skills/shape-work/references/implementation-issues.md +163 -0
  55. package/{skills/plan-work → plugins/agent-os-dev/skills/shape-work}/references/prototypes.md +9 -10
  56. package/plugins/agent-os-dev/skills/simplify/SKILL.md +91 -0
  57. package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.mjs +166 -0
  58. package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.test.mjs +49 -0
  59. package/policy.md +57 -30
  60. package/hooks/hooks.json +0 -17
  61. package/skills/deliver-work/SKILL.md +0 -12
  62. package/skills/diagnose-before-fix/SKILL.md +0 -24
  63. package/skills/explain-work/SKILL.md +0 -28
  64. package/skills/init-agent-os/SKILL.md +0 -55
  65. package/skills/init-agent-os/references/repository-init.md +0 -75
  66. package/skills/init-agent-os/scripts/policy-block.ps1 +0 -87
  67. package/skills/notice-lesson/SKILL.md +0 -20
  68. package/skills/plan-work/SKILL.md +0 -100
  69. package/skills/quality-ratchet/SKILL.md +0 -72
  70. package/skills/record-lesson/SKILL.md +0 -31
  71. package/skills/shape-work/SKILL.md +0 -71
  72. package/skills/shape-work/references/implementation-issues.md +0 -90
  73. package/skills/shape-work/references/mockups.md +0 -23
  74. package/skills/simplifier/SKILL.md +0 -35
  75. package/skills/simplifier-audit/SKILL.md +0 -30
  76. package/skills/simplifier-review/SKILL.md +0 -40
  77. package/skills/understand-work/SKILL.md +0 -32
  78. package/skills/understand-work/agents/openai.yaml +0 -2
  79. package/skills/writing-skills/SKILL.md +0 -68
  80. package/skills/writing-skills/agents/openai.yaml +0 -2
  81. /package/{skills/batch-work → plugins/agent-os-core/skills/capture-intent}/agents/openai.yaml +0 -0
  82. /package/{skills/deliver-work → plugins/agent-os-core/skills/explain-work}/agents/openai.yaml +0 -0
  83. /package/{skills/dispatch-next → plugins/agent-os-core/skills/list-skills}/agents/openai.yaml +0 -0
  84. /package/{skills → plugins/agent-os-core/skills}/plain-voice/references/tells.md +0 -0
  85. /package/{skills/explain-work → plugins/agent-os-core/skills/plan-work}/agents/openai.yaml +0 -0
  86. /package/{skills → plugins/agent-os-core/skills}/plan-work/references/map.md +0 -0
  87. /package/{skills/init-agent-os → plugins/agent-os-dev/skills/batch-work}/agents/openai.yaml +0 -0
  88. /package/{skills → plugins/agent-os-dev/skills}/batch-work/references/manifest.md +0 -0
  89. /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/manifest-hash.mjs +0 -0
  90. /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/test-manifest-hash.mjs +0 -0
  91. /package/{skills → plugins/agent-os-dev/skills}/check-work/references/findings.md +0 -0
  92. /package/{skills/list-skills → plugins/agent-os-dev/skills/deliver-work}/agents/openai.yaml +0 -0
  93. /package/{skills/plan-work → plugins/agent-os-dev/skills/design-work}/agents/openai.yaml +0 -0
  94. /package/{skills/record-lesson → plugins/agent-os-dev/skills/dispatch-next}/agents/openai.yaml +0 -0
  95. /package/{skills/shape-work → plugins/agent-os-dev/skills/init-agent-os}/agents/openai.yaml +0 -0
  96. /package/{skills → plugins/agent-os-dev/skills}/proportional-testing/references/strategy.md +0 -0
  97. /package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/structure.md +0 -0
  98. /package/{skills/simplifier-audit → plugins/agent-os-dev/skills/shape-work}/agents/openai.yaml +0 -0
  99. /package/{skills/simplifier → plugins/agent-os-dev/skills/simplify}/agents/openai.yaml +0 -0
@@ -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
+ })