@sockulags/agent-os 0.14.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 (101) hide show
  1. package/README.md +102 -49
  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/plugins/agent-os-core/skills/plan-work/references/elicitation.md +32 -0
  15. package/plugins/agent-os-core/skills/plan-work/references/map.md +108 -0
  16. package/plugins/agent-os-core/skills/plan-work/references/spec-template.md +64 -0
  17. package/plugins/agent-os-core/skills/record-lesson/SKILL.md +47 -0
  18. package/plugins/agent-os-core/skills/scope-guard/SKILL.md +53 -0
  19. package/{skills → plugins/agent-os-core/skills}/verify-before-done/SKILL.md +6 -2
  20. package/plugins/agent-os-dev/.claude-plugin/plugin.json +18 -0
  21. package/plugins/agent-os-dev/.codex-plugin/plugin.json +24 -0
  22. package/plugins/agent-os-dev/hooks/hooks.json +42 -0
  23. package/{skills → plugins/agent-os-dev/skills}/batch-work/SKILL.md +9 -4
  24. package/{skills → plugins/agent-os-dev/skills}/batch-work/references/manifest.md +8 -0
  25. package/{skills → plugins/agent-os-dev/skills}/check-work/SKILL.md +31 -14
  26. package/{skills/deliver-work/workflow.md → plugins/agent-os-dev/skills/deliver-work/SKILL.md} +85 -17
  27. package/plugins/agent-os-dev/skills/design-work/SKILL.md +145 -0
  28. package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.mjs +233 -0
  29. package/plugins/agent-os-dev/skills/design-work/scripts/render-sketch.test.mjs +73 -0
  30. package/plugins/agent-os-dev/skills/diagnose-before-fix/SKILL.md +29 -0
  31. package/{skills → plugins/agent-os-dev/skills}/dispatch-next/SKILL.md +10 -4
  32. package/plugins/agent-os-dev/skills/init-agent-os/SKILL.md +121 -0
  33. package/plugins/agent-os-dev/skills/init-agent-os/policy.md +88 -0
  34. package/plugins/agent-os-dev/skills/init-agent-os/references/guards.md +39 -0
  35. package/{skills → plugins/agent-os-dev/skills}/init-agent-os/references/repository-init.md +41 -9
  36. package/plugins/agent-os-dev/skills/init-agent-os/references/review-template.md +35 -0
  37. package/plugins/agent-os-dev/skills/init-agent-os/scripts/policy-block.mjs +187 -0
  38. package/plugins/agent-os-dev/skills/init-agent-os/templates/agent-review.yml +59 -0
  39. package/plugins/agent-os-dev/skills/init-agent-os/templates/lint-intents.yml +30 -0
  40. package/{skills → plugins/agent-os-dev/skills}/proportional-testing/SKILL.md +1 -1
  41. package/plugins/agent-os-dev/skills/quality-ratchet/SKILL.md +103 -0
  42. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/project-controls.md +31 -3
  43. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.mjs +145 -0
  44. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/analyzers.test.mjs +158 -0
  45. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.mjs +372 -0
  46. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/guards.test.mjs +138 -0
  47. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.mjs +322 -0
  48. package/plugins/agent-os-dev/skills/quality-ratchet/scripts/intent-files.test.mjs +172 -0
  49. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.mjs +59 -8
  50. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/project-controls.test.mjs +134 -8
  51. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.mjs +296 -22
  52. package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/scripts/quality-delta.test.mjs +114 -6
  53. package/plugins/agent-os-dev/skills/shape-work/SKILL.md +124 -0
  54. package/plugins/agent-os-dev/skills/shape-work/references/implementation-issues.md +143 -0
  55. package/{skills/chart-work → plugins/agent-os-dev/skills/shape-work}/references/prototypes.md +11 -13
  56. package/plugins/agent-os-dev/skills/simplify/SKILL.md +91 -0
  57. package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.mjs +166 -0
  58. package/plugins/agent-os-dev/skills/simplify/scripts/audit-evidence.test.mjs +49 -0
  59. package/policy.md +53 -20
  60. package/hooks/hooks.json +0 -17
  61. package/skills/chart-work/SKILL.md +0 -42
  62. package/skills/chart-work/references/elicitation.md +0 -25
  63. package/skills/chart-work/references/map.md +0 -84
  64. package/skills/deliver-work/SKILL.md +0 -12
  65. package/skills/diagnose-before-fix/SKILL.md +0 -24
  66. package/skills/explain-work/SKILL.md +0 -27
  67. package/skills/guide-me/SKILL.md +0 -36
  68. package/skills/init-agent-os/SKILL.md +0 -54
  69. package/skills/init-agent-os/scripts/policy-block.ps1 +0 -87
  70. package/skills/notice-lesson/SKILL.md +0 -20
  71. package/skills/quality-ratchet/SKILL.md +0 -72
  72. package/skills/record-lesson/SKILL.md +0 -31
  73. package/skills/scope-guard/SKILL.md +0 -32
  74. package/skills/shape-work/SKILL.md +0 -48
  75. package/skills/shape-work/references/implementation-issues.md +0 -69
  76. package/skills/shape-work/references/mockups.md +0 -23
  77. package/skills/simplifier/SKILL.md +0 -35
  78. package/skills/simplifier/agents/openai.yaml +0 -2
  79. package/skills/simplifier-audit/SKILL.md +0 -30
  80. package/skills/simplifier-review/SKILL.md +0 -40
  81. package/skills/understand-work/SKILL.md +0 -31
  82. package/skills/understand-work/agents/openai.yaml +0 -2
  83. package/skills/writing-skills/SKILL.md +0 -68
  84. package/skills/writing-skills/agents/openai.yaml +0 -2
  85. /package/{skills/batch-work → plugins/agent-os-core/skills/capture-intent}/agents/openai.yaml +0 -0
  86. /package/{skills/chart-work → plugins/agent-os-core/skills/explain-work}/agents/openai.yaml +0 -0
  87. /package/{skills/deliver-work → plugins/agent-os-core/skills/list-skills}/agents/openai.yaml +0 -0
  88. /package/{skills → plugins/agent-os-core/skills}/plain-voice/references/tells.md +0 -0
  89. /package/{skills/dispatch-next → plugins/agent-os-core/skills/plan-work}/agents/openai.yaml +0 -0
  90. /package/{skills/explain-work → plugins/agent-os-dev/skills/batch-work}/agents/openai.yaml +0 -0
  91. /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/manifest-hash.mjs +0 -0
  92. /package/{skills → plugins/agent-os-dev/skills}/batch-work/scripts/test-manifest-hash.mjs +0 -0
  93. /package/{skills → plugins/agent-os-dev/skills}/check-work/references/findings.md +0 -0
  94. /package/{skills/guide-me → plugins/agent-os-dev/skills/deliver-work}/agents/openai.yaml +0 -0
  95. /package/{skills/init-agent-os → plugins/agent-os-dev/skills/design-work}/agents/openai.yaml +0 -0
  96. /package/{skills/list-skills → plugins/agent-os-dev/skills/dispatch-next}/agents/openai.yaml +0 -0
  97. /package/{skills/record-lesson → plugins/agent-os-dev/skills/init-agent-os}/agents/openai.yaml +0 -0
  98. /package/{skills → plugins/agent-os-dev/skills}/proportional-testing/references/strategy.md +0 -0
  99. /package/{skills → plugins/agent-os-dev/skills}/quality-ratchet/references/structure.md +0 -0
  100. /package/{skills → plugins/agent-os-dev/skills}/shape-work/agents/openai.yaml +0 -0
  101. /package/{skills/simplifier-audit → plugins/agent-os-dev/skills/simplify}/agents/openai.yaml +0 -0
@@ -5,12 +5,18 @@ 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
+ import {
9
+ prepareControls, runControls, scanSignals, signalDelta, blockingControls, POLICY_PATH,
10
+ readPolicy, controlSignature, controlsTrusted, recordControlsTrust, DEFAULT_TRUST_STORE
11
+ } from './project-controls.mjs'
12
+ import { complexityDelta, findLizard, lizardFunctions, withTemporaryFiles } from './analyzers.mjs'
9
13
 
10
14
  export const STATE_SCHEMA = 2
11
15
  export const STATE_FILE_NAME = '.agent-os-quality-ratchet.json'
12
16
  export const QUALITY_HOOK_MARKER = '--agent-os-hook=quality-ratchet'
13
17
  export const HOOK_TIMEOUT_SECONDS = 10
18
+ export const STOP_BLOCK_LIMIT = 3
19
+ export const STALE_STATE_DAYS = 14
14
20
 
15
21
  const SOURCE_EXTENSIONS = new Set([
16
22
  '.c', '.cc', '.cpp', '.cxx', '.cs', '.css', '.go', '.h', '.hpp', '.java', '.js', '.jsx',
@@ -184,7 +190,7 @@ function absolutePath(root, relativePath) {
184
190
  return target
185
191
  }
186
192
 
187
- function isSourcePath(relativePath) {
193
+ export function isSourcePath(relativePath) {
188
194
  const normalized = relativePath.replaceAll('\\', '/')
189
195
  if (normalized.split('/').some((part) => ['.git', 'node_modules', 'dist', 'build', 'coverage'].includes(part))) {
190
196
  return false
@@ -348,9 +354,17 @@ function normalizeAnalyzer(value, name) {
348
354
  }
349
355
 
350
356
  export function detectOptionalAnalyzers({ spawn = spawnSync } = {}) {
357
+ const lizard = findLizard({ spawn })
358
+ ? {
359
+ status: 'integrated',
360
+ available: true,
361
+ integrated: true,
362
+ reason: 'lizard computes cyclomatic complexity deltas for touched source files.'
363
+ }
364
+ : unavailableAnalyzer('lizard is not installed; complexity deltas are unavailable and core Node evidence is used.')
351
365
  return Object.fromEntries(OPTIONAL_ANALYZERS.map((name) => [
352
366
  name,
353
- commandDetected(name, spawn)
367
+ name === 'lizard' ? lizard : commandDetected(name, spawn)
354
368
  ? {
355
369
  status: 'detected-not-integrated',
356
370
  available: true,
@@ -510,6 +524,56 @@ function evidenceFor(state, candidate, dependencies, analyzers) {
510
524
  }
511
525
  }
512
526
 
527
+ // Entry content is recoverable only for paths that were clean at begin: the baseline stores
528
+ // hashes, not file contents. The working tree may hold either the filtered (line-ending converted)
529
+ // or the raw blob form, so the one matching the recorded hash is used.
530
+ function entryContent(root, entry, relativePath) {
531
+ const record = entry.files.find((file) => file.path === relativePath)
532
+ if (!record || record.kind !== 'file' || !entry.head || entry.dirtyPaths.includes(relativePath)) return null
533
+ const spec = `${entry.head}:${relativePath}`
534
+ for (const args of [['cat-file', '--filters', spec], ['cat-file', 'blob', spec]]) {
535
+ const content = runGit(root, args, { allowFailure: true })
536
+ if (content !== null && digest(content) === record.hash) return content
537
+ }
538
+ return null
539
+ }
540
+
541
+ function complexityEvidence(root, entry, sourceFiles, analyze) {
542
+ const touched = [...sourceFiles.added, ...sourceFiles.changed].sort()
543
+ if (!touched.length) return { status: 'available', reason: 'No touched source files remain.', ...complexityDelta([], []), beforeUnavailable: [] }
544
+ try {
545
+ const after = analyze(root, touched)
546
+ if (after === null) {
547
+ return { status: 'unavailable', reason: 'lizard is not installed; complexity deltas were not computed.' }
548
+ }
549
+ const beforeFiles = sourceFiles.changed.map((relativePath) => [relativePath, entryContent(root, entry, relativePath)])
550
+ const known = beforeFiles.filter(([, content]) => content !== null)
551
+ const beforeUnavailable = beforeFiles.filter(([, content]) => content === null).map(([relativePath]) => relativePath)
552
+ const before = known.length ? withTemporaryFiles(known, (directory) => analyze(directory, known.map(([file]) => file))) : []
553
+ const comparable = after.filter((fn) => !beforeUnavailable.includes(fn.file))
554
+ return {
555
+ status: 'available',
556
+ reason: 'lizard cyclomatic complexity for touched source files.',
557
+ ...complexityDelta(before, comparable),
558
+ beforeUnavailable
559
+ }
560
+ } catch (cause) {
561
+ return { status: 'unavailable', reason: `Complexity analysis failed: ${cause.message}` }
562
+ }
563
+ }
564
+
565
+ function complexitySignals(complexity, policy) {
566
+ const threshold = policy.complexity?.threshold
567
+ if (!threshold || complexity.status !== 'available') return []
568
+ return complexity.functions.filter((fn) => fn.after > threshold).map((fn) => ({
569
+ path: fn.path,
570
+ line: fn.line,
571
+ rule: 'complexity',
572
+ text: `${fn.function} cyclomatic complexity ${fn.before ?? 'new'} -> ${fn.after} (threshold ${threshold})`,
573
+ required: policy.blockSignals.includes('complexity')
574
+ }))
575
+ }
576
+
513
577
  function readState(context) {
514
578
  if (!fs.existsSync(context.statePath)) return null
515
579
  let state
@@ -577,8 +641,31 @@ function baselineState(context, candidate, dependencies, analyzers) {
577
641
  }
578
642
  }
579
643
 
644
+ // Baselines now outlive a single turn, so an attempt that never reached `finish` or `clear` leaves
645
+ // its state behind. Remove other sessions' state and reports untouched for STALE_STATE_DAYS.
646
+ function pruneStaleStates(context, now = Date.now()) {
647
+ let names
648
+ try {
649
+ names = fs.readdirSync(context.gitDir)
650
+ } catch {
651
+ return
652
+ }
653
+ const limit = STALE_STATE_DAYS * 24 * 60 * 60 * 1000
654
+ for (const name of names) {
655
+ if (!name.startsWith(`${STATE_FILE_NAME}.`)) continue
656
+ const file = path.join(context.gitDir, name)
657
+ if (file === context.statePath) continue
658
+ try {
659
+ if (now - fs.statSync(file).mtimeMs > limit) fs.rmSync(file, { force: true })
660
+ } catch {
661
+ // Another session may remove its own state concurrently.
662
+ }
663
+ }
664
+ }
665
+
580
666
  export function begin(cwd = process.cwd(), { detect = detectOptionalAnalyzers, env = process.env } = {}) {
581
667
  const context = repositoryContext(cwd, env)
668
+ pruneStaleStates(context)
582
669
  if (fs.existsSync(context.statePath)) {
583
670
  readState(context)
584
671
  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')
@@ -598,7 +685,21 @@ export function begin(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
598
685
  }
599
686
  }
600
687
 
601
- export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, env = process.env, acceptPolicyChange = '' } = {}) {
688
+ function defaultComplexityAnalyzer() {
689
+ let launcher
690
+ return (cwd, files) => {
691
+ if (launcher === undefined) launcher = findLizard()
692
+ return lizardFunctions(cwd, files, { launcher })
693
+ }
694
+ }
695
+
696
+ export function check(cwd = process.cwd(), {
697
+ detect = detectOptionalAnalyzers,
698
+ env = process.env,
699
+ acceptPolicyChange = '',
700
+ analyzeComplexity = defaultComplexityAnalyzer(),
701
+ trustStore = DEFAULT_TRUST_STORE
702
+ } = {}) {
602
703
  const context = repositoryContext(cwd, env)
603
704
  const state = readState(context)
604
705
  if (!state) error(`No active quality ratchet baseline exists for ${context.root}. Run begin before the first mutation.`, 'BASELINE_MISSING')
@@ -614,13 +715,25 @@ export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
614
715
  const policyChanged = oldSignature ? oldSignature !== prepared.signature : fs.existsSync(path.join(context.root, POLICY_PATH))
615
716
  if (acceptPolicyChange && !acceptPolicyChange.trim()) error('Policy acknowledgement requires a reason.', 'ARGUMENTS')
616
717
  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)
718
+ evidence.complexity = complexityEvidence(context.root, state.entry, evidence.sourceFiles, analyzeComplexity)
719
+ const signals = [
720
+ ...signalDelta(state.entry.files, files).map(signal => ({
721
+ ...signal, required: prepared.policy.blockSignals.includes(signal.rule)
722
+ })),
723
+ ...complexitySignals(evidence.complexity, prepared.policy)
724
+ ]
725
+ // CI already runs the repository's own code in a disposable checkout and cannot answer a prompt.
726
+ const ciEnvironment = ['true', '1'].includes(String(env.CI ?? '').toLowerCase())
727
+ const trusted = !prepared.policy.checks.length || ciEnvironment ||
728
+ controlsTrusted(repositoryIdentity(context.root), prepared.signature, trustStore)
729
+ const results = (policyChanged && !accepted) || !trusted ? [] : runControls(context.root, prepared, state.lastCheck?.evidence?.controls, env)
621
730
  const after = configured ? prepareControls(context.root, snapshot(context.root).files, env) : prepared
622
731
  evidence.controls = {
623
732
  fingerprint: prepared.fingerprint, policyChanged: policyChanged && !accepted,
733
+ untrusted: trusted ? null : {
734
+ commands: prepared.policy.checks.map(entry => ({ id: entry.id, command: entry.command })),
735
+ trustCommand: developerTrustCommand(context.root)
736
+ },
624
737
  policyAcknowledgement: accepted ? { before: oldSignature || null, after: prepared.signature, reason: acceptPolicyChange.trim() } : state.policyAcknowledgement || null,
625
738
  stale: after.fingerprint !== prepared.fingerprint, results, signals
626
739
  }
@@ -639,6 +752,35 @@ export function check(cwd = process.cwd(), { detect = detectOptionalAnalyzers, e
639
752
  return evidence
640
753
  }
641
754
 
755
+ // Trust is shared by every worktree of one repository, so it keys on the common Git directory.
756
+ function repositoryIdentity(root) {
757
+ const common = path.resolve(root, runGit(root, ['rev-parse', '--git-common-dir']).trim())
758
+ let real = common
759
+ try {
760
+ real = fs.realpathSync(common)
761
+ } catch {
762
+ // Keep the resolved path when the directory cannot be canonicalized.
763
+ }
764
+ return normalizePath(real)
765
+ }
766
+
767
+ export function controlsTrustPlan(cwd = process.cwd()) {
768
+ const root = path.resolve(runGit(path.resolve(cwd), ['rev-parse', '--show-toplevel']).trim())
769
+ const policy = readPolicy(root)
770
+ return {
771
+ root,
772
+ repository: repositoryIdentity(root),
773
+ signature: controlSignature(root, policy),
774
+ checks: policy.checks.map(entry => ({ id: entry.id, command: entry.command, required: entry.required === true })),
775
+ protectedFiles: policy.protectedFiles
776
+ }
777
+ }
778
+
779
+ export function trustControls(plan, { trustStore = DEFAULT_TRUST_STORE } = {}) {
780
+ recordControlsTrust(plan.repository, plan.signature, plan.checks, trustStore)
781
+ return { trustStore, trusted: plan.checks.length }
782
+ }
783
+
642
784
  export function clear(cwd = process.cwd(), { env = process.env } = {}) {
643
785
  const context = repositoryContext(cwd, env)
644
786
  const state = readState(context)
@@ -649,6 +791,16 @@ export function clear(cwd = process.cwd(), { env = process.env } = {}) {
649
791
  return { statePath: context.statePath, cleared: true }
650
792
  }
651
793
 
794
+ // Closes a delivered attempt: it records a fresh check and removes the baseline only when that
795
+ // check passes. A blocked check keeps the baseline so delivery stays blocked.
796
+ export function finish(cwd = process.cwd(), options = {}) {
797
+ const evidence = check(cwd, options)
798
+ const context = repositoryContext(cwd, options.env ?? process.env)
799
+ if (evidence.status !== 'ok') return { evidence, statePath: context.statePath, closed: false }
800
+ fs.rmSync(context.statePath, { force: true })
801
+ return { evidence, statePath: context.statePath, closed: true }
802
+ }
803
+
652
804
  function allowResult() {
653
805
  return {}
654
806
  }
@@ -657,10 +809,47 @@ function blockResult(reason) {
657
809
  return { decision: 'block', reason }
658
810
  }
659
811
 
812
+ // Every Stop block is bounded. A check can stay stale or a required control can keep failing for
813
+ // reasons the agent cannot fix (a missing tool, a flaky dependency, a failing runner), and the
814
+ // host's own continuation cap resets whenever the agent calls a tool. After repeated re-entered
815
+ // Stops on the same unchanged candidate, the hook hands the decision to the user instead of
816
+ // looping. The baseline stays active, so `finish` still refuses delivery until a passing check.
817
+ function boundedBlockResult(context, state, kind, fingerprint, reason, releaseMessage, payload) {
818
+ const key = `${kind}:${fingerprint}`
819
+ const released = state.stopRelease?.key === key
820
+ const count = state.stopBlocks?.key === key ? state.stopBlocks.count + 1 : 1
821
+ if (released || (payload?.stop_hook_active === true && count > STOP_BLOCK_LIMIT)) {
822
+ if (!released) {
823
+ state.stopRelease = { key }
824
+ writeState(context, state)
825
+ }
826
+ return { systemMessage: `${releaseMessage} Stopping is allowed so you can decide how to proceed; the baseline stays active and delivery stays blocked until a passing check.` }
827
+ }
828
+ state.stopBlocks = { key, count }
829
+ writeState(context, state)
830
+ return blockResult(reason)
831
+ }
832
+
660
833
  function lifecycleCommand(command) {
661
834
  return `"${process.execPath}" "${fileURLToPath(import.meta.url)}" ${command}`
662
835
  }
663
836
 
837
+ // A developer pastes this into their own terminal, so it names the worktree and, on Windows, uses
838
+ // the PowerShell call operator that a quoted executable path needs.
839
+ function developerTrustCommand(root) {
840
+ const command = `${lifecycleCommand('trust')} --root "${root}"`
841
+ return process.platform === 'win32' ? `& ${command}` : command
842
+ }
843
+
844
+ // The guard hooks freeze accepted intents and specs only while a delivery baseline is active.
845
+ export function deliveryBaselineActive(cwd = process.cwd(), payload = {}, { env = process.env } = {}) {
846
+ try {
847
+ return fs.existsSync(repositoryContext(cwd, hookSessionEnvironment(payload, env)).statePath)
848
+ } catch {
849
+ return false
850
+ }
851
+ }
852
+
664
853
  export function hook(cwd = process.cwd(), payload = {}, { env = process.env } = {}) {
665
854
  let context
666
855
  try {
@@ -677,8 +866,15 @@ export function hook(cwd = process.cwd(), payload = {}, { env = process.env } =
677
866
  try {
678
867
  candidate = candidateSnapshot(context.root, state.entry, { includeFiles: false })
679
868
  } catch (cause) {
680
- const reason = `Quality ratchet could not inspect the candidate: ${cause.message}. Run the quality-ratchet check and retry.`
681
- return blockResult(reason)
869
+ return boundedBlockResult(context, state, 'inspect', 'uninspectable',
870
+ `Quality ratchet could not inspect the candidate: ${cause.message}. Run the quality-ratchet check and retry.`,
871
+ `Quality ratchet still cannot inspect the candidate: ${cause.message}.`, payload)
872
+ }
873
+ // An inspection failure has no candidate fingerprint, so its bound resets once inspection works.
874
+ if ([state.stopRelease?.key, state.stopBlocks?.key].some((key) => key?.startsWith('inspect:'))) {
875
+ if (state.stopRelease?.key?.startsWith('inspect:')) delete state.stopRelease
876
+ if (state.stopBlocks?.key?.startsWith('inspect:')) delete state.stopBlocks
877
+ writeState(context, state)
682
878
  }
683
879
  const fresh = state.lastCheck?.candidateFingerprint === candidate.fingerprint
684
880
  if (fresh) {
@@ -686,17 +882,35 @@ export function hook(cwd = process.cwd(), payload = {}, { env = process.env } =
686
882
  const configured = fs.existsSync(path.join(context.root, POLICY_PATH)) || controls?.results?.length || controls?.policyChanged
687
883
  if (configured) {
688
884
  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.')
885
+ if (!controls || prepared.fingerprint !== controls.fingerprint) {
886
+ return boundedBlockResult(context, state, 'controls-stale', candidate.fingerprint,
887
+ `Project control evidence is stale. Run \`${lifecycleCommand('check')}\` before stopping.`,
888
+ 'Quality ratchet: project control evidence is still stale for the unchanged candidate.', payload)
889
+ }
690
890
  }
691
891
  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.`)
693
- fs.rmSync(context.statePath, { force: true })
892
+ // The agent cannot resolve untrusted controls, so blocking would only spend continuations.
893
+ if (controls?.untrusted && blockers.length === 1) {
894
+ return {
895
+ systemMessage: 'Quality ratchet: this repository declares project controls that are not trusted on this machine, so none ran: ' +
896
+ controls.untrusted.commands.map((entry) => `${entry.id} ${JSON.stringify(entry.command)}`).join('; ') +
897
+ `. To review and trust them, run in a terminal: ${controls.untrusted.trustCommand}. Delivery stays blocked until then.`
898
+ }
899
+ }
900
+ if (blockers.length) {
901
+ const summary = blockers.slice(0, 5).join('; ')
902
+ return boundedBlockResult(context, state, 'controls', candidate.fingerprint,
903
+ `Project controls block delivery: ${summary}. Fix the reported problem; do not rerun unchanged failing checks. If it cannot be fixed in this session, report the blocker and stop.`,
904
+ `Quality ratchet: required project controls still fail for the unchanged candidate: ${summary}.`, payload)
905
+ }
906
+ // A passing check keeps the baseline: a turn can end mid-delivery to ask the developer, and
907
+ // the next turn still compares against the exact entry state. `finish` or `clear` ends it.
694
908
  return allowResult()
695
909
  }
696
- const reason = state.lastCheck
697
- ? `Quality ratchet check is stale for the current candidate. Run \`${lifecycleCommand('check')}\` before stopping.`
698
- : `Quality ratchet has an active baseline but no check for this candidate. Run \`${lifecycleCommand('check')}\` before stopping.`
699
- return blockResult(reason)
910
+ const missing = state.lastCheck ? 'is stale for the current candidate' : 'has not run for this candidate'
911
+ return boundedBlockResult(context, state, 'stale', candidate.fingerprint,
912
+ `Quality ratchet check ${missing}. Run \`${lifecycleCommand('check')}\` before stopping, also when you only pause to ask the developer; the baseline stays active across turns.`,
913
+ `Quality ratchet: the check ${missing} after repeated Stop blocks.`, payload)
700
914
  } catch (cause) {
701
915
  const reason = cause instanceof QualityRatchetError
702
916
  ? cause.message
@@ -709,6 +923,16 @@ function humanList(values) {
709
923
  return values.length ? values.join(', ') : 'none'
710
924
  }
711
925
 
926
+ function complexityLines(complexity) {
927
+ if (!complexity) return []
928
+ if (complexity.status !== 'available') return [`Complexity: unavailable (${complexity.reason})`]
929
+ return [
930
+ `Complexity (touched functions): ${complexity.increased} increased, ${complexity.added} new, ${complexity.decreased} decreased or removed; max ${complexity.maxAfter}`,
931
+ ...complexity.functions.slice(0, 10).map((fn) => ` ${fn.path}:${fn.line} ${fn.function}: ${fn.before ?? 'new'} -> ${fn.after}`),
932
+ ...(complexity.beforeUnavailable.length ? [` before unavailable (dirty at begin): ${humanList(complexity.beforeUnavailable)}`] : [])
933
+ ]
934
+ }
935
+
712
936
  export function formatEvidence(evidence) {
713
937
  const lines = [
714
938
  'Agent OS quality-ratchet evidence',
@@ -721,12 +945,18 @@ export function formatEvidence(evidence) {
721
945
  `Touched legacy after: ${evidence.touchedLegacy.after.status} (${humanList(evidence.touchedLegacy.after.files)})`,
722
946
  `Package dependencies: +${evidence.packageDependencies.added.length} -${evidence.packageDependencies.removed.length} ~${evidence.packageDependencies.updated.length} (${evidence.packageDependencies.status})`,
723
947
  ...OPTIONAL_ANALYZERS.map((name) => `Optional analyzer ${name}: ${evidence.optionalAnalyzers.candidate[name].status} — ${evidence.optionalAnalyzers.candidate[name].reason}`),
948
+ ...complexityLines(evidence.complexity),
724
949
  `Candidate fingerprint: ${evidence.candidateFingerprint}`,
725
950
  ...(evidence.controls ? [
726
951
  `Project controls: ${evidence.status}; ${evidence.controls.results.length} checks; ${evidence.controls.signals.length} new advisory/required signals`,
727
952
  ...evidence.controls.results.filter(result => result.status !== 'passed').map(result => ` ${result.id}: ${result.status} ${result.detail || result.output?.slice(0, 500) || ''}`),
728
953
  ...evidence.controls.signals.filter(signal => !signal.required).slice(0, 5).map(signal => ` advisory: ${signal.path}:${signal.line} ${signal.rule}: ${signal.text}`),
729
954
  ...blockingControls(evidence.controls).slice(0, 5).map(reason => ` blocked: ${reason}`),
955
+ ...(evidence.controls.untrusted ? [
956
+ ' Untrusted repository commands that were not run:',
957
+ ...evidence.controls.untrusted.commands.map(entry => ` ${entry.id}: ${JSON.stringify(entry.command)}`),
958
+ ` The developer reviews and trusts them by running this in an interactive terminal: ${evidence.controls.untrusted.trustCommand}`
959
+ ] : []),
730
960
  `Full report: ${evidence.reportPath}; use --json for structured output.`
731
961
  ] : [])
732
962
  ]
@@ -742,7 +972,7 @@ function parseArguments(args) {
742
972
  result.json = true
743
973
  } else if (argument === '--accept-policy-change') {
744
974
  const reason = args[++index]
745
- if (result.command !== 'check' || !reason?.trim() || reason.startsWith('--')) error('--accept-policy-change requires check and a reason.', 'ARGUMENTS')
975
+ if (!['check', 'finish'].includes(result.command) || !reason?.trim() || reason.startsWith('--')) error('--accept-policy-change requires check or finish and a reason.', 'ARGUMENTS')
746
976
  result.acceptPolicyChange = reason
747
977
  } else if (argument === '--root') {
748
978
  const root = args[index + 1]
@@ -759,12 +989,41 @@ function parseArguments(args) {
759
989
  }
760
990
  index += 1
761
991
  }
762
- if (!['begin', 'check', 'clear', 'hook'].includes(result.command)) {
763
- error(`Unknown command "${result.command}". Use begin, check, clear, or hook.`, 'ARGUMENTS')
992
+ if (!['begin', 'check', 'finish', 'clear', 'trust', 'hook'].includes(result.command)) {
993
+ error(`Unknown command "${result.command}". Use begin, check, finish, clear, trust, or hook.`, 'ARGUMENTS')
764
994
  }
765
995
  return result
766
996
  }
767
997
 
998
+ // Trust is the developer's decision, so it needs an interactive terminal. An agent's shell tool has
999
+ // no TTY; this is a speed bump and a visible prompt, not a tamper-proof boundary.
1000
+ async function runTrust(root, { input = process.stdin, output = process.stdout } = {}) {
1001
+ const plan = controlsTrustPlan(root)
1002
+ if (!plan.checks.length) {
1003
+ output.write(`No project controls are declared in ${POLICY_PATH}.\n`)
1004
+ return
1005
+ }
1006
+ output.write(`Repository: ${plan.root}\nCommands declared in ${POLICY_PATH}:\n`)
1007
+ for (const entry of plan.checks) output.write(` ${entry.id}${entry.required ? ' (required)' : ''}: ${JSON.stringify(entry.command)}\n`)
1008
+ if (plan.protectedFiles.length) output.write(`Protected files: ${plan.protectedFiles.join(', ')}\n`)
1009
+ if (!input.isTTY || !output.isTTY) {
1010
+ error('trust must be run by the developer in an interactive terminal; an agent must not run it.', 'TRUST_INTERACTIVE')
1011
+ }
1012
+ const readline = await import('node:readline/promises')
1013
+ const prompt = readline.createInterface({ input, output })
1014
+ try {
1015
+ const answer = (await prompt.question('Run these commands during quality-ratchet check on this machine? [y/N] ')).trim().toLowerCase()
1016
+ if (answer !== 'y' && answer !== 'yes') {
1017
+ output.write('Not trusted. check will keep reporting these controls as untrusted.\n')
1018
+ return
1019
+ }
1020
+ } finally {
1021
+ prompt.close()
1022
+ }
1023
+ const result = trustControls(plan)
1024
+ output.write(`Trusted ${result.trusted} commands for this repository in ${result.trustStore}. Changing ${POLICY_PATH} or a protected file requires trusting again.\n`)
1025
+ }
1026
+
768
1027
  function readHookPayload() {
769
1028
  try {
770
1029
  const input = fs.readFileSync(0, 'utf8').trim()
@@ -774,9 +1033,13 @@ function readHookPayload() {
774
1033
  }
775
1034
  }
776
1035
 
777
- function main() {
1036
+ async function main() {
778
1037
  try {
779
1038
  const options = parseArguments(process.argv.slice(2))
1039
+ if (options.command === 'trust') {
1040
+ await runTrust(options.root)
1041
+ return
1042
+ }
780
1043
  if (options.command === 'begin') {
781
1044
  const result = begin(options.root)
782
1045
  console.log(`Quality ratchet baseline started for ${result.fileCount} files (${result.fingerprint}). State: ${result.statePath}`)
@@ -788,6 +1051,17 @@ function main() {
788
1051
  if (evidence.status !== 'ok') process.exitCode = 1
789
1052
  return
790
1053
  }
1054
+ if (options.command === 'finish') {
1055
+ const result = finish(options.root, { acceptPolicyChange: options.acceptPolicyChange })
1056
+ console.log(options.json ? JSON.stringify(result) : [
1057
+ formatEvidence(result.evidence),
1058
+ result.closed
1059
+ ? `Quality ratchet baseline closed at ${result.statePath}.`
1060
+ : `Quality ratchet check is ${result.evidence.status}; the baseline stays active at ${result.statePath}.`
1061
+ ].join('\n'))
1062
+ if (!result.closed) process.exitCode = 1
1063
+ return
1064
+ }
791
1065
  if (options.command === 'clear') {
792
1066
  const result = clear(options.root)
793
1067
  console.log(`Quality ratchet baseline cleared at ${result.statePath}.`)
@@ -798,7 +1072,7 @@ function main() {
798
1072
  console.log(JSON.stringify(result))
799
1073
  } catch (cause) {
800
1074
  console.error(`quality-ratchet: ${cause.message}`)
801
- process.exitCode = cause instanceof QualityRatchetError && cause.code === 'ARGUMENTS' ? 2 : 1
1075
+ process.exitCode = cause instanceof QualityRatchetError && ['ARGUMENTS', 'TRUST_INTERACTIVE'].includes(cause.code) ? 2 : 1
802
1076
  }
803
1077
  }
804
1078