@sockulags/agent-os 0.13.1 → 0.14.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sockulags/agent-os",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "description": "A lightweight personal agent operating system with an npx installer for Claude Code and Codex.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,7 +16,7 @@
16
16
  "node": ">=18.18"
17
17
  },
18
18
  "scripts": {
19
- "test": "node --test cli/index.test.mjs skills/quality-ratchet/scripts/quality-delta.test.mjs",
19
+ "test": "node --test cli/index.test.mjs skills/quality-ratchet/scripts/quality-delta.test.mjs skills/quality-ratchet/scripts/project-controls.test.mjs",
20
20
  "test:evals": "node scripts/test-eval-agent-behavior.mjs",
21
21
  "validate": "node scripts/validate-agent-os.mjs",
22
22
  "verify:release": "node scripts/verify-release.mjs"
@@ -6,7 +6,7 @@ description: Keeps implementation quality from regressing by comparing a candida
6
6
  # Quality ratchet
7
7
 
8
8
  Keep the smallest set of concepts and machinery needed for the current change. The ratchet is an
9
- evidence layer, not a score, gate, or replacement for semantic review.
9
+ evidence layer, not a score or replacement for semantic review. Explicit project rules may gate delivery.
10
10
 
11
11
  Before choosing the implementation, find the nearest existing behavior, contract, and tests. Reuse
12
12
  or extend their owner before adding a parallel implementation. For TypeScript, React, or Java
@@ -41,22 +41,28 @@ aggregate score and no threshold gate. Missing Lizard or jscpd is reported as un
41
41
  than clean; the core Node evidence remains usable. Their parsing integration is an explicit
42
42
  follow-up, not an install-time prerequisite.
43
43
 
44
- Use existing project checks for enforceable rules and report structural signals as advisory. A
44
+ Use existing project checks for enforceable rules and report structural signals as advisory.
45
+ When configuring external checks, read [references/project-controls.md](references/project-controls.md).
46
+ The runner executes project commands from `.agent-os/quality.json`; required failures block delivery.
47
+ Do not rerun unchanged failing checks in a loop. Fix the failure or report the blocker.
48
+ Policy changes require an explicit acknowledgement with the already-authorized reason; do not ask
49
+ for approval again when the task authorizes the change or clear the baseline to hide it. A
45
50
  fresh `check` proves evidence freshness, not code quality, passing tests, or completed review. The
46
51
  runner currently inspects dependencies only in the root `package.json`; do not infer Java or
47
52
  workspace-package coverage from it. Run relevant configured analyzers outside the model, pass short
48
53
  actionable deltas to review, and reuse results only while their inputs, configuration, and tool
49
54
  versions remain unchanged. Do not install analyzers or invent thresholds for an ordinary task.
50
55
 
51
- The Stop hook blocks only an active lifecycle violation: a corrupt baseline, or a missing/stale check
52
- for the current candidate. State is bound to the current Git worktree and host session: Claude uses
56
+ The Stop hook blocks an active lifecycle violation (a corrupt baseline or missing/stale check),
57
+ unacknowledged control-policy changes, or failed explicit project requirements. It checks recorded
58
+ results and their inputs without rerunning project commands. State is bound to the current Git worktree and host session: Claude uses
53
59
  `CLAUDE_CODE_SESSION_ID`, Codex uses `CODEX_THREAD_ID`, and standalone/manual use has a deterministic
54
60
  fallback. `begin`, `check`, and `clear` use those command environments, preferring Codex when both
55
61
  IDs exist. Stop uses payload
56
62
  `session_id`, treating a non-empty `turn_id` as Codex and otherwise as Claude; without `session_id`,
57
63
  it retains the command environment for direct/manual use. A worktree without an active baseline for
58
64
  the current session is a cheap no-op. A re-entered Stop hook remains blocked until that same session
59
- records a fresh `check`; the `stop_hook_active` payload does not bypass the lifecycle requirement. A fresh Stop clears only the
65
+ records a fresh passing `check`; the `stop_hook_active` payload does not bypass the lifecycle requirement. A fresh passing Stop clears only the
60
66
  current session state. Run `clear` deliberately from the same host session when abandoning an
61
67
  implementation attempt; uninstall is not currently a command.
62
68
 
@@ -0,0 +1,135 @@
1
+ # Project controls
2
+
3
+ Use the installed `quality-ratchet/scripts/quality-delta.mjs` runner for `begin`, `check`, and
4
+ `hook`. Project controls are optional. They use existing executable tools; Agent OS neither installs
5
+ analyzers nor infers architecture from file size. The same commands work manually and in CI.
6
+
7
+ ## Configuration
8
+
9
+ Create `.agent-os/quality.json` in the target Git repository. Example for a TypeScript project that
10
+ already has dependency-cruiser installed (verify its executable path in your installed version):
11
+
12
+ ```json
13
+ {
14
+ "schema": 1,
15
+ "protectedFiles": [".dependency-cruiser.cjs"],
16
+ "checks": [
17
+ {
18
+ "id": "architecture",
19
+ "command": ["node", "node_modules/dependency-cruiser/bin/dependency-cruise.mjs", "--config", ".dependency-cruiser.cjs", "src/**/*.ts"],
20
+ "required": true,
21
+ "timeoutMs": 60000
22
+ }
23
+ ],
24
+ "blockSignals": []
25
+ }
26
+ ```
27
+
28
+ The project's dependency-cruiser configuration owns its architecture, for example:
29
+
30
+ ```js
31
+ module.exports = {
32
+ forbidden: [{
33
+ name: 'domain-does-not-import-ui',
34
+ severity: 'error',
35
+ from: { path: '^src/domain/' },
36
+ to: { path: '^src/ui/' }
37
+ }],
38
+ options: { doNotFollow: { path: 'node_modules' } }
39
+ }
40
+ ```
41
+
42
+ For Java, keep architecture rules in the project's existing ArchUnit tests and run the project's
43
+ Maven/Gradle verification command. For example, a Maven project with a configured `ArchitectureTest`
44
+ can use `"command": ["./mvnw", "-Dtest=ArchitectureTest", "test"]`. Protect the rule test and build
45
+ configuration through `protectedFiles`. Do not introduce a second homegrown dependency parser.
46
+ Use the actual project wrapper and supported command for its operating system.
47
+
48
+ Commands are argument arrays, run at the Git root with inherited environment and no implicit shell.
49
+ Use an explicit interpreter for scripts that need one; on Windows prefer Node entrypoints or the
50
+ project's explicitly selected shell for `.cmd` wrappers. The repository configuration is trusted
51
+ executable project code. Inspect it before running it, as with project build scripts.
52
+
53
+ All checks default to advisory and run on every `check`. `required: true` blocks delivery unless the
54
+ command exits zero. Missing tools, timeout, signal termination, and output overflow are distinct
55
+ non-passing results. The timeout defaults to 60 seconds, at most 600 seconds per command. Commands
56
+ must be bounded and clean up their child processes; the runner does not manage process groups.
57
+ Output is capped at 1 MiB while running and 16,000 characters in evidence. No command runs in Stop.
58
+
59
+ Required checks apply to the candidate, including existing violations. Introduce rules as advisory
60
+ when existing debt prevents passing; use the analyzer's own approved baseline support if needed.
61
+ Agent OS does not suppress pre-existing analyzer failures or equate tool success with sound design.
62
+
63
+ ## New exceptions and policy changes
64
+
65
+ The runner reports new source lines matching `type-escape` (common `: any`/`as any` annotations and casts, TypeScript suppression comments),
66
+ `lint-disable` (ESLint suppression and Java `@SuppressWarnings`), and `test-skip` (common test skips,
67
+ focused tests, and Java `@Disabled`). It subtracts existing occurrences per file, ignoring simple
68
+ line movement. These lexical signals can match comments or strings and can reappear on rename;
69
+ they do not establish a semantic defect. Review them or delegate exact rules to the project's linter.
70
+ Only rules explicitly listed in `blockSignals` block delivery. Raw LOC and structural counts never do.
71
+
72
+ The policy itself and repository-relative `protectedFiles` are fingerprinted at entry. Include the
73
+ lint, type, test, architecture, and CI configurations whose weakening should require attention.
74
+ A protected missing file is represented as absent; later creation or deletion changes the signature.
75
+ Changes are held before project commands run until restored or explicitly acknowledged:
76
+
77
+ ```sh
78
+ node "$QUALITY_RUNNER" check --accept-policy-change "Task authorizes replacing the obsolete architecture rule"
79
+ ```
80
+
81
+ Reuse existing task authorization; ask only if the change exceeds it. The reason remains in evidence.
82
+ `clear` cannot silently erase an unacknowledged policy change. Acknowledgement does not turn a failed
83
+ check into a pass. Local configuration and Git metadata remain editable by the user and agent;
84
+ this is transparent workflow control, not an authorization boundary. Enforce protected rules in CI.
85
+
86
+ ## Conservative reuse
87
+
88
+ No cache is enabled by default. Only an explicitly static check can opt in:
89
+
90
+ ```json
91
+ "cache": { "kind": "static", "toolInputs": ["node_modules"] }
92
+ ```
93
+
94
+ Declare every ignored file/directory that can affect the static tool, including its installed
95
+ transitive dependencies and compiler plugins. This requires regular files/directories inside the
96
+ repository; symlinked inputs and repositories with symlinks/submodules cannot use static caching.
97
+ `.git`, absolute paths, and traversal are disallowed. Missing declared inputs are unavailable, not
98
+ clean. Use uncached checks when tool installations cannot be described this way.
99
+
100
+ The key covers the whole tracked and nonignored repository, declared tool inputs and modes, the
101
+ resolved executable bytes, command, policy and protected files, runner code, Node runtime, OS and
102
+ architecture, and a digest of the complete inherited environment. Environment values are not stored.
103
+ Full repository scope deliberately avoids unsafe guesses about affected tests. Only a passed result
104
+ from this session's previous check can be reused. Failures and dynamic checks always run again.
105
+
106
+ Do not opt integration/E2E tests, network-dependent checks, clocks, external services, or mutable
107
+ external caches into static reuse. Their state is not captured by this key. Source hashes alone
108
+ cannot justify reuse. An incorrect tool-input declaration can invalidate the caching assumption.
109
+
110
+ Stop hashes inputs again but does not spawn analyzers. Hashing a large ignored tool directory can be
111
+ expensive and the native hook has a ten-second timeout. Measure before enabling it; use smaller
112
+ complete tool inputs or leave caching off. No latency or token-saving target is claimed.
113
+
114
+ ## Evidence and CI
115
+
116
+ ```sh
117
+ node "$QUALITY_RUNNER" begin
118
+ # implementation, or the candidate checks in CI
119
+ node "$QUALITY_RUNNER" check --json
120
+ ```
121
+
122
+ `check` exits 1 on blocked evidence, 0 when all required checks pass, and reports errors as nonzero.
123
+ The default output is concise; `--json` includes per-check status, command, fingerprint, cache reuse,
124
+ measured scope, duration, output, signals, and any policy acknowledgement. The latest full report is
125
+ `<session-state-path>.report.json` under Git metadata and survives successful Stop; `begin` prints the
126
+ session state path. Treat command output as potentially sensitive when uploading reports.
127
+
128
+ For CI, use a fresh checkout and the same runner and project policy; `check` is the gate. A baseline
129
+ started on the candidate detects full command failures but cannot detect exceptions introduced by
130
+ that candidate. To compare new exception lines or protected policies, `begin` on the trusted base
131
+ and then check out the candidate in the same worktree and host session before `check`. Keep the
132
+ runner and protected CI policy trusted outside candidate-controlled scripts when enforcing security.
133
+
134
+ A green result only establishes the configured checks at the recorded inputs. It does not select a
135
+ useful prototype, judge abstraction quality, prove meaningful test coverage, or replace review.
@@ -0,0 +1,186 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { createHash } from 'node:crypto'
4
+ import { spawnSync } from 'node:child_process'
5
+
6
+ export const POLICY_PATH = '.agent-os/quality.json'
7
+ const SIGNALS = {
8
+ 'type-escape': /@ts-(?:ignore|nocheck|expect-error)\b|:\s*any\b|\bas\s+any\b/,
9
+ 'lint-disable': /eslint-disable|@SuppressWarnings\b/,
10
+ 'test-skip': /\b(?:it|test|describe)\s*\.\s*(?:skip|todo|only)\s*\(|\b[fx](?:it|describe)\s*\(|@Disabled\b/
11
+ }
12
+ const hash = value => createHash('sha256').update(value).digest('hex')
13
+ const identity = value => hash(JSON.stringify(value))
14
+ const runnerHash = identity(['project-controls.mjs', 'quality-delta.mjs'].map(name =>
15
+ hash(fs.readFileSync(new URL(name, import.meta.url)))))
16
+
17
+ function relativeFile(value) {
18
+ return typeof value === 'string' && value.length && !value.includes('\\') &&
19
+ !value.includes('\0') && !path.posix.isAbsolute(value) && !path.win32.isAbsolute(value) &&
20
+ !/^[A-Za-z]:/.test(value) && value.split('/').every(part => part && part !== '.' && part !== '..' && part !== '.git')
21
+ }
22
+
23
+ function exactKeys(value, keys, label) {
24
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
25
+ Object.keys(value).some(key => !keys.includes(key))) throw new Error(`Invalid ${label} fields`)
26
+ }
27
+
28
+ export function readPolicy(root) {
29
+ const file = path.join(root, POLICY_PATH)
30
+ if (!fs.existsSync(file)) return { schema: 1, checks: [], blockSignals: [], protectedFiles: [] }
31
+ const policy = JSON.parse(fs.readFileSync(file, 'utf8'))
32
+ exactKeys(policy, ['schema', 'checks', 'blockSignals', 'protectedFiles'], 'quality policy')
33
+ if (policy.schema !== 1 || !Array.isArray(policy.checks)) throw new Error('Quality policy requires schema 1 and checks')
34
+ const ids = new Set()
35
+ for (const check of policy.checks) {
36
+ exactKeys(check, ['id', 'command', 'required', 'timeoutMs', 'cache'], 'check')
37
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(check.id) || ids.has(check.id)) throw new Error('Check IDs must be unique lowercase names')
38
+ ids.add(check.id)
39
+ if (!Array.isArray(check.command) || !check.command.length ||
40
+ check.command.some(arg => typeof arg !== 'string' || arg.includes('\0')) || !check.command[0]) {
41
+ throw new Error(`Check ${check.id} requires an argument array`)
42
+ }
43
+ if (check.required !== undefined && typeof check.required !== 'boolean') throw new Error('required must be boolean')
44
+ if (check.timeoutMs !== undefined && (!Number.isInteger(check.timeoutMs) || check.timeoutMs < 1 || check.timeoutMs > 600000)) {
45
+ throw new Error('timeoutMs must be between 1 and 600000')
46
+ }
47
+ if (check.cache !== undefined && check.cache !== false) {
48
+ exactKeys(check.cache, ['kind', 'toolInputs'], 'cache')
49
+ if (check.cache.kind !== 'static' || !Array.isArray(check.cache.toolInputs) ||
50
+ !check.cache.toolInputs.length || !check.cache.toolInputs.every(relativeFile)) {
51
+ throw new Error('Static cache requires explicit repository-relative toolInputs')
52
+ }
53
+ }
54
+ }
55
+ policy.blockSignals ??= []
56
+ policy.protectedFiles ??= []
57
+ if (!Array.isArray(policy.blockSignals) || policy.blockSignals.some(name => !Object.hasOwn(SIGNALS, name))) {
58
+ throw new Error('Unknown blockSignals rule')
59
+ }
60
+ if (!Array.isArray(policy.protectedFiles) || !policy.protectedFiles.every(relativeFile)) throw new Error('Invalid protectedFiles')
61
+ return policy
62
+ }
63
+
64
+ export function scanSignals(content) {
65
+ const result = []
66
+ content.toString('utf8').split(/\r?\n/).forEach((text, index) => {
67
+ for (const [rule, pattern] of Object.entries(SIGNALS)) {
68
+ if (pattern.test(text)) result.push({ rule, line: index + 1, text: text.trim().slice(0, 300) })
69
+ }
70
+ })
71
+ return result
72
+ }
73
+
74
+ export function signalDelta(before, after) {
75
+ const old = new Map(before.map(file => [file.path, file]))
76
+ return after.flatMap(file => {
77
+ const counts = new Map()
78
+ for (const signal of old.get(file.path)?.signals || []) {
79
+ const key = `${signal.rule}\0${signal.text}`
80
+ counts.set(key, (counts.get(key) || 0) + 1)
81
+ }
82
+ return (file.signals || []).filter(signal => {
83
+ const key = `${signal.rule}\0${signal.text}`
84
+ const count = counts.get(key) || 0
85
+ if (count) { counts.set(key, count - 1); return false }
86
+ return true
87
+ }).map(signal => ({ path: file.path, ...signal }))
88
+ })
89
+ }
90
+
91
+ // Cache inputs are explicit, including ignored tool installations. Symlinks are rejected rather
92
+ // than treating the link text as evidence for the external file contents.
93
+ function inputHash(root, relative) {
94
+ const chunks = []
95
+ let ancestor = root
96
+ for (const part of relative.split('/')) {
97
+ ancestor = path.join(ancestor, part)
98
+ if (fs.lstatSync(ancestor).isSymbolicLink()) throw new Error(`Symlink cache input: ${relative}`)
99
+ }
100
+ function visit(file) {
101
+ const stat = fs.lstatSync(file)
102
+ if (stat.isSymbolicLink()) throw new Error(`Symlink cache input: ${relative}`)
103
+ chunks.push(path.relative(root, file), stat.mode)
104
+ if (stat.isDirectory()) {
105
+ for (const name of fs.readdirSync(file).sort()) visit(path.join(file, name))
106
+ } else if (stat.isFile()) chunks.push(hash(fs.readFileSync(file)))
107
+ else throw new Error(`Unsupported cache input: ${relative}`)
108
+ }
109
+ visit(path.join(root, relative))
110
+ return identity(chunks)
111
+ }
112
+
113
+ function executable(root, name, env) {
114
+ if (name === 'node') return process.execPath
115
+ const candidates = name.includes('/') || name.includes('\\') || path.isAbsolute(name)
116
+ ? [path.resolve(root, name)]
117
+ : (env.PATH || env.Path || '').split(path.delimiter).map(dir => path.resolve(root, dir, name))
118
+ const extensions = process.platform === 'win32' ? ['', ...(env.PATHEXT || '.EXE;.CMD;.BAT').split(';')] : ['']
119
+ for (const candidate of candidates) for (const extension of extensions) {
120
+ const file = candidate + extension
121
+ try { if (fs.statSync(file).isFile()) return fs.realpathSync(file) } catch { /* try next */ }
122
+ }
123
+ throw new Error(`Executable unavailable: ${name}`)
124
+ }
125
+
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)))
130
+ const protectedIdentity = [POLICY_PATH, ...policy.protectedFiles].map(name => {
131
+ try { return [name, inputHash(root, name)] } catch (error) {
132
+ if (error.code === 'ENOENT') return [name, null]
133
+ throw error
134
+ }
135
+ })
136
+ const signature = identity({ policy, protectedIdentity })
137
+ const checks = policy.checks.map(check => {
138
+ try {
139
+ if (check.cache && files.some(file => !['file', 'missing'].includes(file.kind))) {
140
+ throw new Error('Static cache cannot verify repository symlinks, submodules, or special files; disable caching')
141
+ }
142
+ const program = executable(root, check.command[0], env)
143
+ const toolInputs = (check.cache?.toolInputs || []).map(name => [name, inputHash(root, name)])
144
+ const key = identity({ check, signature, fileIdentity, environment, runnerHash,
145
+ runtime: process.versions, platform: process.platform, arch: process.arch,
146
+ program, executable: hash(fs.readFileSync(program)), executableMode: fs.statSync(program).mode, toolInputs })
147
+ return { ...check, program, key }
148
+ } catch (error) {
149
+ return { ...check, key: null, error: error.message }
150
+ }
151
+ })
152
+ return { policy, signature, checks, fingerprint: identity({ signature, fileIdentity, environment,
153
+ runnerHash, checks: checks.map(check => [check.id, check.key, check.error]) }) }
154
+ }
155
+
156
+ export function runControls(root, prepared, previous, env = process.env) {
157
+ return prepared.checks.map(check => {
158
+ const base = { id: check.id, command: check.command, required: check.required === true,
159
+ inputFingerprint: check.key, scope: 'repository plus declared toolInputs', cached: false }
160
+ if (check.error) return { ...base, status: 'unavailable', detail: check.error }
161
+ const prior = previous?.results?.find(result => result.id === check.id)
162
+ if (check.cache?.kind === 'static' && prior?.status === 'passed' && prior.inputFingerprint === check.key) {
163
+ return { ...prior, cached: true }
164
+ }
165
+ const start = Date.now()
166
+ const result = spawnSync(check.program, check.command.slice(1), {
167
+ cwd: root, env, encoding: 'utf8', shell: false, timeout: check.timeoutMs ?? 60000,
168
+ killSignal: 'SIGKILL', maxBuffer: 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe']
169
+ })
170
+ const status = result.error || result.signal ? 'error' : result.status === 0 ? 'passed' : 'failed'
171
+ return { ...base, status, exitCode: result.status, durationMs: Date.now() - start,
172
+ completedAt: new Date().toISOString(),
173
+ detail: result.error?.message || result.signal || '',
174
+ output: `${result.stdout || ''}${result.stderr || ''}`.slice(0, 16000) }
175
+ })
176
+ }
177
+
178
+ export function blockingControls(report) {
179
+ if (!report) return []
180
+ return [
181
+ ...(report.policyChanged ? ['quality policy changed: restore it or explicitly acknowledge the authorized change'] : []),
182
+ ...(report.stale ? ['inputs changed during verification; run check again'] : []),
183
+ ...report.results.filter(result => result.required && result.status !== 'passed').map(result => `${result.id}: ${result.status}`),
184
+ ...report.signals.filter(signal => signal.required).map(signal => `${signal.path}:${signal.line} ${signal.rule}`)
185
+ ]
186
+ }
@@ -0,0 +1,175 @@
1
+ import assert from 'node:assert/strict'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { execFileSync } from 'node:child_process'
6
+ import test from 'node:test'
7
+ import { begin, check, hook, clear } from './quality-delta.mjs'
8
+
9
+ const options = { detect: () => ({}) }
10
+ function fixture(t, checks = [], extra = {}) {
11
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-controls-'))
12
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }))
13
+ execFileSync('git', ['init', '-q', root])
14
+ fs.mkdirSync(path.join(root, '.agent-os'))
15
+ const write = (name, content) => fs.writeFileSync(path.join(root, name), content)
16
+ write('.agent-os/quality.json', JSON.stringify({ schema: 1, checks, ...extra }))
17
+ write('.gitignore', 'counter\ntools/\n')
18
+ fs.mkdirSync(path.join(root, 'tools'))
19
+ write('tools/version', '1')
20
+ write('source.ts', 'export const value = 1\n')
21
+ write('verify.cjs', "const fs = require('fs'); fs.appendFileSync('counter', 'x'); if (fs.readFileSync('source.ts', 'utf8').includes('BROKEN')) process.exit(1)")
22
+ return { root, write, policy: JSON.parse(fs.readFileSync(path.join(root, '.agent-os/quality.json'))), count: () => fs.readFileSync(path.join(root, 'counter'), 'utf8').length }
23
+ }
24
+ const required = { id: 'verify', command: ['node', 'verify.cjs'], required: true }
25
+ const cached = { ...required, cache: { kind: 'static', toolInputs: ['tools'] } }
26
+
27
+ test('required failures block repeatedly; fixed code passes and Stop never reruns commands', t => {
28
+ const f = fixture(t, [required])
29
+ const started = begin(f.root, options)
30
+ f.write('source.ts', 'BROKEN')
31
+ assert.equal(check(f.root, options).status, 'blocked')
32
+ assert.equal(hook(f.root).decision, 'block')
33
+ assert.equal(hook(f.root, { stop_hook_active: true }).decision, 'block')
34
+ assert.equal(f.count(), 1)
35
+ f.write('source.ts', 'export const value = 2')
36
+ assert.equal(check(f.root, options).status, 'ok')
37
+ assert.deepEqual(hook(f.root), {})
38
+ assert.equal(f.count(), 2)
39
+ assert.ok(fs.existsSync(started.statePath + '.report.json'))
40
+ })
41
+
42
+ test('advisory failures and new exception signals do not gate delivery', t => {
43
+ const f = fixture(t, [{ ...required, required: false }])
44
+ f.write('source.ts', '// @ts-ignore\nexport const value = 1')
45
+ begin(f.root, options)
46
+ f.write('source.ts', '// @ts-ignore\n// eslint-disable-next-line\nconst value: any = "BROKEN"')
47
+ const result = check(f.root, options)
48
+ assert.equal(result.status, 'ok')
49
+ assert.equal(result.controls.results[0].status, 'failed')
50
+ assert.deepEqual(result.controls.signals.map(s => s.rule), ['lint-disable', 'type-escape'])
51
+ assert.deepEqual(hook(f.root), {})
52
+ })
53
+
54
+ test('an explicit project exception rule blocks only additions since entry', t => {
55
+ const f = fixture(t, [], { blockSignals: ['test-skip'] })
56
+ f.write('source.ts', "test.skip('old', () => {})")
57
+ begin(f.root, options)
58
+ f.write('source.ts', "\n\ntest.skip('old', () => {})\ntest.skip('new', () => {})")
59
+ const result = check(f.root, options)
60
+ assert.equal(result.status, 'blocked')
61
+ assert.equal(result.controls.signals.length, 1)
62
+ assert.match(hook(f.root).reason, /source.ts:4 test-skip/)
63
+ })
64
+
65
+ test('static cache invalidates on source, ignored tool inputs, and environment; Stop checks freshness', t => {
66
+ const f = fixture(t, [cached])
67
+ const env = { ...process.env, CONTROL_FIXTURE: 'one' }
68
+ begin(f.root, { ...options, env })
69
+ assert.equal(check(f.root, { ...options, env }).controls.results[0].cached, false)
70
+ assert.equal(check(f.root, { ...options, env }).controls.results[0].cached, true)
71
+ assert.equal(f.count(), 1)
72
+ f.write('tools/version', '2')
73
+ assert.equal(hook(f.root, {}, { env }).decision, 'block')
74
+ assert.equal(check(f.root, { ...options, env }).controls.results[0].cached, false)
75
+ env.CONTROL_FIXTURE = 'two'
76
+ assert.equal(hook(f.root, {}, { env }).decision, 'block')
77
+ assert.equal(check(f.root, { ...options, env }).controls.results[0].cached, false)
78
+ f.write('source.ts', 'export const value = 3')
79
+ assert.equal(check(f.root, { ...options, env }).controls.results[0].cached, false)
80
+ assert.equal(f.count(), 4)
81
+ })
82
+
83
+ test('dynamic checks and failed static checks are never reused', t => {
84
+ for (const control of [required, cached]) {
85
+ const f = fixture(t, [control])
86
+ begin(f.root, options)
87
+ if (control.cache) f.write('source.ts', 'BROKEN')
88
+ check(f.root, options)
89
+ assert.equal(check(f.root, options).controls.results[0].cached, false)
90
+ assert.equal(f.count(), 2)
91
+ }
92
+ })
93
+
94
+ test('policy changes require explicit acknowledgement and cannot be cleared silently', t => {
95
+ const f = fixture(t, [required], { protectedFiles: ['verify.cjs'] })
96
+ begin(f.root, options)
97
+ f.write('verify.cjs', 'process.exit(0)')
98
+ assert.equal(check(f.root, options).status, 'blocked')
99
+ assert.throws(() => clear(f.root), /Policy changed|policy changed/)
100
+ assert.equal(hook(f.root).decision, 'block')
101
+ const accepted = check(f.root, { ...options, acceptPolicyChange: 'Authorized replacement of obsolete check' })
102
+ assert.equal(accepted.status, 'ok')
103
+ assert.match(accepted.controls.policyAcknowledgement.reason, /Authorized/)
104
+ assert.match(check(f.root, options).controls.policyAcknowledgement.reason, /Authorized/)
105
+ assert.deepEqual(hook(f.root), {})
106
+ })
107
+
108
+ test('missing executable, missing tool inputs, timeout, and malformed policy cannot report success', t => {
109
+ const controls = [
110
+ { ...required, command: ['agent-os-nonexistent-fixture-command'] },
111
+ { ...cached, cache: { kind: 'static', toolInputs: ['missing'] } },
112
+ { ...required, command: ['node', '-e', 'setInterval(() => {}, 1000)'], timeoutMs: 20 }
113
+ ]
114
+ for (const control of controls) {
115
+ const f = fixture(t, [control])
116
+ begin(f.root, options)
117
+ assert.equal(check(f.root, options).status, 'blocked')
118
+ assert.equal(hook(f.root).decision, 'block')
119
+ }
120
+ const f = fixture(t)
121
+ begin(f.root, options)
122
+ f.write('.agent-os/quality.json', '{')
123
+ assert.throws(() => check(f.root, options))
124
+ assert.equal(hook(f.root).decision, 'block')
125
+ })
126
+
127
+ test('commands that mutate source leave stale evidence', t => {
128
+ const f = fixture(t, [{ ...required, command: ['node', '-e', "require('fs').appendFileSync('source.ts', '\\n// generated')"] }])
129
+ begin(f.root, options)
130
+ assert.equal(check(f.root, options).controls.stale, true)
131
+ assert.equal(hook(f.root).decision, 'block')
132
+ })
133
+
134
+ test('cache rejects symlink ancestors and repository symlinks', { skip: process.platform === 'win32' }, t => {
135
+ const f = fixture(t, [{ ...cached, cache: { kind: 'static', toolInputs: ['tools/link/version'] } }])
136
+ fs.symlinkSync('.', path.join(f.root, 'tools/link'))
137
+ begin(f.root, options)
138
+ assert.match(check(f.root, options).controls.results[0].detail, /Symlink/)
139
+ const other = fixture(t, [cached])
140
+ fs.symlinkSync('source.ts', path.join(other.root, 'linked.ts'))
141
+ begin(other.root, options)
142
+ assert.match(check(other.root, options).controls.results[0].detail, /symlinks/)
143
+ })
144
+
145
+ test('host payload identity and another session cannot consume verified controls', t => {
146
+ const f = fixture(t, [required])
147
+ const env = { ...process.env, CODEX_THREAD_ID: 'controls-a', CLAUDE_CODE_SESSION_ID: '' }
148
+ begin(f.root, { ...options, env })
149
+ check(f.root, { ...options, env })
150
+ assert.deepEqual(hook(f.root, { session_id: 'controls-b', turn_id: 'turn' }, { env }), {})
151
+ assert.deepEqual(hook(f.root, { session_id: 'controls-a', turn_id: 'turn' }, { env }), {})
152
+ assert.equal(f.count(), 1)
153
+ })
154
+
155
+ test('focused tests are new exceptions under an explicit test-skip rule', t => {
156
+ const f = fixture(t, [], { blockSignals: ['test-skip'] })
157
+ begin(f.root, options)
158
+ f.write('source.ts', "test.only('focus', () => {})\ndescribe.only('suite', () => {})")
159
+ const result = check(f.root, options)
160
+ assert.equal(result.status, 'blocked')
161
+ assert.equal(result.controls.signals.length, 2)
162
+ })
163
+
164
+ test('external executable permission changes invalidate a cached pass', { skip: process.platform === 'win32' }, t => {
165
+ const external = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-os-tool-'))
166
+ t.after(() => fs.rmSync(external, { recursive: true, force: true }))
167
+ const tool = path.join(external, 'verify')
168
+ fs.writeFileSync(tool, '#!/bin/sh\nexit 0\n', { mode: 0o755 })
169
+ const f = fixture(t, [{ ...cached, command: [tool] }])
170
+ begin(f.root, options)
171
+ assert.equal(check(f.root, options).status, 'ok')
172
+ fs.chmodSync(tool, 0o644)
173
+ assert.equal(hook(f.root).decision, 'block')
174
+ assert.equal(check(f.root, options).status, 'blocked')
175
+ })
@@ -5,6 +5,7 @@ import { createHash, randomUUID } from 'node:crypto'
5
5
  import fs from 'node:fs'
6
6
  import path from 'node:path'
7
7
  import { fileURLToPath, pathToFileURL } from 'node:url'
8
+ import { prepareControls, runControls, scanSignals, signalDelta, blockingControls, POLICY_PATH } from './project-controls.mjs'
8
9
 
9
10
  export const STATE_SCHEMA = 2
10
11
  export const STATE_FILE_NAME = '.agent-os-quality-ratchet.json'
@@ -63,8 +64,8 @@ function hookSessionEnvironment(payload, env) {
63
64
  if (!sessionId) return env
64
65
  const codex = typeof payload?.turn_id === 'string' && payload.turn_id.trim()
65
66
  return codex
66
- ? { CODEX_THREAD_ID: sessionId }
67
- : { CLAUDE_CODE_SESSION_ID: sessionId }
67
+ ? { ...env, CLAUDE_CODE_SESSION_ID: '', CODEX_THREAD_ID: sessionId }
68
+ : { ...env, CODEX_THREAD_ID: '', CLAUDE_CODE_SESSION_ID: sessionId }
68
69
  }
69
70
 
70
71
  function normalizePath(value) {
@@ -258,7 +259,9 @@ function fileRecord(root, relativePath) {
258
259
  hash: digest(content),
259
260
  bytes: content.byteLength,
260
261
  source,
261
- nloc: source ? countNloc(content) : 0
262
+ nloc: source ? countNloc(content) : 0,
263
+ mode: stats.mode,
264
+ signals: source ? scanSignals(content) : []
262
265
  }
263
266
  }
264
267
 
@@ -584,6 +587,8 @@ export function begin(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
584
587
  const dependencies = packageDependencies(context.root)
585
588
  const analyzers = safeAnalyzerDetection(detect)
586
589
  const state = baselineState(context, candidate, dependencies, analyzers)
590
+ state.entry.hasControlPolicy = fs.existsSync(path.join(context.root, POLICY_PATH))
591
+ state.entry.controlSignature = prepareControls(context.root, candidate.files, env).signature
587
592
  writeState(context, state)
588
593
  return {
589
594
  statePath: context.statePath,
@@ -593,7 +598,7 @@ export function begin(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
593
598
  }
594
599
  }
595
600
 
596
- export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, env = process.env } = {}) {
601
+ export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, env = process.env, acceptPolicyChange = '' } = {}) {
597
602
  const context = repositoryContext(cwd, env)
598
603
  const state = readState(context)
599
604
  if (!state) error(`No active quality ratchet baseline exists for ${context.root}. Run begin before the first mutation.`, 'BASELINE_MISSING')
@@ -601,16 +606,45 @@ export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
601
606
  const dependencies = packageDependencies(context.root)
602
607
  const analyzers = safeAnalyzerDetection(detect)
603
608
  const evidence = evidenceFor(state, candidate, dependencies, analyzers)
609
+ const configured = state.entry.hasControlPolicy || fs.existsSync(path.join(context.root, POLICY_PATH))
610
+ const files = configured ? snapshot(context.root).files : candidate.files
611
+ const prepared = prepareControls(context.root, files, env)
612
+ // Old evidence-only baselines can continue without opting into project commands mid-flight.
613
+ const oldSignature = state.entry.controlSignature
614
+ const policyChanged = oldSignature ? oldSignature !== prepared.signature : fs.existsSync(path.join(context.root, POLICY_PATH))
615
+ if (acceptPolicyChange && !acceptPolicyChange.trim()) error('Policy acknowledgement requires a reason.', 'ARGUMENTS')
616
+ const accepted = policyChanged && Boolean(acceptPolicyChange.trim())
617
+ const signals = signalDelta(state.entry.files, files).map(signal => ({
618
+ ...signal, required: prepared.policy.blockSignals.includes(signal.rule)
619
+ }))
620
+ const results = policyChanged && !accepted ? [] : runControls(context.root, prepared, state.lastCheck?.evidence?.controls, env)
621
+ const after = configured ? prepareControls(context.root, snapshot(context.root).files, env) : prepared
622
+ evidence.controls = {
623
+ fingerprint: prepared.fingerprint, policyChanged: policyChanged && !accepted,
624
+ policyAcknowledgement: accepted ? { before: oldSignature || null, after: prepared.signature, reason: acceptPolicyChange.trim() } : state.policyAcknowledgement || null,
625
+ stale: after.fingerprint !== prepared.fingerprint, results, signals
626
+ }
627
+ if (accepted && !evidence.controls.stale) {
628
+ state.entry.controlSignature = prepared.signature
629
+ state.policyAcknowledgement = evidence.controls.policyAcknowledgement
630
+ }
631
+ evidence.status = blockingControls(evidence.controls).length ? 'blocked' : 'ok'
632
+ evidence.reportPath = context.statePath + '.report.json'
604
633
  state.lastCheck = {
605
634
  candidateFingerprint: candidate.fingerprint,
606
635
  evidence
607
636
  }
608
637
  writeState(context, state)
638
+ fs.writeFileSync(evidence.reportPath, JSON.stringify(evidence, null, 2) + '\n')
609
639
  return evidence
610
640
  }
611
641
 
612
642
  export function clear(cwd = process.cwd(), { env = process.env } = {}) {
613
643
  const context = repositoryContext(cwd, env)
644
+ const state = readState(context)
645
+ if (state?.entry.controlSignature && prepareControls(context.root, snapshot(context.root).files, env).signature !== state.entry.controlSignature) {
646
+ error('Quality policy changed. Restore it or acknowledge the authorized change with check --accept-policy-change <reason> before abandoning this baseline.', 'POLICY_CHANGED')
647
+ }
614
648
  if (fs.existsSync(context.statePath)) fs.rmSync(context.statePath, { force: true })
615
649
  return { statePath: context.statePath, cleared: true }
616
650
  }
@@ -648,6 +682,14 @@ export function hook(cwd = process.cwd(), payload = {}, { env = process.env } =
648
682
  }
649
683
  const fresh = state.lastCheck?.candidateFingerprint === candidate.fingerprint
650
684
  if (fresh) {
685
+ const controls = state.lastCheck.evidence?.controls
686
+ const configured = fs.existsSync(path.join(context.root, POLICY_PATH)) || controls?.results?.length || controls?.policyChanged
687
+ if (configured) {
688
+ const prepared = prepareControls(context.root, snapshot(context.root).files, env)
689
+ if (!controls || prepared.fingerprint !== controls.fingerprint) return blockResult('Project control evidence is stale; run quality-ratchet check.')
690
+ }
691
+ const blockers = blockingControls(controls)
692
+ if (blockers.length) return blockResult(`Project controls block delivery: ${blockers.slice(0, 5).join('; ')}. Fix the reported problem; do not rerun unchanged failing checks.`)
651
693
  fs.rmSync(context.statePath, { force: true })
652
694
  return allowResult()
653
695
  }
@@ -680,7 +722,13 @@ export function formatEvidence(evidence) {
680
722
  `Package dependencies: +${evidence.packageDependencies.added.length} -${evidence.packageDependencies.removed.length} ~${evidence.packageDependencies.updated.length} (${evidence.packageDependencies.status})`,
681
723
  ...OPTIONAL_ANALYZERS.map((name) => `Optional analyzer ${name}: ${evidence.optionalAnalyzers.candidate[name].status} — ${evidence.optionalAnalyzers.candidate[name].reason}`),
682
724
  `Candidate fingerprint: ${evidence.candidateFingerprint}`,
683
- `Machine-readable evidence: ${JSON.stringify(evidence)}`
725
+ ...(evidence.controls ? [
726
+ `Project controls: ${evidence.status}; ${evidence.controls.results.length} checks; ${evidence.controls.signals.length} new advisory/required signals`,
727
+ ...evidence.controls.results.filter(result => result.status !== 'passed').map(result => ` ${result.id}: ${result.status} ${result.detail || result.output?.slice(0, 500) || ''}`),
728
+ ...evidence.controls.signals.filter(signal => !signal.required).slice(0, 5).map(signal => ` advisory: ${signal.path}:${signal.line} ${signal.rule}: ${signal.text}`),
729
+ ...blockingControls(evidence.controls).slice(0, 5).map(reason => ` blocked: ${reason}`),
730
+ `Full report: ${evidence.reportPath}; use --json for structured output.`
731
+ ] : [])
684
732
  ]
685
733
  return lines.join('\n')
686
734
  }
@@ -692,6 +740,10 @@ function parseArguments(args) {
692
740
  const argument = args[index]
693
741
  if (argument === '--json') {
694
742
  result.json = true
743
+ } else if (argument === '--accept-policy-change') {
744
+ const reason = args[++index]
745
+ if (result.command !== 'check' || !reason?.trim() || reason.startsWith('--')) error('--accept-policy-change requires check and a reason.', 'ARGUMENTS')
746
+ result.acceptPolicyChange = reason
695
747
  } else if (argument === '--root') {
696
748
  const root = args[index + 1]
697
749
  if (!root || root.startsWith('-')) error('--root requires a path.', 'ARGUMENTS')
@@ -727,12 +779,13 @@ function main() {
727
779
  const options = parseArguments(process.argv.slice(2))
728
780
  if (options.command === 'begin') {
729
781
  const result = begin(options.root)
730
- console.log(`Quality ratchet baseline started for ${result.fileCount} files (${result.fingerprint}).`)
782
+ console.log(`Quality ratchet baseline started for ${result.fileCount} files (${result.fingerprint}). State: ${result.statePath}`)
731
783
  return
732
784
  }
733
785
  if (options.command === 'check') {
734
- const evidence = check(options.root)
786
+ const evidence = check(options.root, { acceptPolicyChange: options.acceptPolicyChange })
735
787
  console.log(options.json ? JSON.stringify(evidence) : formatEvidence(evidence))
788
+ if (evidence.status !== 'ok') process.exitCode = 1
736
789
  return
737
790
  }
738
791
  if (options.command === 'clear') {