@sockulags/agent-os 0.11.0 → 0.12.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 +155 -127
- package/cli/index.mjs +1022 -735
- package/cli/index.test.mjs +574 -300
- package/hooks/hooks.json +17 -0
- package/package.json +34 -32
- package/policy.md +47 -45
- package/skills/batch-work/SKILL.md +43 -43
- package/skills/batch-work/agents/openai.yaml +2 -2
- package/skills/batch-work/references/manifest.md +100 -100
- package/skills/batch-work/scripts/manifest-hash.mjs +263 -263
- package/skills/batch-work/scripts/test-manifest-hash.mjs +132 -132
- package/skills/chart-work/SKILL.md +37 -37
- package/skills/chart-work/references/elicitation.md +25 -25
- package/skills/chart-work/references/map.md +84 -84
- package/skills/chart-work/references/prototypes.md +21 -21
- package/skills/check-work/SKILL.md +61 -0
- package/skills/deliver-work/SKILL.md +12 -12
- package/skills/deliver-work/workflow.md +119 -113
- package/skills/diagnose-before-fix/SKILL.md +24 -24
- package/skills/dispatch-next/SKILL.md +28 -28
- package/skills/init-agent-os/SKILL.md +54 -39
- package/skills/init-agent-os/references/repository-init.md +74 -0
- package/skills/init-agent-os/scripts/policy-block.ps1 +87 -87
- package/skills/list-skills/SKILL.md +43 -42
- package/skills/list-skills/agents/openai.yaml +2 -2
- package/skills/plain-voice/SKILL.md +39 -0
- package/skills/plain-voice/references/tells.md +82 -0
- package/skills/proportional-testing/SKILL.md +30 -30
- package/skills/proportional-testing/references/strategy.md +75 -75
- package/skills/quality-ratchet/SKILL.md +50 -0
- package/skills/quality-ratchet/scripts/quality-delta.mjs +752 -0
- package/skills/quality-ratchet/scripts/quality-delta.test.mjs +514 -0
- package/skills/scope-guard/SKILL.md +21 -21
- package/skills/shape-work/SKILL.md +39 -39
- package/skills/shape-work/references/implementation-issues.md +69 -69
- package/skills/shape-work/references/mockups.md +23 -23
- package/skills/simplifier/SKILL.md +34 -34
- package/skills/simplifier/agents/openai.yaml +2 -2
- package/skills/simplifier-audit/SKILL.md +28 -28
- package/skills/simplifier-audit/agents/openai.yaml +2 -2
- package/skills/simplifier-review/SKILL.md +36 -29
- package/skills/verify-before-done/SKILL.md +29 -29
- package/skills/writing-skills/SKILL.md +68 -68
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawnSync } from 'node:child_process'
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
8
|
+
|
|
9
|
+
export const STATE_SCHEMA = 2
|
|
10
|
+
export const STATE_FILE_NAME = '.agent-os-quality-ratchet.json'
|
|
11
|
+
export const QUALITY_HOOK_MARKER = '--agent-os-hook=quality-ratchet'
|
|
12
|
+
export const HOOK_TIMEOUT_SECONDS = 10
|
|
13
|
+
|
|
14
|
+
const SOURCE_EXTENSIONS = new Set([
|
|
15
|
+
'.c', '.cc', '.cpp', '.cxx', '.cs', '.css', '.go', '.h', '.hpp', '.java', '.js', '.jsx',
|
|
16
|
+
'.jsonc', '.kts', '.kt', '.m', '.mjs', '.cjs', '.php', '.py', '.rb', '.rs', '.scala',
|
|
17
|
+
'.sh', '.sql', '.swift', '.ts', '.tsx', '.vue', '.svelte'
|
|
18
|
+
])
|
|
19
|
+
const DEPENDENCY_SECTIONS = [
|
|
20
|
+
'dependencies',
|
|
21
|
+
'devDependencies',
|
|
22
|
+
'optionalDependencies',
|
|
23
|
+
'peerDependencies'
|
|
24
|
+
]
|
|
25
|
+
const OPTIONAL_ANALYZERS = ['lizard', 'jscpd']
|
|
26
|
+
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
|
|
27
|
+
const SESSION_ENVIRONMENT = [
|
|
28
|
+
['codex', 'CODEX_THREAD_ID'],
|
|
29
|
+
['claude', 'CLAUDE_CODE_SESSION_ID']
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
export class QualityRatchetError extends Error {
|
|
33
|
+
constructor(message, code = 'QUALITY_RATCHET') {
|
|
34
|
+
super(message)
|
|
35
|
+
this.name = 'QualityRatchetError'
|
|
36
|
+
this.code = code
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function error(message, code) {
|
|
41
|
+
throw new QualityRatchetError(message, code)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function digest(value) {
|
|
45
|
+
return createHash('sha256').update(value).digest('hex')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function sessionIdentity(env = process.env) {
|
|
49
|
+
for (const [source, variable] of SESSION_ENVIRONMENT) {
|
|
50
|
+
const value = env?.[variable]
|
|
51
|
+
if (typeof value === 'string' && value.trim()) {
|
|
52
|
+
return {
|
|
53
|
+
source,
|
|
54
|
+
key: `${source}-${digest(`${source}\0${value.trim()}`).slice(0, 32)}`
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return { source: 'standalone', key: 'standalone' }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function hookSessionEnvironment(payload, env) {
|
|
62
|
+
const sessionId = typeof payload?.session_id === 'string' ? payload.session_id.trim() : ''
|
|
63
|
+
if (!sessionId) return env
|
|
64
|
+
const codex = typeof payload?.turn_id === 'string' && payload.turn_id.trim()
|
|
65
|
+
return codex
|
|
66
|
+
? { CODEX_THREAD_ID: sessionId }
|
|
67
|
+
: { CLAUDE_CODE_SESSION_ID: sessionId }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function normalizePath(value) {
|
|
71
|
+
const resolved = path.resolve(value)
|
|
72
|
+
return process.platform === 'win32' ? resolved.toLowerCase() : resolved
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isSafeGitRelativePath(value) {
|
|
76
|
+
return typeof value === 'string' && value.length > 0 &&
|
|
77
|
+
value === value.replaceAll('\\', '/') && !value.includes('\0') &&
|
|
78
|
+
!path.posix.isAbsolute(value) && !path.win32.isAbsolute(value) && !/^[A-Za-z]:/.test(value) &&
|
|
79
|
+
value.split('/').every((part) => part !== '' && part !== '.' && part !== '..')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function canonicalGitPaths(value) {
|
|
83
|
+
return Array.isArray(value) && value.every(isSafeGitRelativePath) &&
|
|
84
|
+
value.every((relativePath, index) => index === 0 || value[index - 1] < relativePath)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function validHead(value) {
|
|
88
|
+
return value === null || (typeof value === 'string' && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(value))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function runGit(root, args, { allowFailure = false } = {}) {
|
|
92
|
+
const result = spawnSync('git', ['-C', root, ...args], {
|
|
93
|
+
encoding: 'utf8',
|
|
94
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
95
|
+
})
|
|
96
|
+
if (result.status === 0) return result.stdout || ''
|
|
97
|
+
if (allowFailure) return null
|
|
98
|
+
const detail = result.stderr?.trim() || result.error?.message || `exit ${result.status}`
|
|
99
|
+
error(`Git command failed: git -C "${root}" ${args.join(' ')}\n${detail}`, 'GIT_FAILURE')
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function repositoryContext(cwd, env = process.env) {
|
|
103
|
+
const requested = path.resolve(cwd)
|
|
104
|
+
const rootText = runGit(requested, ['rev-parse', '--show-toplevel']).trim()
|
|
105
|
+
const root = path.resolve(rootText)
|
|
106
|
+
const gitDirText = runGit(root, ['rev-parse', '--git-dir']).trim()
|
|
107
|
+
const gitDir = path.isAbsolute(gitDirText)
|
|
108
|
+
? path.normalize(gitDirText)
|
|
109
|
+
: path.resolve(root, gitDirText)
|
|
110
|
+
const session = sessionIdentity(env)
|
|
111
|
+
return {
|
|
112
|
+
root,
|
|
113
|
+
gitDir,
|
|
114
|
+
session,
|
|
115
|
+
statePath: path.join(gitDir, `${STATE_FILE_NAME}.${session.key}`)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function splitGitPaths(value) {
|
|
120
|
+
return value
|
|
121
|
+
.split('\0')
|
|
122
|
+
.filter(Boolean)
|
|
123
|
+
.map((entry) => entry.replaceAll('\\', '/'))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function trackedPaths(root) {
|
|
127
|
+
return splitGitPaths(runGit(root, ['ls-files', '-z']))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function untrackedPaths(root) {
|
|
131
|
+
return splitGitPaths(runGit(root, ['ls-files', '--others', '--exclude-standard', '-z']))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function gitStatusEntries(root) {
|
|
135
|
+
const tokens = runGit(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])
|
|
136
|
+
.split('\0')
|
|
137
|
+
.filter(Boolean)
|
|
138
|
+
const entries = []
|
|
139
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
140
|
+
const token = tokens[index]
|
|
141
|
+
const status = token.slice(0, 2)
|
|
142
|
+
const relativePath = token.slice(3).replaceAll('\\', '/')
|
|
143
|
+
entries.push({ status, path: relativePath })
|
|
144
|
+
if (status.includes('R') || status.includes('C')) {
|
|
145
|
+
const previousPath = tokens[index + 1]
|
|
146
|
+
if (previousPath !== undefined) {
|
|
147
|
+
entries.push({ status, path: previousPath.replaceAll('\\', '/') })
|
|
148
|
+
index += 1
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return entries.sort((left, right) => {
|
|
153
|
+
const leftKey = `${left.status}\0${left.path}`
|
|
154
|
+
const rightKey = `${right.status}\0${right.path}`
|
|
155
|
+
return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function gitState(root) {
|
|
160
|
+
const status = gitStatusEntries(root)
|
|
161
|
+
return {
|
|
162
|
+
head: runGit(root, ['rev-parse', 'HEAD'], { allowFailure: true })?.trim() || null,
|
|
163
|
+
status,
|
|
164
|
+
dirtyPaths: [...new Set(status.map((entry) => entry.path))].sort()
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function changedHeadPaths(root, beforeHead, afterHead) {
|
|
169
|
+
if (!afterHead || beforeHead === afterHead) return []
|
|
170
|
+
return splitGitPaths(runGit(root, [
|
|
171
|
+
'diff', '--name-only', '--no-renames', '-z', beforeHead || EMPTY_TREE, afterHead
|
|
172
|
+
]))
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function isWithinRoot(root, target) {
|
|
176
|
+
const relative = path.relative(root, target)
|
|
177
|
+
return relative === '' || (relative && !relative.startsWith('..') && !path.isAbsolute(relative))
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function absolutePath(root, relativePath) {
|
|
181
|
+
const target = path.resolve(root, ...relativePath.split('/'))
|
|
182
|
+
if (!isWithinRoot(root, target)) error(`Git returned a path outside the repository: ${relativePath}`, 'GIT_PATH')
|
|
183
|
+
return target
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function isSourcePath(relativePath) {
|
|
187
|
+
const normalized = relativePath.replaceAll('\\', '/')
|
|
188
|
+
if (normalized.split('/').some((part) => ['.git', 'node_modules', 'dist', 'build', 'coverage'].includes(part))) {
|
|
189
|
+
return false
|
|
190
|
+
}
|
|
191
|
+
return SOURCE_EXTENSIONS.has(path.posix.extname(normalized).toLowerCase())
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function countNloc(buffer) {
|
|
195
|
+
return buffer.toString('utf8').split(/\r?\n/).reduce((count, line) => {
|
|
196
|
+
const trimmed = line.trim()
|
|
197
|
+
if (!trimmed) return count
|
|
198
|
+
if (/^(?:\/\/|\/\*|\*\/|\*\s|<!--|-->)/.test(trimmed)) return count
|
|
199
|
+
if (/^#(?:\s|!)/.test(trimmed)) return count
|
|
200
|
+
return count + 1
|
|
201
|
+
}, 0)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function missingRecord(relativePath, source) {
|
|
205
|
+
return {
|
|
206
|
+
path: relativePath,
|
|
207
|
+
kind: 'missing',
|
|
208
|
+
hash: null,
|
|
209
|
+
bytes: 0,
|
|
210
|
+
source,
|
|
211
|
+
nloc: 0
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function fileRecord(root, relativePath) {
|
|
216
|
+
const source = isSourcePath(relativePath)
|
|
217
|
+
const target = absolutePath(root, relativePath)
|
|
218
|
+
let stats
|
|
219
|
+
try {
|
|
220
|
+
stats = fs.lstatSync(target)
|
|
221
|
+
} catch (cause) {
|
|
222
|
+
if (cause.code === 'ENOENT') return missingRecord(relativePath, source)
|
|
223
|
+
error(`Cannot inspect ${relativePath}: ${cause.message}`, 'SNAPSHOT_FAILURE')
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (stats.isSymbolicLink()) {
|
|
227
|
+
const link = fs.readlinkSync(target)
|
|
228
|
+
return {
|
|
229
|
+
path: relativePath,
|
|
230
|
+
kind: 'symlink',
|
|
231
|
+
hash: digest(link),
|
|
232
|
+
bytes: Buffer.byteLength(link),
|
|
233
|
+
source,
|
|
234
|
+
nloc: 0
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (!stats.isFile()) {
|
|
239
|
+
return {
|
|
240
|
+
path: relativePath,
|
|
241
|
+
kind: stats.isDirectory() ? 'directory' : 'other',
|
|
242
|
+
hash: null,
|
|
243
|
+
bytes: 0,
|
|
244
|
+
source,
|
|
245
|
+
nloc: 0
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
let content
|
|
250
|
+
try {
|
|
251
|
+
content = fs.readFileSync(target)
|
|
252
|
+
} catch (cause) {
|
|
253
|
+
error(`Cannot read ${relativePath}: ${cause.message}`, 'SNAPSHOT_FAILURE')
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
path: relativePath,
|
|
257
|
+
kind: 'file',
|
|
258
|
+
hash: digest(content),
|
|
259
|
+
bytes: content.byteLength,
|
|
260
|
+
source,
|
|
261
|
+
nloc: source ? countNloc(content) : 0
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function fileFingerprintRecord(record) {
|
|
266
|
+
return [record.path, record.kind, record.hash, record.bytes, record.source, record.nloc]
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function entryFingerprint(files, dirtyPaths, head) {
|
|
270
|
+
return digest(JSON.stringify({
|
|
271
|
+
files: files.map(fileFingerprintRecord),
|
|
272
|
+
dirtyPaths,
|
|
273
|
+
head
|
|
274
|
+
}))
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function snapshot(root) {
|
|
278
|
+
const git = gitState(root)
|
|
279
|
+
const paths = [...new Set([...trackedPaths(root), ...untrackedPaths(root)])].sort()
|
|
280
|
+
const files = paths.map((relativePath) => fileRecord(root, relativePath))
|
|
281
|
+
return {
|
|
282
|
+
files,
|
|
283
|
+
fingerprint: entryFingerprint(files, git.dirtyPaths, git.head),
|
|
284
|
+
sourceNloc: files.reduce((total, file) => total + (file.source ? file.nloc : 0), 0),
|
|
285
|
+
head: git.head,
|
|
286
|
+
dirtyPaths: git.dirtyPaths
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function mergeCandidateFiles(baselineFiles, inspected) {
|
|
291
|
+
const files = baselineFiles.map((file) => inspected.get(file.path) || file)
|
|
292
|
+
const knownPaths = new Set(files.map((file) => file.path))
|
|
293
|
+
for (const file of inspected.values()) {
|
|
294
|
+
if (!knownPaths.has(file.path) && file.kind !== 'missing') files.push(file)
|
|
295
|
+
}
|
|
296
|
+
return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function candidateSnapshot(root, entry, { includeFiles = true } = {}) {
|
|
300
|
+
const git = gitState(root)
|
|
301
|
+
const headPaths = changedHeadPaths(root, entry.head, git.head)
|
|
302
|
+
const relevantPaths = [...new Set([
|
|
303
|
+
...entry.dirtyPaths,
|
|
304
|
+
...git.dirtyPaths,
|
|
305
|
+
...headPaths
|
|
306
|
+
])].sort()
|
|
307
|
+
const inspected = new Map(relevantPaths.map((relativePath) => [relativePath, fileRecord(root, relativePath)]))
|
|
308
|
+
const files = includeFiles ? mergeCandidateFiles(entry.files, inspected) : null
|
|
309
|
+
return {
|
|
310
|
+
files,
|
|
311
|
+
fingerprint: digest(JSON.stringify({
|
|
312
|
+
head: git.head,
|
|
313
|
+
status: git.status,
|
|
314
|
+
files: relevantPaths.map((relativePath) => fileFingerprintRecord(inspected.get(relativePath)))
|
|
315
|
+
})),
|
|
316
|
+
head: git.head
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function commandDetected(command, spawn = spawnSync) {
|
|
321
|
+
const lookup = process.platform === 'win32' ? 'where.exe' : 'which'
|
|
322
|
+
try {
|
|
323
|
+
const result = spawn(lookup, [command], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
|
324
|
+
return result.status === 0
|
|
325
|
+
} catch {
|
|
326
|
+
return false
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function unavailableAnalyzer(reason) {
|
|
331
|
+
return { status: 'unavailable', available: false, integrated: false, reason }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function normalizeAnalyzer(value, name) {
|
|
335
|
+
if (!value || typeof value !== 'object') {
|
|
336
|
+
return unavailableAnalyzer(`${name} capability detection returned no result`)
|
|
337
|
+
}
|
|
338
|
+
const status = typeof value.status === 'string' ? value.status : 'unavailable'
|
|
339
|
+
return {
|
|
340
|
+
status,
|
|
341
|
+
available: value.available === true,
|
|
342
|
+
integrated: value.integrated === true,
|
|
343
|
+
reason: typeof value.reason === 'string' ? value.reason : 'No analyzer result was provided.'
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function detectOptionalAnalyzers({ spawn = spawnSync } = {}) {
|
|
348
|
+
return Object.fromEntries(OPTIONAL_ANALYZERS.map((name) => [
|
|
349
|
+
name,
|
|
350
|
+
commandDetected(name, spawn)
|
|
351
|
+
? {
|
|
352
|
+
status: 'detected-not-integrated',
|
|
353
|
+
available: true,
|
|
354
|
+
integrated: false,
|
|
355
|
+
reason: `${name} was detected but is not integrated; core Node evidence is used.`
|
|
356
|
+
}
|
|
357
|
+
: unavailableAnalyzer(`${name} is not installed; core Node evidence is used.`)
|
|
358
|
+
]))
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function safeAnalyzerDetection(detector) {
|
|
362
|
+
try {
|
|
363
|
+
const detected = detector()
|
|
364
|
+
return Object.fromEntries(OPTIONAL_ANALYZERS.map((name) => [
|
|
365
|
+
name,
|
|
366
|
+
normalizeAnalyzer(detected?.[name], name)
|
|
367
|
+
]))
|
|
368
|
+
} catch (cause) {
|
|
369
|
+
return Object.fromEntries(OPTIONAL_ANALYZERS.map((name) => [
|
|
370
|
+
name,
|
|
371
|
+
unavailableAnalyzer(`Capability detection failed: ${cause.message}`)
|
|
372
|
+
]))
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function packageDependencies(root) {
|
|
377
|
+
const packagePath = path.join(root, 'package.json')
|
|
378
|
+
if (!fs.existsSync(packagePath)) {
|
|
379
|
+
return { status: 'unavailable', reason: 'package.json is absent.', dependencies: {} }
|
|
380
|
+
}
|
|
381
|
+
let manifest
|
|
382
|
+
try {
|
|
383
|
+
manifest = JSON.parse(fs.readFileSync(packagePath, 'utf8'))
|
|
384
|
+
} catch (cause) {
|
|
385
|
+
return { status: 'unavailable', reason: `package.json could not be parsed: ${cause.message}`, dependencies: {} }
|
|
386
|
+
}
|
|
387
|
+
const dependencies = {}
|
|
388
|
+
for (const section of DEPENDENCY_SECTIONS) {
|
|
389
|
+
const values = manifest?.[section]
|
|
390
|
+
if (!values || typeof values !== 'object' || Array.isArray(values)) continue
|
|
391
|
+
for (const name of Object.keys(values).sort()) {
|
|
392
|
+
dependencies[`${section}:${name}`] = String(values[name])
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return { status: 'available', reason: 'Root package.json dependency sections were read.', dependencies }
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function dependencyDiff(before, after) {
|
|
399
|
+
if (before.status !== 'available' || after.status !== 'available') {
|
|
400
|
+
return {
|
|
401
|
+
status: 'unavailable',
|
|
402
|
+
reason: `Dependency comparison unavailable: before=${before.reason} after=${after.reason}`,
|
|
403
|
+
added: [],
|
|
404
|
+
removed: [],
|
|
405
|
+
updated: []
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
const beforeValues = before.dependencies
|
|
409
|
+
const afterValues = after.dependencies
|
|
410
|
+
const added = []
|
|
411
|
+
const removed = []
|
|
412
|
+
const updated = []
|
|
413
|
+
for (const key of [...new Set([...Object.keys(beforeValues), ...Object.keys(afterValues)])].sort()) {
|
|
414
|
+
const [section, ...nameParts] = key.split(':')
|
|
415
|
+
const name = nameParts.join(':')
|
|
416
|
+
if (!(key in beforeValues)) {
|
|
417
|
+
added.push({ section, name, version: afterValues[key] })
|
|
418
|
+
} else if (!(key in afterValues)) {
|
|
419
|
+
removed.push({ section, name, version: beforeValues[key] })
|
|
420
|
+
} else if (beforeValues[key] !== afterValues[key]) {
|
|
421
|
+
updated.push({ section, name, before: beforeValues[key], after: afterValues[key] })
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return {
|
|
425
|
+
status: 'available',
|
|
426
|
+
reason: 'Root package.json dependency sections were compared.',
|
|
427
|
+
added,
|
|
428
|
+
removed,
|
|
429
|
+
updated
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function fileMap(files) {
|
|
434
|
+
return new Map(files.map((file) => [file.path, file]))
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function changedPaths(beforeFiles, afterFiles) {
|
|
438
|
+
const before = fileMap(beforeFiles)
|
|
439
|
+
const after = fileMap(afterFiles)
|
|
440
|
+
const added = []
|
|
441
|
+
const changed = []
|
|
442
|
+
const deleted = []
|
|
443
|
+
for (const relativePath of [...new Set([...before.keys(), ...after.keys()])].sort()) {
|
|
444
|
+
const previous = before.get(relativePath)
|
|
445
|
+
const current = after.get(relativePath)
|
|
446
|
+
if (!previous) {
|
|
447
|
+
if (current.source) added.push(relativePath)
|
|
448
|
+
} else if (!current) {
|
|
449
|
+
if (previous.source) deleted.push(relativePath)
|
|
450
|
+
} else if (current.kind === 'missing' && previous.kind !== 'missing') {
|
|
451
|
+
if (previous.source) deleted.push(relativePath)
|
|
452
|
+
} else if (JSON.stringify(fileFingerprintRecord(previous)) !== JSON.stringify(fileFingerprintRecord(current))) {
|
|
453
|
+
if (previous.source || current.source) changed.push(relativePath)
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return { added, changed, deleted }
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function touchedLegacy(beforeFiles, afterFiles, touchedPaths) {
|
|
460
|
+
const before = fileMap(beforeFiles)
|
|
461
|
+
const after = fileMap(afterFiles)
|
|
462
|
+
const beforeFilesTouched = touchedPaths.filter((relativePath) => before.get(relativePath)?.source)
|
|
463
|
+
const afterFilesTouched = touchedPaths.filter((relativePath) => before.get(relativePath)?.source &&
|
|
464
|
+
after.get(relativePath)?.kind !== 'missing' && after.get(relativePath)?.source)
|
|
465
|
+
return {
|
|
466
|
+
before: {
|
|
467
|
+
status: beforeFilesTouched.length ? 'touched' : 'none',
|
|
468
|
+
files: beforeFilesTouched
|
|
469
|
+
},
|
|
470
|
+
after: {
|
|
471
|
+
status: afterFilesTouched.length ? 'touched' : 'none',
|
|
472
|
+
files: afterFilesTouched
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function touchedNloc(beforeFiles, afterFiles, touchedPaths) {
|
|
478
|
+
const before = fileMap(beforeFiles)
|
|
479
|
+
const after = fileMap(afterFiles)
|
|
480
|
+
const beforeNloc = touchedPaths.reduce((total, relativePath) => total + (before.get(relativePath)?.nloc || 0), 0)
|
|
481
|
+
const afterNloc = touchedPaths.reduce((total, relativePath) => total + (after.get(relativePath)?.nloc || 0), 0)
|
|
482
|
+
return { before: beforeNloc, after: afterNloc, delta: afterNloc - beforeNloc }
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function evidenceFor(state, candidate, dependencies, analyzers) {
|
|
486
|
+
const sourceFiles = changedPaths(state.entry.files, candidate.files)
|
|
487
|
+
const touchedPaths = [...new Set([
|
|
488
|
+
...sourceFiles.added,
|
|
489
|
+
...sourceFiles.changed,
|
|
490
|
+
...sourceFiles.deleted
|
|
491
|
+
])].sort()
|
|
492
|
+
return {
|
|
493
|
+
schema: STATE_SCHEMA,
|
|
494
|
+
status: 'ok',
|
|
495
|
+
baselineFingerprint: state.entry.fingerprint,
|
|
496
|
+
candidateFingerprint: candidate.fingerprint,
|
|
497
|
+
sourceFiles,
|
|
498
|
+
sourceNloc: touchedNloc(state.entry.files, candidate.files, touchedPaths),
|
|
499
|
+
touchedLegacy: touchedLegacy(state.entry.files, candidate.files, touchedPaths),
|
|
500
|
+
packageDependencies: dependencyDiff(state.entry.packageDependencies, dependencies),
|
|
501
|
+
optionalAnalyzers: {
|
|
502
|
+
baseline: state.entry.optionalAnalyzers,
|
|
503
|
+
candidate: analyzers
|
|
504
|
+
},
|
|
505
|
+
entryHead: state.entry.head,
|
|
506
|
+
candidateHead: candidate.head
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function readState(context) {
|
|
511
|
+
if (!fs.existsSync(context.statePath)) return null
|
|
512
|
+
let state
|
|
513
|
+
try {
|
|
514
|
+
state = JSON.parse(fs.readFileSync(context.statePath, 'utf8'))
|
|
515
|
+
} catch (cause) {
|
|
516
|
+
error(`Quality ratchet state is corrupt at ${context.statePath}: ${cause.message}. Run clear, then begin again.`, 'STATE_CORRUPT')
|
|
517
|
+
}
|
|
518
|
+
const filesValid = Array.isArray(state?.entry?.files) && state.entry.files.every((file) =>
|
|
519
|
+
file && typeof file.path === 'string' && typeof file.source === 'boolean' && Number.isInteger(file.nloc))
|
|
520
|
+
const dirtyPathsValid = canonicalGitPaths(state?.entry?.dirtyPaths)
|
|
521
|
+
const headValid = validHead(state?.entry?.head)
|
|
522
|
+
const sessionValid = state?.session && typeof state.session.source === 'string' &&
|
|
523
|
+
typeof state.session.key === 'string' && state.session.source === context.session.source &&
|
|
524
|
+
state.session.key === context.session.key
|
|
525
|
+
const pathsValid = typeof state?.repositoryRoot === 'string' && typeof state?.gitDir === 'string'
|
|
526
|
+
const fingerprintValid = filesValid && dirtyPathsValid && headValid && state.entry.fingerprint ===
|
|
527
|
+
entryFingerprint(state.entry.files, state.entry.dirtyPaths, state.entry.head)
|
|
528
|
+
if (!state || state.schema !== STATE_SCHEMA || state.state !== 'active' || !pathsValid ||
|
|
529
|
+
normalizePath(state.repositoryRoot) !== normalizePath(context.root) ||
|
|
530
|
+
normalizePath(state.gitDir) !== normalizePath(context.gitDir) ||
|
|
531
|
+
!sessionValid ||
|
|
532
|
+
!state.entry || typeof state.entry.fingerprint !== 'string' || !filesValid || !dirtyPathsValid || !headValid ||
|
|
533
|
+
!fingerprintValid ||
|
|
534
|
+
!state.entry.packageDependencies || typeof state.entry.packageDependencies.status !== 'string' ||
|
|
535
|
+
!state.entry.optionalAnalyzers || typeof state.entry.optionalAnalyzers !== 'object') {
|
|
536
|
+
error(`Quality ratchet state is invalid or belongs to another session or worktree at ${context.statePath}. Run clear, then begin again.`, 'STATE_INVALID')
|
|
537
|
+
}
|
|
538
|
+
if (state.lastCheck !== null &&
|
|
539
|
+
(!state.lastCheck || typeof state.lastCheck.candidateFingerprint !== 'string')) {
|
|
540
|
+
error(`Quality ratchet state has an invalid last check at ${context.statePath}. Run clear, then begin again.`, 'STATE_INVALID')
|
|
541
|
+
}
|
|
542
|
+
return state
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function writeState(context, state) {
|
|
546
|
+
fs.mkdirSync(context.gitDir, { recursive: true })
|
|
547
|
+
const temporary = path.join(context.gitDir, `${STATE_FILE_NAME}.${randomUUID()}.tmp`)
|
|
548
|
+
try {
|
|
549
|
+
fs.writeFileSync(temporary, JSON.stringify(state, null, 2) + '\n')
|
|
550
|
+
fs.renameSync(temporary, context.statePath)
|
|
551
|
+
} finally {
|
|
552
|
+
if (fs.existsSync(temporary)) fs.rmSync(temporary, { force: true })
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function baselineState(context, candidate, dependencies, analyzers) {
|
|
557
|
+
return {
|
|
558
|
+
schema: STATE_SCHEMA,
|
|
559
|
+
state: 'active',
|
|
560
|
+
repositoryRoot: path.resolve(context.root),
|
|
561
|
+
gitDir: path.resolve(context.gitDir),
|
|
562
|
+
session: context.session,
|
|
563
|
+
entry: {
|
|
564
|
+
fingerprint: candidate.fingerprint,
|
|
565
|
+
head: candidate.head,
|
|
566
|
+
dirtyPaths: candidate.dirtyPaths,
|
|
567
|
+
sourceNloc: candidate.sourceNloc,
|
|
568
|
+
fileCount: candidate.files.length,
|
|
569
|
+
files: candidate.files,
|
|
570
|
+
packageDependencies: dependencies,
|
|
571
|
+
optionalAnalyzers: analyzers
|
|
572
|
+
},
|
|
573
|
+
lastCheck: null
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
export function begin(cwd = process.cwd(), { detect = detectOptionalAnalyzers, env = process.env } = {}) {
|
|
578
|
+
const context = repositoryContext(cwd, env)
|
|
579
|
+
if (fs.existsSync(context.statePath)) {
|
|
580
|
+
readState(context)
|
|
581
|
+
error(`An active quality ratchet baseline already exists for this session and worktree at ${context.statePath}. Run clear before beginning a new delivery.`, 'BASELINE_ACTIVE')
|
|
582
|
+
}
|
|
583
|
+
const candidate = snapshot(context.root)
|
|
584
|
+
const dependencies = packageDependencies(context.root)
|
|
585
|
+
const analyzers = safeAnalyzerDetection(detect)
|
|
586
|
+
const state = baselineState(context, candidate, dependencies, analyzers)
|
|
587
|
+
writeState(context, state)
|
|
588
|
+
return {
|
|
589
|
+
statePath: context.statePath,
|
|
590
|
+
fingerprint: candidate.fingerprint,
|
|
591
|
+
fileCount: candidate.files.length,
|
|
592
|
+
sourceNloc: candidate.sourceNloc
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, env = process.env } = {}) {
|
|
597
|
+
const context = repositoryContext(cwd, env)
|
|
598
|
+
const state = readState(context)
|
|
599
|
+
if (!state) error(`No active quality ratchet baseline exists for ${context.root}. Run begin before the first mutation.`, 'BASELINE_MISSING')
|
|
600
|
+
const candidate = candidateSnapshot(context.root, state.entry)
|
|
601
|
+
const dependencies = packageDependencies(context.root)
|
|
602
|
+
const analyzers = safeAnalyzerDetection(detect)
|
|
603
|
+
const evidence = evidenceFor(state, candidate, dependencies, analyzers)
|
|
604
|
+
state.lastCheck = {
|
|
605
|
+
candidateFingerprint: candidate.fingerprint,
|
|
606
|
+
evidence
|
|
607
|
+
}
|
|
608
|
+
writeState(context, state)
|
|
609
|
+
return evidence
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
export function clear(cwd = process.cwd(), { env = process.env } = {}) {
|
|
613
|
+
const context = repositoryContext(cwd, env)
|
|
614
|
+
if (fs.existsSync(context.statePath)) fs.rmSync(context.statePath, { force: true })
|
|
615
|
+
return { statePath: context.statePath, cleared: true }
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function allowResult() {
|
|
619
|
+
return {}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function blockResult(reason) {
|
|
623
|
+
return { decision: 'block', reason }
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
function lifecycleCommand(command) {
|
|
627
|
+
return `"${process.execPath}" "${fileURLToPath(import.meta.url)}" ${command}`
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
export function hook(cwd = process.cwd(), payload = {}, { env = process.env } = {}) {
|
|
631
|
+
let context
|
|
632
|
+
try {
|
|
633
|
+
context = repositoryContext(cwd, hookSessionEnvironment(payload, env))
|
|
634
|
+
} catch {
|
|
635
|
+
return allowResult()
|
|
636
|
+
}
|
|
637
|
+
if (!fs.existsSync(context.statePath)) return allowResult()
|
|
638
|
+
|
|
639
|
+
try {
|
|
640
|
+
const state = readState(context)
|
|
641
|
+
if (!state) return allowResult()
|
|
642
|
+
let candidate
|
|
643
|
+
try {
|
|
644
|
+
candidate = candidateSnapshot(context.root, state.entry, { includeFiles: false })
|
|
645
|
+
} catch (cause) {
|
|
646
|
+
const reason = `Quality ratchet could not inspect the candidate: ${cause.message}. Run the quality-ratchet check and retry.`
|
|
647
|
+
return blockResult(reason)
|
|
648
|
+
}
|
|
649
|
+
const fresh = state.lastCheck?.candidateFingerprint === candidate.fingerprint
|
|
650
|
+
if (fresh) {
|
|
651
|
+
fs.rmSync(context.statePath, { force: true })
|
|
652
|
+
return allowResult()
|
|
653
|
+
}
|
|
654
|
+
const reason = state.lastCheck
|
|
655
|
+
? `Quality ratchet check is stale for the current candidate. Run \`${lifecycleCommand('check')}\` before stopping.`
|
|
656
|
+
: `Quality ratchet has an active baseline but no check for this candidate. Run \`${lifecycleCommand('check')}\` before stopping.`
|
|
657
|
+
return blockResult(reason)
|
|
658
|
+
} catch (cause) {
|
|
659
|
+
const reason = cause instanceof QualityRatchetError
|
|
660
|
+
? cause.message
|
|
661
|
+
: `Quality ratchet lifecycle error: ${cause.message}`
|
|
662
|
+
return blockResult(reason)
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function humanList(values) {
|
|
667
|
+
return values.length ? values.join(', ') : 'none'
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
export function formatEvidence(evidence) {
|
|
671
|
+
const lines = [
|
|
672
|
+
'Agent OS quality-ratchet evidence',
|
|
673
|
+
`Source files: +${evidence.sourceFiles.added.length} ~${evidence.sourceFiles.changed.length} -${evidence.sourceFiles.deleted.length}`,
|
|
674
|
+
` added: ${humanList(evidence.sourceFiles.added)}`,
|
|
675
|
+
` changed: ${humanList(evidence.sourceFiles.changed)}`,
|
|
676
|
+
` deleted: ${humanList(evidence.sourceFiles.deleted)}`,
|
|
677
|
+
`Source NLOC (touched): ${evidence.sourceNloc.before} -> ${evidence.sourceNloc.after} (delta ${evidence.sourceNloc.delta >= 0 ? '+' : ''}${evidence.sourceNloc.delta})`,
|
|
678
|
+
`Touched legacy before: ${evidence.touchedLegacy.before.status} (${humanList(evidence.touchedLegacy.before.files)})`,
|
|
679
|
+
`Touched legacy after: ${evidence.touchedLegacy.after.status} (${humanList(evidence.touchedLegacy.after.files)})`,
|
|
680
|
+
`Package dependencies: +${evidence.packageDependencies.added.length} -${evidence.packageDependencies.removed.length} ~${evidence.packageDependencies.updated.length} (${evidence.packageDependencies.status})`,
|
|
681
|
+
...OPTIONAL_ANALYZERS.map((name) => `Optional analyzer ${name}: ${evidence.optionalAnalyzers.candidate[name].status} — ${evidence.optionalAnalyzers.candidate[name].reason}`),
|
|
682
|
+
`Candidate fingerprint: ${evidence.candidateFingerprint}`,
|
|
683
|
+
`Machine-readable evidence: ${JSON.stringify(evidence)}`
|
|
684
|
+
]
|
|
685
|
+
return lines.join('\n')
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function parseArguments(args) {
|
|
689
|
+
const result = { command: args[0] || 'check', root: process.cwd(), json: false }
|
|
690
|
+
let index = 1
|
|
691
|
+
while (index < args.length) {
|
|
692
|
+
const argument = args[index]
|
|
693
|
+
if (argument === '--json') {
|
|
694
|
+
result.json = true
|
|
695
|
+
} else if (argument === '--root') {
|
|
696
|
+
const root = args[index + 1]
|
|
697
|
+
if (!root || root.startsWith('-')) error('--root requires a path.', 'ARGUMENTS')
|
|
698
|
+
result.root = root
|
|
699
|
+
index += 1
|
|
700
|
+
} else if (argument.startsWith('--root=')) {
|
|
701
|
+
result.root = argument.slice('--root='.length)
|
|
702
|
+
if (!result.root) error('--root requires a path.', 'ARGUMENTS')
|
|
703
|
+
} else if (argument === QUALITY_HOOK_MARKER) {
|
|
704
|
+
// The marker makes direct-installed commands identifiable and is ignored by the engine.
|
|
705
|
+
} else {
|
|
706
|
+
error(`Unknown option "${argument}".`, 'ARGUMENTS')
|
|
707
|
+
}
|
|
708
|
+
index += 1
|
|
709
|
+
}
|
|
710
|
+
if (!['begin', 'check', 'clear', 'hook'].includes(result.command)) {
|
|
711
|
+
error(`Unknown command "${result.command}". Use begin, check, clear, or hook.`, 'ARGUMENTS')
|
|
712
|
+
}
|
|
713
|
+
return result
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function readHookPayload() {
|
|
717
|
+
try {
|
|
718
|
+
const input = fs.readFileSync(0, 'utf8').trim()
|
|
719
|
+
return input ? JSON.parse(input) : {}
|
|
720
|
+
} catch {
|
|
721
|
+
return {}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function main() {
|
|
726
|
+
try {
|
|
727
|
+
const options = parseArguments(process.argv.slice(2))
|
|
728
|
+
if (options.command === 'begin') {
|
|
729
|
+
const result = begin(options.root)
|
|
730
|
+
console.log(`Quality ratchet baseline started for ${result.fileCount} files (${result.fingerprint}).`)
|
|
731
|
+
return
|
|
732
|
+
}
|
|
733
|
+
if (options.command === 'check') {
|
|
734
|
+
const evidence = check(options.root)
|
|
735
|
+
console.log(options.json ? JSON.stringify(evidence) : formatEvidence(evidence))
|
|
736
|
+
return
|
|
737
|
+
}
|
|
738
|
+
if (options.command === 'clear') {
|
|
739
|
+
const result = clear(options.root)
|
|
740
|
+
console.log(`Quality ratchet baseline cleared at ${result.statePath}.`)
|
|
741
|
+
return
|
|
742
|
+
}
|
|
743
|
+
const payload = readHookPayload()
|
|
744
|
+
const result = hook(payload.cwd || options.root, payload)
|
|
745
|
+
console.log(JSON.stringify(result))
|
|
746
|
+
} catch (cause) {
|
|
747
|
+
console.error(`quality-ratchet: ${cause.message}`)
|
|
748
|
+
process.exitCode = cause instanceof QualityRatchetError && cause.code === 'ARGUMENTS' ? 2 : 1
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main()
|