@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.
Files changed (96) hide show
  1. package/README.md +102 -48
  2. package/cli/doctor.mjs +307 -0
  3. package/cli/index.mjs +328 -151
  4. package/cli/index.test.mjs +406 -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 +65 -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 +13 -6
  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 +133 -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 +64 -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 +5 -2
  23. package/{skills → plugins/agent-os-dev/skills}/check-work/SKILL.md +31 -14
  24. package/{skills/deliver-work/workflow.md → plugins/agent-os-dev/skills/deliver-work/SKILL.md} +77 -42
  25. package/plugins/agent-os-dev/skills/design-work/SKILL.md +145 -0
  26. package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.mjs +233 -0
  27. package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.test.mjs +73 -0
  28. package/plugins/agent-os-dev/skills/diagnose-before-fix/SKILL.md +29 -0
  29. package/{skills → plugins/agent-os-dev/skills}/dispatch-next/SKILL.md +6 -1
  30. package/plugins/agent-os-dev/skills/init-agent-os/SKILL.md +121 -0
  31. package/plugins/agent-os-dev/skills/init-agent-os/policy.md +88 -0
  32. package/plugins/agent-os-dev/skills/init-agent-os/references/guards.md +39 -0
  33. package/{skills → plugins/agent-os-dev/skills}/init-agent-os/references/repository-init.md +41 -10
  34. package/plugins/agent-os-dev/skills/init-agent-os/references/review-template.md +35 -0
  35. package/plugins/agent-os-dev/skills/init-agent-os/scripts/policy-block.mjs +187 -0
  36. package/plugins/agent-os-dev/skills/init-agent-os/templates/agent-review.yml +59 -0
  37. package/plugins/agent-os-dev/skills/init-agent-os/templates/lint-intents.yml +30 -0
  38. package/{skills → plugins/agent-os-dev/skills}/proportional-testing/SKILL.md +1 -1
  39. package/plugins/agent-os-dev/skills/quality-ratchet/SKILL.md +103 -0
  40. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/project-controls.md +31 -3
  41. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.mjs +145 -0
  42. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.test.mjs +158 -0
  43. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.mjs +372 -0
  44. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.test.mjs +138 -0
  45. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.mjs +322 -0
  46. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.test.mjs +172 -0
  47. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.mjs +59 -8
  48. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.test.mjs +134 -8
  49. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.mjs +296 -22
  50. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.test.mjs +114 -6
  51. package/plugins/agent-os-dev/skills/shape-work/SKILL.md +124 -0
  52. package/plugins/agent-os-dev/skills/shape-work/references/implementation-issues.md +143 -0
  53. package/{skills/plan-work → plugins/agent-os-dev/skills/shape-work}/references/prototypes.md +9 -10
  54. package/plugins/agent-os-dev/skills/simplify/SKILL.md +91 -0
  55. package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.mjs +166 -0
  56. package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.test.mjs +49 -0
  57. package/policy.md +48 -24
  58. package/hooks/hooks.json +0 -17
  59. package/skills/deliver-work/SKILL.md +0 -12
  60. package/skills/diagnose-before-fix/SKILL.md +0 -24
  61. package/skills/explain-work/SKILL.md +0 -28
  62. package/skills/init-agent-os/SKILL.md +0 -55
  63. package/skills/init-agent-os/scripts/policy-block.ps1 +0 -87
  64. package/skills/notice-lesson/SKILL.md +0 -20
  65. package/skills/plan-work/SKILL.md +0 -100
  66. package/skills/quality-ratchet/SKILL.md +0 -72
  67. package/skills/record-lesson/SKILL.md +0 -31
  68. package/skills/shape-work/SKILL.md +0 -71
  69. package/skills/shape-work/references/implementation-issues.md +0 -90
  70. package/skills/shape-work/references/mockups.md +0 -23
  71. package/skills/simplifier/SKILL.md +0 -35
  72. package/skills/simplifier-audit/SKILL.md +0 -30
  73. package/skills/simplifier-review/SKILL.md +0 -40
  74. package/skills/understand-work/SKILL.md +0 -32
  75. package/skills/understand-work/agents/openai.yaml +0 -2
  76. package/skills/writing-skills/SKILL.md +0 -68
  77. package/skills/writing-skills/agents/openai.yaml +0 -2
  78. /package/{skills/batch-work → plugins/agent-os-core/skills/capture-intent}/agents/openai.yaml +0 -0
  79. /package/{skills/deliver-work → plugins/agent-os-core/skills/explain-work}/agents/openai.yaml +0 -0
  80. /package/{skills/dispatch-next → plugins/agent-os-core/skills/list-skills}/agents/openai.yaml +0 -0
  81. /package/{skills → plugins/agent-os-core/skills}/plain-voice/references/tells.md +0 -0
  82. /package/{skills/explain-work → plugins/agent-os-core/skills/plan-work}/agents/openai.yaml +0 -0
  83. /package/{skills → plugins/agent-os-core/skills}/plan-work/references/map.md +0 -0
  84. /package/{skills/init-agent-os → plugins/agent-os-dev/skills/batch-work}/agents/openai.yaml +0 -0
  85. /package/{skills → plugins/agent-os-dev/skills}/batch-work/references/manifest.md +0 -0
  86. /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/manifest-hash.mjs +0 -0
  87. /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/test-manifest-hash.mjs +0 -0
  88. /package/{skills → plugins/agent-os-dev/skills}/check-work/references/findings.md +0 -0
  89. /package/{skills/list-skills → plugins/agent-os-dev/skills/deliver-work}/agents/openai.yaml +0 -0
  90. /package/{skills/plan-work → plugins/agent-os-dev/skills/design-work}/agents/openai.yaml +0 -0
  91. /package/{skills/record-lesson → plugins/agent-os-dev/skills/dispatch-next}/agents/openai.yaml +0 -0
  92. /package/{skills/shape-work → plugins/agent-os-dev/skills/init-agent-os}/agents/openai.yaml +0 -0
  93. /package/{skills → plugins/agent-os-dev/skills}/proportional-testing/references/strategy.md +0 -0
  94. /package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/structure.md +0 -0
  95. /package/{skills/simplifier-audit → plugins/agent-os-dev/skills/shape-work}/agents/openai.yaml +0 -0
  96. /package/{skills/simplifier → plugins/agent-os-dev/skills/simplify}/agents/openai.yaml +0 -0
@@ -0,0 +1,322 @@
1
+ // Reads and checks intents/<id>/{intent,spec,plan}.md. Shared by the guard hooks and the
2
+ // `agent-os lint-intents` command, so both read the files the same way.
3
+
4
+ import { spawnSync } from 'node:child_process'
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ export const INTENTS_DIR = 'intents'
9
+ export const INTENT_FILES = ['intent.md', 'spec.md', 'plan.md']
10
+ export const ID_PATTERN = /^\d{4}-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*$/
11
+ export const STATUSES = {
12
+ 'intent.md': ['accepted', 'done', 'superseded'],
13
+ 'spec.md': ['accepted', 'superseded'],
14
+ 'plan.md': ['accepted', 'done', 'superseded']
15
+ }
16
+ const UPSTREAM = { 'spec.md': 'intent', 'plan.md': 'spec' }
17
+ const UNIT_LINE = /^-\s+\[([A-Za-z0-9][A-Za-z0-9._/-]*)\]\s+(.+)$/
18
+ const DEPENDS = /^depends on\s+(.+)$/i
19
+ const BLOCKED = /^blocked:\s*(.+)$/i
20
+ const UNIT_FIELDS = ['Outcome', 'Boundaries', 'Change surface', 'Acceptance', 'Ground truth', 'Dependencies', 'Evidence and settled decisions', 'Delivery target', 'Open risks']
21
+ const UNIT_FIELD_LINE = new RegExp(`^(${UNIT_FIELDS.join('|')})(?:\\s*\\([^)]*\\))?:\\s*(.*)$`)
22
+ const UNIT_LENGTH_WARNING = 5000
23
+ const POINTER_WORD =/^(?:spec|behaviou?rs?|examples?|sections?|headings?|lines?|rules?|see|the|in|and|to|of|all|first|second|third)$/i
24
+
25
+ // Frontmatter is a flat `key: value` block between two `---` lines; values stay strings.
26
+ export function parseFrontmatter(text) {
27
+ const normalized = String(text).replace(/\r\n/g, '\n')
28
+ const match = /^---\n([\s\S]*?)\n---\n?/.exec(normalized)
29
+ if (!match) return null
30
+ const data = {}
31
+ for (const line of match[1].split('\n')) {
32
+ const entry = /^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*?)\s*$/.exec(line)
33
+ if (entry) data[entry[1]] = entry[2].replace(/^(['"])(.*)\1$/, '$2')
34
+ }
35
+ return { data, body: normalized.slice(match[0].length) }
36
+ }
37
+
38
+ export function parseRev(value) {
39
+ return /^[1-9]\d*$/.test(String(value ?? '')) ? Number(value) : null
40
+ }
41
+
42
+ export function parseBuiltOn(value, kind) {
43
+ const match = new RegExp(`^${kind}@([1-9]\\d*)$`).exec(String(value ?? ''))
44
+ return match ? Number(match[1]) : null
45
+ }
46
+
47
+ // Unit lines: `- [KEY] title`, optionally ` — depends on A, B` and ` — blocked: reason`.
48
+ export function parseUnits(body) {
49
+ const lines = String(body).replace(/\r\n/g, '\n').split('\n')
50
+ const start = lines.findIndex((line) => /^##\s+Units\s*$/.test(line))
51
+ if (start < 0) return null
52
+ const units = []
53
+ for (const line of lines.slice(start + 1)) {
54
+ if (/^##\s/.test(line)) break
55
+ const match = UNIT_LINE.exec(line.trim())
56
+ if (!match) continue
57
+ const [title, ...notes] = match[2].split(/\s+(?:—|--)\s+/)
58
+ const unit = { key: match[1], title: title.trim(), depends: [], blocked: null }
59
+ for (const note of notes) {
60
+ const depends = DEPENDS.exec(note.trim())
61
+ const blocked = BLOCKED.exec(note.trim())
62
+ if (depends) unit.depends.push(...depends[1].split(',').map((key) => key.trim()).filter(Boolean))
63
+ else if (blocked) unit.blocked = blocked[1].trim()
64
+ }
65
+ units.push(unit)
66
+ }
67
+ return units
68
+ }
69
+
70
+ // Each `### KEY title` section mapped to its contract fields. A field value runs until the next field.
71
+ export function unitContracts(body) {
72
+ const contracts = new Map()
73
+ let fields = null
74
+ let field = null
75
+ for (const line of String(body).replace(/\r\n/g, '\n').split('\n')) {
76
+ const heading = /^###\s+(\S+)/.exec(line)
77
+ if (heading) {
78
+ fields = {}
79
+ field = null
80
+ contracts.set(heading[1], fields)
81
+ continue
82
+ }
83
+ if (/^##\s/.test(line)) fields = null
84
+ if (!fields) continue
85
+ const label = UNIT_FIELD_LINE.exec(line)
86
+ if (label) {
87
+ field = label[1]
88
+ fields[field] = label[2]
89
+ } else if (field) {
90
+ fields[field] += `\n${line}`
91
+ }
92
+ }
93
+ return contracts
94
+ }
95
+
96
+ // Acceptance that names only spec locations, such as "behaviors 1 to 3 (server side)". Parentheses,
97
+ // quotes, numbers, and file paths are citations; fewer than three other words cannot state a check.
98
+ function isBarePointer(acceptance) {
99
+ const words = acceptance.replace(/\([^)]*\)|"[^"]*"|`[^`]*`/g, ' ').match(/[A-Za-z][\w/-]*(?:\.\w+)*/g) ?? []
100
+ return words.filter((word) => !POINTER_WORD.test(word) && !/\.md$/i.test(word)).length < 3
101
+ }
102
+
103
+ function checkUnitContract(unit, fields, warn) {
104
+ for (const name of UNIT_FIELDS) {
105
+ if (!fields[name]?.trim()) warn(`unit ${unit.key} has no "${name}:" field`)
106
+ }
107
+ if (fields.Acceptance?.trim() && isBarePointer(fields.Acceptance)) {
108
+ warn(`unit ${unit.key} acceptance only points at the spec; write out the checks`)
109
+ }
110
+ const length = Object.values(fields).join('').length
111
+ if (length > UNIT_LENGTH_WARNING) {
112
+ warn(`unit ${unit.key} contract is ${length} characters; cut what retells the spec or split it to stay under ${UNIT_LENGTH_WARNING}`)
113
+ }
114
+ }
115
+
116
+ function readFile(file) {
117
+ try {
118
+ return fs.readFileSync(file, 'utf8')
119
+ } catch {
120
+ return null
121
+ }
122
+ }
123
+
124
+ export function readIntent(root, id, dir = INTENTS_DIR) {
125
+ const folder = { id, path: path.join(root, dir, id), files: {} }
126
+ for (const name of INTENT_FILES) {
127
+ const text = readFile(path.join(folder.path, name))
128
+ if (text === null) continue
129
+ folder.files[name] = { name, relative: `${dir}/${id}/${name}`, text, ...(parseFrontmatter(text) ?? { data: null, body: text }) }
130
+ }
131
+ return folder
132
+ }
133
+
134
+ export function listIntents(root, dir = INTENTS_DIR) {
135
+ const base = path.join(root, dir)
136
+ if (!fs.existsSync(base)) return []
137
+ return fs.readdirSync(base, { withFileTypes: true })
138
+ .filter((entry) => entry.isDirectory())
139
+ .map((entry) => readIntent(root, entry.name, dir))
140
+ .filter((folder) => Object.keys(folder.files).length > 0)
141
+ .sort((a, b) => a.id.localeCompare(b.id))
142
+ }
143
+
144
+ // A spec built on an older intent revision, or a plan built on an older spec revision, is stale.
145
+ export function staleness(folder) {
146
+ const stale = []
147
+ for (const name of ['spec.md', 'plan.md']) {
148
+ const file = folder.files[name]
149
+ const kind = UPSTREAM[name]
150
+ const upstream = folder.files[`${kind}.md`]
151
+ if (!file?.data || !upstream?.data) continue
152
+ const builtOn = parseBuiltOn(file.data.built_on, kind)
153
+ const current = parseRev(upstream.data.rev)
154
+ if (builtOn !== null && current !== null && builtOn < current) {
155
+ stale.push({ file: file.relative, kind, builtOn, current })
156
+ }
157
+ }
158
+ return stale
159
+ }
160
+
161
+ // The body of a spec's `## Interface` section, or null when it has none.
162
+ function interfaceSection(body) {
163
+ const lines = String(body).replace(/\r\n/g, '\n').split('\n')
164
+ const start = lines.findIndex((line) => /^##\s+Interface\s*$/.test(line))
165
+ if (start < 0) return null
166
+ const end = lines.findIndex((line, index) => index > start && /^##\s/.test(line))
167
+ return lines.slice(start + 1, end < 0 ? undefined : end).join('\n').trim()
168
+ }
169
+
170
+ function interfaceBullets(section) {
171
+ const bullets = []
172
+ for (const line of section.split('\n')) {
173
+ if (/^[-*]\s/.test(line)) bullets.push(line.replace(/^[-*]\s+/, ''))
174
+ else if (/^\s+\S/.test(line) && bullets.length > 0) bullets[bullets.length - 1] += ` ${line.trim()}`
175
+ }
176
+ return bullets
177
+ }
178
+
179
+ // Files named by inline code or a link, for the formats a sketch comes in. A story title or a URL
180
+ // is not a file, so neither is checked.
181
+ function sketchFiles(section) {
182
+ const references = [...section.matchAll(/`([^`\s]+)`|\]\(([^)\s]+)\)/g)].map((match) => match[1] ?? match[2])
183
+ return [...new Set(references)].filter((reference) => !/^[a-z][a-z0-9+.-]*:\/\//i.test(reference) &&
184
+ /\.(?:html?|png|jpe?g|gif|webp|svg|pdf|mdx)$|\.stories\.[jt]sx?$/i.test(reference))
185
+ }
186
+
187
+ function checkInterface(folder, file, root, warn) {
188
+ const section = interfaceSection(file.body)
189
+ if (section === null) return warn('needs a "## Interface" section; write None when nothing a person sees or does changes')
190
+ if (!section) return warn('"## Interface" is empty; list each surface or write None')
191
+ if (/^none\.?$/i.test(section)) return undefined
192
+ for (const bullet of interfaceBullets(section)) {
193
+ const label = bullet.length > 60 ? `${bullet.slice(0, 57)}...` : bullet
194
+ if (/\bDeferred to\b/.test(bullet)) {
195
+ if (!/\bDeferred to\s+\S.*?\s+by\s+\S/.test(bullet)) warn(`interface surface "${label}" is deferred without an owner and a date`)
196
+ } else if (/\bOpen:/.test(bullet)) warn(`interface surface "${label}" is still open`)
197
+ else if (!/\bDecided:/.test(bullet)) warn(`interface surface "${label}" has no Decided:, Deferred to, or Open:`)
198
+ }
199
+ const inside = (candidate) => !path.relative(root, candidate).startsWith('..')
200
+ for (const reference of sketchFiles(section)) {
201
+ const machinePath = /^(?:[A-Za-z]:[\\/]|[\\/~])/.test(reference)
202
+ const candidates = machinePath ? [] : [path.resolve(root, reference), path.resolve(folder.path, reference)]
203
+ if (candidates.some((candidate) => inside(candidate) && fs.existsSync(candidate))) continue
204
+ if (machinePath || !inside(path.resolve(root, reference))) {
205
+ warn(`interface names ${reference}, which exists only on one machine; use a repository path, a pull request image, or a URL`)
206
+ } else warn(`interface names ${reference}, which does not exist`)
207
+ }
208
+ return undefined
209
+ }
210
+
211
+ function checkFile(folder, name, ids, problems, root) {
212
+ const file = folder.files[name]
213
+ if (!file) return
214
+ const error = (message) => problems.push({ level: 'error', file: file.relative, message })
215
+ if (!file.data) return error('missing frontmatter between --- lines')
216
+ const { data } = file
217
+ if (name === 'intent.md' && data.id !== folder.id) error(`id "${data.id ?? ''}" must equal the folder name "${folder.id}"`)
218
+ if (name !== 'intent.md' && data.intent !== folder.id) error(`intent "${data.intent ?? ''}" must equal the folder name "${folder.id}"`)
219
+ if (!STATUSES[name].includes(data.status)) error(`status must be one of ${STATUSES[name].join(', ')}`)
220
+ if (parseRev(data.rev) === null) error('rev must be a positive integer')
221
+ if (name === 'intent.md' && data.supersedes && data.supersedes !== 'null' && !ids.has(data.supersedes)) {
222
+ error(`supersedes "${data.supersedes}" is not an intent in this repository`)
223
+ }
224
+ if (name !== 'intent.md') {
225
+ const kind = UPSTREAM[name]
226
+ const builtOn = parseBuiltOn(data.built_on, kind)
227
+ const upstream = folder.files[`${kind}.md`]
228
+ const current = parseRev(upstream?.data?.rev)
229
+ if (builtOn === null) error(`built_on must look like ${kind}@<rev>`)
230
+ else if (!upstream) error(`built_on names ${kind}@${builtOn}, but ${kind}.md is missing`)
231
+ else if (current !== null && builtOn > current) error(`built_on ${kind}@${builtOn} is newer than ${kind}.md rev ${current}`)
232
+ }
233
+ if (name === 'spec.md' && data.status === 'accepted') {
234
+ checkInterface(folder, file, root, (message) => problems.push({ level: 'warning', file: file.relative, message }))
235
+ }
236
+ if (name === 'plan.md') {
237
+ if (!['files', 'issues'].includes(data.source)) error('source must be files or issues')
238
+ const units = parseUnits(file.body)
239
+ if (!units || units.length === 0) return error('needs a "## Units" section with at least one "- [KEY] title" line')
240
+ const keys = new Set()
241
+ for (const unit of units) {
242
+ if (keys.has(unit.key)) error(`unit key ${unit.key} appears twice`)
243
+ keys.add(unit.key)
244
+ }
245
+ if (data.source === 'files') {
246
+ const contracts = unitContracts(file.body)
247
+ const warn = (message) => problems.push({ level: 'warning', file: file.relative, message })
248
+ for (const unit of units) {
249
+ for (const dependency of unit.depends) {
250
+ if (!keys.has(dependency)) error(`unit ${unit.key} depends on unknown unit ${dependency}`)
251
+ }
252
+ const fields = contracts.get(unit.key)
253
+ if (!fields) error(`unit ${unit.key} needs a "### ${unit.key} <title>" section with its contract`)
254
+ else if (data.status === 'accepted' && !unit.blocked) checkUnitContract(unit, fields, warn)
255
+ }
256
+ }
257
+ }
258
+ }
259
+
260
+ function gitShow(root, ref, relative) {
261
+ const result = spawnSync('git', ['-C', root, 'show', `${ref}:${relative}`], { encoding: 'utf8' })
262
+ return result.status === 0 ? result.stdout : null
263
+ }
264
+
265
+ function changedFiles(root, base, dir) {
266
+ const result = spawnSync('git', ['-C', root, 'diff', '--name-only', `${base}...HEAD`, '--', dir], { encoding: 'utf8' })
267
+ if (result.status !== 0) throw new Error(`git diff against ${base} failed: ${(result.stderr || '').trim()}`)
268
+ return result.stdout.split('\n').map((line) => line.trim()).filter((line) => line.endsWith('.md'))
269
+ }
270
+
271
+ // Changing the text of an accepted file needs a higher rev; frontmatter-only edits such as a status
272
+ // change or a confirmed built_on do not.
273
+ function checkRevisions(root, base, dir, allowUnchangedRev, problems) {
274
+ for (const relative of changedFiles(root, base, dir)) {
275
+ const before = gitShow(root, base, relative)
276
+ const afterText = readFile(path.join(root, relative))
277
+ if (before === null || afterText === null) continue
278
+ const old = parseFrontmatter(before)
279
+ const now = parseFrontmatter(afterText)
280
+ if (!old?.data || !now?.data || old.data.status !== 'accepted') continue
281
+ const oldRev = parseRev(old.data.rev)
282
+ const newRev = parseRev(now.data.rev)
283
+ if (oldRev !== null && newRev !== null && newRev < oldRev) {
284
+ problems.push({ level: 'error', file: relative, message: `rev went down from ${oldRev} to ${newRev}` })
285
+ } else if (old.body.trim() !== now.body.trim() && oldRev !== null && newRev === oldRev && !allowUnchangedRev) {
286
+ problems.push({
287
+ level: 'error',
288
+ file: relative,
289
+ message: `an accepted file changed without raising rev ${oldRev}; raise it and add a decision log line, or mark a pure wording fix as allowed`
290
+ })
291
+ }
292
+ }
293
+ }
294
+
295
+ export function lintIntents(root, { dir = INTENTS_DIR, base = null, allowUnchangedRev = false } = {}) {
296
+ const problems = []
297
+ const base_ = path.join(root, dir)
298
+ if (fs.existsSync(base_)) {
299
+ for (const entry of fs.readdirSync(base_, { withFileTypes: true })) {
300
+ if (entry.isDirectory() && !ID_PATTERN.test(entry.name)) {
301
+ problems.push({ level: 'error', file: `${dir}/${entry.name}`, message: 'folder name must be <YYYY-MM>-<slug> in lowercase kebab-case' })
302
+ }
303
+ }
304
+ }
305
+ const folders = listIntents(root, dir)
306
+ const ids = new Set(folders.map((folder) => folder.id))
307
+ for (const folder of folders) {
308
+ if (!folder.files['intent.md']) {
309
+ problems.push({ level: 'error', file: `${dir}/${folder.id}`, message: 'intent.md is missing' })
310
+ }
311
+ for (const name of INTENT_FILES) checkFile(folder, name, ids, problems, root)
312
+ for (const item of staleness(folder)) {
313
+ problems.push({
314
+ level: 'warning',
315
+ file: item.file,
316
+ message: `stale: built on ${item.kind}@${item.builtOn}, but ${item.kind}.md is at rev ${item.current}`
317
+ })
318
+ }
319
+ }
320
+ if (base) checkRevisions(root, base, dir, allowUnchangedRev, problems)
321
+ return problems
322
+ }
@@ -0,0 +1,172 @@
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 { lintIntents, parseFrontmatter, parseUnits } from './intent-files.mjs'
8
+
9
+ function git(root, ...args) {
10
+ const result = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' })
11
+ assert.equal(result.status, 0, result.stderr)
12
+ }
13
+
14
+ const intent = (rev = 1, body = '# Export\n') =>
15
+ `---\nid: 2026-11-csv-export\nstatus: accepted\nrev: ${rev}\nsupersedes: null\n---\n${body}`
16
+ const spec = (builtOn = 1, rev = 1, face = '## Interface\n\nNone\n') =>
17
+ `---\nintent: 2026-11-csv-export\nrev: ${rev}\nbuilt_on: intent@${builtOn}\nstatus: accepted\n---\n# Export\n\n${face}`
18
+ const plan = (units, sections = '') =>
19
+ `---\nintent: 2026-11-csv-export\nrev: 1\nbuilt_on: spec@1\nstatus: accepted\nsource: files\n---\n## Units\n\n${units}\n\n${sections}`
20
+
21
+ const contract = (heading, acceptance = '- Given a filter, when exported, then the CSV holds the filtered rows (spec example 1).') =>
22
+ `### ${heading}\n\nOutcome: x\nBoundaries: x\nChange surface: x\nAcceptance:\n${acceptance}\nGround truth: x\nDependencies: none\n` +
23
+ 'Evidence and settled decisions: none\nDelivery target: pull request\nOpen risks: none\n\n'
24
+
25
+ function repository(files) {
26
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-intents-')))
27
+ for (const [relative, content] of Object.entries(files)) {
28
+ fs.mkdirSync(path.dirname(path.join(root, relative)), { recursive: true })
29
+ fs.writeFileSync(path.join(root, relative), content)
30
+ }
31
+ return root
32
+ }
33
+
34
+ const messages = (problems, level) => problems.filter((item) => item.level === level).map((item) => `${item.file}: ${item.message}`)
35
+
36
+ test('frontmatter and unit lines parse into plain values', () => {
37
+ assert.deepEqual(parseFrontmatter('---\nid: a\nrev: "2"\n---\nbody').data, { id: 'a', rev: '2' })
38
+ assert.equal(parseFrontmatter('no frontmatter'), null)
39
+ assert.deepEqual(parseUnits('## Units\n- [WEB-142] Export endpoint\n- [U2] Button — depends on WEB-142, U1 — blocked: copy text\n## Next'), [
40
+ { key: 'WEB-142', title: 'Export endpoint', depends: [], blocked: null },
41
+ { key: 'U2', title: 'Button', depends: ['WEB-142', 'U1'], blocked: 'copy text' }
42
+ ])
43
+ })
44
+
45
+ test('a consistent intent folder passes', () => {
46
+ const root = repository({
47
+ 'intents/2026-11-csv-export/intent.md': intent(),
48
+ 'intents/2026-11-csv-export/spec.md': spec(),
49
+ 'intents/2026-11-csv-export/plan.md': plan('- [U1] Endpoint\n- [U2] Button — depends on U1', contract('U1 Endpoint') + contract('U2 Button'))
50
+ })
51
+ assert.deepEqual(lintIntents(root), [])
52
+ })
53
+
54
+ test('a ready unit with a missing field or a bare acceptance pointer is a warning, not an error', () => {
55
+ const thin = contract('U1 Endpoint', 'behaviors 14 to 17, 20, 23 (server side).').replace('Change surface: x\n', '')
56
+ const root = repository({
57
+ 'intents/2026-11-csv-export/intent.md': intent(),
58
+ 'intents/2026-11-csv-export/spec.md': spec(),
59
+ 'intents/2026-11-csv-export/plan.md': plan('- [U1] Endpoint', thin)
60
+ })
61
+ assert.deepEqual(messages(lintIntents(root), 'error'), [])
62
+ assert.deepEqual(messages(lintIntents(root), 'warning'), [
63
+ 'intents/2026-11-csv-export/plan.md: unit U1 has no "Change surface:" field',
64
+ 'intents/2026-11-csv-export/plan.md: unit U1 acceptance only points at the spec; write out the checks'
65
+ ])
66
+ })
67
+
68
+ const interfaceWarnings = (face, extra = {}) => {
69
+ const root = repository({
70
+ 'intents/2026-11-csv-export/intent.md': intent(),
71
+ 'intents/2026-11-csv-export/spec.md': spec(1, 1, face),
72
+ ...extra
73
+ })
74
+ assert.deepEqual(messages(lintIntents(root), 'error'), [])
75
+ return messages(lintIntents(root), 'warning').map((line) => line.replace('intents/2026-11-csv-export/spec.md: ', ''))
76
+ }
77
+
78
+ test('a spec with decided surfaces and reachable sketches has no interface warnings', () => {
79
+ const face = '## Interface\n\n' +
80
+ '- Accountant, invoice list. Decided: export sits in the header, because they look there.\n' +
81
+ ' Rejected: filter bar. Sketch: `intents/2026-11-csv-export/sketches/list.html`.\n' +
82
+ '- Admin, settings. Deferred to Mira by 2026-12-01: where the limit is shown.\n' +
83
+ '- Accountant, empty list. Decided: no action. Sketch: [image](https://github.com/o/r/pull/1).\n\n## Boundaries\n'
84
+ assert.deepEqual(interfaceWarnings(face, { 'intents/2026-11-csv-export/sketches/list.html': 'x' }), [])
85
+ })
86
+
87
+ test('a missing or empty interface section is a warning, and None is enough', () => {
88
+ assert.deepEqual(interfaceWarnings(''), ['needs a "## Interface" section; write None when nothing a person sees or does changes'])
89
+ assert.deepEqual(interfaceWarnings('## Interface\n\n## Boundaries\n'), ['"## Interface" is empty; list each surface or write None'])
90
+ assert.deepEqual(interfaceWarnings('## Interface\n\nNone.\n'), [])
91
+ })
92
+
93
+ test('a surface without a decision or an owner is a warning', () => {
94
+ const warnings = interfaceWarnings('## Interface\n\n- Admin, settings. Open: where it goes.\n- Admin, list. Deferred to Mira: order.\n- Admin, page. Looks nice.\n')
95
+ assert.deepEqual(warnings, [
96
+ 'interface surface "Admin, settings. Open: where it goes." is still open',
97
+ 'interface surface "Admin, list. Deferred to Mira: order." is deferred without an owner and a date',
98
+ 'interface surface "Admin, page. Looks nice." has no Decided:, Deferred to, or Open:'
99
+ ])
100
+ })
101
+
102
+ test('a sketch must exist and be reachable by others', () => {
103
+ const warnings = interfaceWarnings('## Interface\n\n- A, B. Decided: x. Sketch: `gone.png`, `../outbox/a.png`, `C:/Users/me/a.png`, `Sketches/Export/Header`.\n')
104
+ assert.deepEqual(warnings, [
105
+ 'interface names gone.png, which does not exist',
106
+ 'interface names ../outbox/a.png, which exists only on one machine; use a repository path, a pull request image, or a URL',
107
+ 'interface names C:/Users/me/a.png, which exists only on one machine; use a repository path, a pull request image, or a URL'
108
+ ])
109
+ })
110
+
111
+ test('a field label may carry a parenthetical qualifier', () => {
112
+ const qualified = contract('U1 Endpoint').replace('Acceptance:', 'Acceptance (all with the mock server):')
113
+ const root = repository({
114
+ 'intents/2026-11-csv-export/intent.md': intent(),
115
+ 'intents/2026-11-csv-export/spec.md': spec(),
116
+ 'intents/2026-11-csv-export/plan.md': plan('- [U1] Endpoint', qualified)
117
+ })
118
+ assert.deepEqual(lintIntents(root), [])
119
+ })
120
+
121
+ test('an overlong unit is a warning that names its length', () => {
122
+ const longCheck = `- Given a filter, when exported, then the CSV holds the filtered rows (spec example 1). ${'x'.repeat(5000)}`
123
+ const root = repository({
124
+ 'intents/2026-11-csv-export/intent.md': intent(),
125
+ 'intents/2026-11-csv-export/spec.md': spec(),
126
+ 'intents/2026-11-csv-export/plan.md': plan('- [U1] Endpoint', contract('U1 Endpoint', longCheck))
127
+ })
128
+ assert.deepEqual(messages(lintIntents(root), 'error'), [])
129
+ assert.match(messages(lintIntents(root), 'warning').join('\n'), /unit U1 contract is \d+ characters; cut what retells the spec or split it/)
130
+ })
131
+
132
+ test('a blocked unit is not held to the ready contract', () => {
133
+ const root = repository({
134
+ 'intents/2026-11-csv-export/intent.md': intent(),
135
+ 'intents/2026-11-csv-export/spec.md': spec(),
136
+ 'intents/2026-11-csv-export/plan.md': plan('- [U1] Endpoint — blocked: which format', '### U1 Endpoint\n\nOutcome: x\n')
137
+ })
138
+ assert.deepEqual(lintIntents(root), [])
139
+ })
140
+
141
+ test('broken files are reported as errors and stale specs as warnings', () => {
142
+ const root = repository({
143
+ 'intents/Bad_Name/intent.md': intent(),
144
+ 'intents/2026-11-csv-export/intent.md': intent(2),
145
+ 'intents/2026-11-csv-export/spec.md': spec(1),
146
+ 'intents/2026-11-csv-export/plan.md': plan('- [U1] Endpoint — depends on U9\n- [U1] Again')
147
+ })
148
+ const errors = messages(lintIntents(root), 'error')
149
+ assert.ok(errors.some((line) => line.startsWith('intents/Bad_Name: folder name')))
150
+ assert.ok(errors.includes('intents/2026-11-csv-export/plan.md: unit key U1 appears twice'))
151
+ assert.ok(errors.includes('intents/2026-11-csv-export/plan.md: unit U1 depends on unknown unit U9'))
152
+ assert.deepEqual(messages(lintIntents(root), 'warning'), [
153
+ 'intents/2026-11-csv-export/spec.md: stale: built on intent@1, but intent.md is at rev 2'
154
+ ])
155
+ })
156
+
157
+ test('changing an accepted text needs a higher rev unless explicitly allowed', () => {
158
+ const root = repository({ 'intents/2026-11-csv-export/intent.md': intent(1) })
159
+ git(root, 'init', '-q', '-b', 'main')
160
+ git(root, 'config', 'user.email', 'test@example.invalid')
161
+ git(root, 'config', 'user.name', 'Test')
162
+ git(root, 'add', '-A')
163
+ git(root, 'commit', '-qm', 'base')
164
+ git(root, 'checkout', '-qb', 'change')
165
+ fs.writeFileSync(path.join(root, 'intents/2026-11-csv-export/intent.md'), intent(1, '# Export with Excel\n'))
166
+ git(root, 'commit', '-qam', 'change')
167
+ assert.match(messages(lintIntents(root, { base: 'main' }), 'error').join('\n'), /changed without raising rev 1/)
168
+ assert.deepEqual(messages(lintIntents(root, { base: 'main', allowUnchangedRev: true }), 'error'), [])
169
+ fs.writeFileSync(path.join(root, 'intents/2026-11-csv-export/intent.md'), intent(2, '# Export with Excel\n'))
170
+ git(root, 'commit', '-qam', 'raise rev')
171
+ assert.deepEqual(messages(lintIntents(root, { base: 'main' }), 'error'), [])
172
+ })
@@ -1,9 +1,11 @@
1
1
  import fs from 'node:fs'
2
+ import os from 'node:os'
2
3
  import path from 'node:path'
3
- import { createHash } from 'node:crypto'
4
+ import { createHash, randomUUID } from 'node:crypto'
4
5
  import { spawnSync } from 'node:child_process'
5
6
 
6
7
  export const POLICY_PATH = '.agent-os/quality.json'
8
+ export const DEFAULT_TRUST_STORE = path.join(os.homedir(), '.agent-os', 'trusted-controls.json')
7
9
  const SIGNALS = {
8
10
  'type-escape': /@ts-(?:ignore|nocheck|expect-error)\b|:\s*any\b|\bas\s+any\b/,
9
11
  'lint-disable': /eslint-disable|@SuppressWarnings\b/,
@@ -29,7 +31,7 @@ export function readPolicy(root) {
29
31
  const file = path.join(root, POLICY_PATH)
30
32
  if (!fs.existsSync(file)) return { schema: 1, checks: [], blockSignals: [], protectedFiles: [] }
31
33
  const policy = JSON.parse(fs.readFileSync(file, 'utf8'))
32
- exactKeys(policy, ['schema', 'checks', 'blockSignals', 'protectedFiles'], 'quality policy')
34
+ exactKeys(policy, ['schema', 'checks', 'blockSignals', 'protectedFiles', 'complexity'], 'quality policy')
33
35
  if (policy.schema !== 1 || !Array.isArray(policy.checks)) throw new Error('Quality policy requires schema 1 and checks')
34
36
  const ids = new Set()
35
37
  for (const check of policy.checks) {
@@ -54,9 +56,18 @@ export function readPolicy(root) {
54
56
  }
55
57
  policy.blockSignals ??= []
56
58
  policy.protectedFiles ??= []
57
- if (!Array.isArray(policy.blockSignals) || policy.blockSignals.some(name => !Object.hasOwn(SIGNALS, name))) {
59
+ if (!Array.isArray(policy.blockSignals) ||
60
+ policy.blockSignals.some(name => !Object.hasOwn(SIGNALS, name) && name !== 'complexity')) {
58
61
  throw new Error('Unknown blockSignals rule')
59
62
  }
63
+ if (policy.complexity !== undefined) {
64
+ exactKeys(policy.complexity, ['threshold'], 'complexity')
65
+ const { threshold } = policy.complexity
66
+ if (!Number.isInteger(threshold) || threshold < 1 || threshold > 200) throw new Error('complexity.threshold must be an integer between 1 and 200')
67
+ }
68
+ if (policy.blockSignals.includes('complexity') && !policy.complexity) {
69
+ throw new Error('The complexity blockSignals rule requires complexity.threshold')
70
+ }
60
71
  if (!Array.isArray(policy.protectedFiles) || !policy.protectedFiles.every(relativeFile)) throw new Error('Invalid protectedFiles')
61
72
  return policy
62
73
  }
@@ -123,17 +134,56 @@ function executable(root, name, env) {
123
134
  throw new Error(`Executable unavailable: ${name}`)
124
135
  }
125
136
 
126
- export function prepareControls(root, files, env = process.env) {
127
- const policy = readPolicy(root)
128
- const fileIdentity = files.map(file => [file.path, file.kind, file.hash, file.mode])
129
- const environment = identity(Object.entries(env).sort(([a], [b]) => a.localeCompare(b)))
137
+ // The declared controls: the policy plus the protected files that implement it.
138
+ export function controlSignature(root, policy = readPolicy(root)) {
130
139
  const protectedIdentity = [POLICY_PATH, ...policy.protectedFiles].map(name => {
131
140
  try { return [name, inputHash(root, name)] } catch (error) {
132
141
  if (error.code === 'ENOENT') return [name, null]
133
142
  throw error
134
143
  }
135
144
  })
136
- const signature = identity({ policy, protectedIdentity })
145
+ return identity({ policy, protectedIdentity })
146
+ }
147
+
148
+ // A repository's quality.json can name any program, and check runs it with the developer's
149
+ // environment. The developer trusts each repository's declared controls once per signature from an
150
+ // interactive terminal before check runs them. The store lives outside every repository.
151
+ function readTrustStore(file) {
152
+ try {
153
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'))
154
+ if (value?.schema === 1 && value.trusted && typeof value.trusted === 'object' && !Array.isArray(value.trusted)) return value
155
+ } catch {
156
+ // A missing or unreadable store trusts nothing.
157
+ }
158
+ return { schema: 1, trusted: {} }
159
+ }
160
+
161
+ const trustKey = (repository, signature) => identity({ repository, signature })
162
+
163
+ export function controlsTrusted(repository, signature, trustStore = DEFAULT_TRUST_STORE) {
164
+ return Object.hasOwn(readTrustStore(trustStore).trusted, trustKey(repository, signature))
165
+ }
166
+
167
+ export function recordControlsTrust(repository, signature, checks, trustStore = DEFAULT_TRUST_STORE) {
168
+ const store = readTrustStore(trustStore)
169
+ store.trusted[trustKey(repository, signature)] = {
170
+ repository, trustedAt: new Date().toISOString(), commands: checks.map(check => [check.id, check.command])
171
+ }
172
+ fs.mkdirSync(path.dirname(trustStore), { recursive: true })
173
+ const temporary = `${trustStore}.${randomUUID()}.tmp`
174
+ try {
175
+ fs.writeFileSync(temporary, JSON.stringify(store, null, 2) + '\n')
176
+ fs.renameSync(temporary, trustStore)
177
+ } finally {
178
+ if (fs.existsSync(temporary)) fs.rmSync(temporary, { force: true })
179
+ }
180
+ }
181
+
182
+ export function prepareControls(root, files, env = process.env) {
183
+ const policy = readPolicy(root)
184
+ const fileIdentity = files.map(file => [file.path, file.kind, file.hash, file.mode])
185
+ const environment = identity(Object.entries(env).sort(([a], [b]) => a.localeCompare(b)))
186
+ const signature = controlSignature(root, policy)
137
187
  const checks = policy.checks.map(check => {
138
188
  try {
139
189
  if (check.cache && files.some(file => !['file', 'missing'].includes(file.kind))) {
@@ -179,6 +229,7 @@ export function blockingControls(report) {
179
229
  if (!report) return []
180
230
  return [
181
231
  ...(report.policyChanged ? ['quality policy changed: restore it or explicitly acknowledge the authorized change'] : []),
232
+ ...(report.untrusted ? ['project controls are not trusted on this machine: the developer must run trust in an interactive terminal'] : []),
182
233
  ...(report.stale ? ['inputs changed during verification; run check again'] : []),
183
234
  ...report.results.filter(result => result.required && result.status !== 'passed').map(result => `${result.id}: ${result.status}`),
184
235
  ...report.signals.filter(signal => signal.required).map(signal => `${signal.path}:${signal.line} ${signal.rule}`)