@sockulags/agent-os 0.9.1 → 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.
Files changed (42) hide show
  1. package/README.md +112 -67
  2. package/cli/index.mjs +299 -12
  3. package/cli/index.test.mjs +277 -3
  4. package/hooks/hooks.json +17 -0
  5. package/package.json +6 -3
  6. package/policy.md +42 -40
  7. package/skills/batch-work/SKILL.md +43 -43
  8. package/skills/batch-work/agents/openai.yaml +2 -2
  9. package/skills/batch-work/references/manifest.md +100 -100
  10. package/skills/batch-work/scripts/manifest-hash.mjs +263 -263
  11. package/skills/batch-work/scripts/test-manifest-hash.mjs +132 -132
  12. package/skills/chart-work/SKILL.md +37 -37
  13. package/skills/chart-work/references/elicitation.md +25 -25
  14. package/skills/chart-work/references/map.md +84 -84
  15. package/skills/chart-work/references/prototypes.md +21 -21
  16. package/skills/check-work/SKILL.md +61 -0
  17. package/skills/deliver-work/SKILL.md +12 -12
  18. package/skills/deliver-work/workflow.md +119 -109
  19. package/skills/diagnose-before-fix/SKILL.md +24 -24
  20. package/skills/dispatch-next/SKILL.md +28 -28
  21. package/skills/init-agent-os/SKILL.md +52 -37
  22. package/skills/init-agent-os/references/repository-init.md +74 -0
  23. package/skills/list-skills/SKILL.md +43 -0
  24. package/skills/list-skills/agents/openai.yaml +2 -0
  25. package/skills/plain-voice/SKILL.md +39 -0
  26. package/skills/plain-voice/references/tells.md +82 -0
  27. package/skills/proportional-testing/SKILL.md +30 -0
  28. package/skills/proportional-testing/references/strategy.md +75 -0
  29. package/skills/quality-ratchet/SKILL.md +50 -0
  30. package/skills/quality-ratchet/scripts/quality-delta.mjs +752 -0
  31. package/skills/quality-ratchet/scripts/quality-delta.test.mjs +514 -0
  32. package/skills/scope-guard/SKILL.md +21 -21
  33. package/skills/shape-work/SKILL.md +39 -39
  34. package/skills/shape-work/references/implementation-issues.md +69 -69
  35. package/skills/shape-work/references/mockups.md +23 -23
  36. package/skills/simplifier/SKILL.md +34 -0
  37. package/skills/simplifier/agents/openai.yaml +2 -0
  38. package/skills/simplifier-audit/SKILL.md +28 -0
  39. package/skills/simplifier-audit/agents/openai.yaml +2 -0
  40. package/skills/simplifier-review/SKILL.md +36 -0
  41. package/skills/verify-before-done/SKILL.md +29 -29
  42. package/skills/writing-skills/SKILL.md +68 -68
package/README.md CHANGED
@@ -1,38 +1,47 @@
1
- # agent-os
2
-
3
- A lightweight personal agent operating system — an Agent Skills framework shared between
4
- Claude Code and Codex. One skill source, two platforms, ceremony proportional to the work.
5
-
6
- **Documentation: [sockulags.github.io/agent-os](https://sockulags.github.io/agent-os/)**
7
-
8
- ## Skills
9
-
10
- Reading order: the planning foundation (`shape-work`, then `chart-work`, which hands off into it),
11
- the on-ramp in front of both (`guide-me`), the remaining workflows, then the component skills the
12
- workflows compose (`understand-work`, `explain-work`), the disciplines, and the meta-skill.
13
-
14
- | Skill | Bucket | Invocation | Purpose |
15
- |---|---|---|---|
16
- | `shape-work` | workflow | manual | Turn bounded choices into implementation-ready issues |
17
- | `chart-work` | workflow | manual | Chart broad work as a parallel graph of decision tickets |
18
- | `guide-me` | workflow | manual | Guide a vague desire to an approved goal and into planning |
19
- | `deliver-work` | workflow | manual | Implement one change against boundaries and ground truth |
20
- | `batch-work` | workflow | manual | Run isolated ready units and verify the integrated result |
21
- | `dispatch-next` | workflow | manual | Pick or dispatch one action according to the request |
22
- | `init-agent-os` | workflow | manual | Managed policy setup or repository defaults |
23
- | `record-lesson` | workflow | manual | Record a durable lesson in repo or global policy |
24
- | `understand-work` | workflow | manual | Question out the need behind a stated wish |
25
- | `explain-work` | workflow | manual | Explain the task in plain language for approval |
26
- | `verify-before-done` | discipline | automatic | Fresh evidence before any completion claim |
27
- | `diagnose-before-fix` | discipline | automatic | Reproduce and root-cause before patching |
28
- | `scope-guard` | discipline | automatic | Keep work inside the task; flag drift |
29
- | `notice-lesson` | discipline | automatic | Treat interruptions as misunderstanding signals |
30
- | `writing-skills` | meta | manual | Doctrine and definition of done for agent-os skills |
31
-
32
- Manual skills carry `disable-model-invocation: true` (Claude) and `agents/openai.yaml` with
33
- `policy.allow_implicit_invocation: false` (Codex). Retired skills move to root `deprecated/`
34
- (outside the plugin's `skills/`, so they are never distributed).
35
-
1
+ # agent-os
2
+
3
+ A lightweight personal agent operating system — an Agent Skills framework shared between
4
+ Claude Code and Codex. One skill source, two platforms, ceremony proportional to the work.
5
+
6
+ **Documentation: [sockulags.github.io/agent-os](https://sockulags.github.io/agent-os/)**
7
+
8
+ ## Skills
9
+
10
+ Reading order: the planning foundation (`shape-work`, then `chart-work`, which hands off into it),
11
+ the on-ramp in front of both (`guide-me`), the remaining workflows, then the component skills the
12
+ workflows compose (`understand-work`, `explain-work`), the disciplines, and the meta skills.
13
+
14
+ | Skill | Bucket | Invocation | Purpose |
15
+ |---|---|---|---|
16
+ | `shape-work` | workflow | manual | Turn bounded choices into implementation-ready issues |
17
+ | `chart-work` | workflow | manual | Chart broad work as a parallel graph of decision tickets |
18
+ | `guide-me` | workflow | manual | Guide a vague desire to an approved goal and into planning |
19
+ | `deliver-work` | workflow | manual | Implement one change against boundaries and ground truth |
20
+ | `batch-work` | workflow | manual | Run isolated ready units and verify the integrated result |
21
+ | `dispatch-next` | workflow | manual | Pick or dispatch one action according to the request |
22
+ | `init-agent-os` | workflow | manual | Managed policy setup or repository defaults |
23
+ | `record-lesson` | workflow | manual | Record a durable lesson in repo or global policy |
24
+ | `simplifier` | workflow | manual | Remove unnecessary code and solution layers |
25
+ | `simplifier-audit` | workflow | manual | Audit a repository for simplification opportunities |
26
+ | `check-work` | workflow | automatic | Independently review a candidate and report or fix supported findings |
27
+ | `understand-work` | workflow | manual | Question out the need behind a stated wish |
28
+ | `explain-work` | workflow | manual | Explain the task in plain language for approval |
29
+ | `verify-before-done` | discipline | automatic | Fresh evidence before any completion claim |
30
+ | `diagnose-before-fix` | discipline | automatic | Reproduce and root-cause before patching |
31
+ | `proportional-testing` | discipline | automatic | Minimum meaningful regression coverage |
32
+ | `scope-guard` | discipline | automatic | Keep work inside the task; flag drift |
33
+ | `simplifier-review` | discipline | automatic | Review a diff for unnecessary complexity |
34
+ | `quality-ratchet` | discipline | automatic | Compare exact entry and candidate evidence without score gates |
35
+ | `notice-lesson` | discipline | automatic | Treat interruptions as misunderstanding signals |
36
+ | `plain-voice` | discipline | automatic | Apply plain voice to every agent-authored text response |
37
+ | `list-skills` | meta | manual | List installed skills and how to invoke them |
38
+ | `writing-skills` | meta | manual | Doctrine and definition of done for agent-os skills |
39
+
40
+ Manual skills carry `disable-model-invocation: true` (Claude) and `agents/openai.yaml` with
41
+ `policy.allow_implicit_invocation: false` (Codex). Automatic skills carry neither gate; their
42
+ descriptions define when they trigger, and they may still be explicitly named. Retired skills move to root `deprecated/`
43
+ (outside the plugin's `skills/`, so they are never distributed).
44
+
36
45
  ## Install
37
46
 
38
47
  ### Guided npm installer
@@ -64,7 +73,28 @@ skills. Use `--scope project` to install into the current project's skill direct
64
73
  command always downloads the current npm CLI; use `npx @sockulags/agent-os@latest update` to force
65
74
  the newest published installer.
66
75
 
67
- Direct Claude skills appear as `/<skill>` and direct Codex skills as `$<skill>`.
76
+ Direct Claude skills appear as `/<skill>` and direct Codex skills as `$<skill>`. Direct installation
77
+ also merges the managed quality-ratchet `Stop` hook into the selected host configuration without
78
+ replacing unrelated hooks. The user and project paths are `~/.claude/settings.json` or
79
+ `<project>/.claude/settings.json` for Claude Code, and `~/.codex/hooks.json` or
80
+ `<project>/.codex/hooks.json` for Codex. Node must be available to native plugin hooks. The
81
+ packaged hook keeps one logical command source: Claude and Unix-like Codex use
82
+ `${CLAUDE_PLUGIN_ROOT}`, while Windows Codex uses a quote-free `commandWindows` with a UTF-16LE
83
+ PowerShell `-EncodedCommand` payload that resolves `$env:PLUGIN_ROOT` at runtime.
84
+
85
+ The ratchet begins an exact worktree- and host-session-local baseline before the first mutation when `deliver-work`
86
+ can run it, checks the candidate before `simplifier-review`, and reports source-file/NLOC,
87
+ legacy-before/after, dependency, and optional-analyzer evidence. These are signals for semantic
88
+ judgment, not score or raw-count thresholds. Missing Lizard or jscpd is reported as unavailable,
89
+ never clean. A Stop hook blocks a missing, corrupt, or stale active lifecycle check until the same
90
+ host session records a fresh check; `stop_hook_active` does not bypass that requirement. Without a
91
+ baseline for the current host session it is a no-op. Resolve
92
+ `scripts/quality-delta.mjs` relative to the installed `quality-ratchet/SKILL.md` and run its `clear`
93
+ command from that same host session to abandon an active attempt. Standalone/manual use without a
94
+ host session ID uses a deterministic fallback state. `begin`, `check`, and `clear` read the host ID
95
+ from `CODEX_THREAD_ID` or `CLAUDE_CODE_SESSION_ID`, with Codex taking precedence when both exist;
96
+ native Stop resolves the same identity from its `session_id` payload, using non-empty `turn_id` to
97
+ identify Codex. There is no uninstall command yet.
68
98
 
69
99
  Native marketplace installation remains available with `--method plugin`. It requires the selected
70
100
  host CLI. Claude plugin skills appear as `/agent-os:<skill>`; Codex plugin skills remain
@@ -72,39 +102,54 @@ host CLI. Claude plugin skills appear as `/agent-os:<skill>`; Codex plugin skill
72
102
 
73
103
  For development against this clone, Claude can still use `claude --plugin-dir .`, and Codex can
74
104
  register the local `.agents/plugins/marketplace.json` marketplace.
75
-
76
- ## Release routine
77
-
105
+
106
+ ## Release routine
107
+
78
108
  1. Run `node scripts/validate-agent-os.mjs`, `npm test`, its red-case suite, and the live evals in `evals/`.
79
109
  2. Bump `version` in `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json`, and `package.json`.
80
- 3. Commit with the Git identity configured by the repository or current session, without AI attribution, and push.
81
- 4. Pack the npm artifact and verify a clean direct install for both hosts. Publish it, then verify
82
- `npx @sockulags/agent-os@latest update`; also smoke-test native plugin mode when it changed.
83
-
84
- ## Documentation site
85
-
86
- `docs-site/` is a [VitePress](https://vitepress.dev) site published to GitHub Pages by
87
- `.github/workflows/docs.yml` on every push to `main` that touches `docs-site/**`.
88
-
89
- ```bash
90
- npm --prefix docs-site install
91
- npm --prefix docs-site run dev
92
- ```
93
-
94
- The base path in `docs-site/.vitepress/config.mjs` is `/agent-os/` and must match the repository
95
- name. A skill edit and its documentation page are one change — the pages under `skills/` and
96
- `reference/` mirror the skill files and go stale first.
97
-
98
- ## Evals
99
-
100
- - `evals/cases/` — versioned trigger and behavior cases plus `manifest.json`, which indexes at least
101
- 2 positive and 2 negative cases per skill.
102
- - `evals/RESULTS.md` — historical forward-test results. New results evaluate observable contracts,
103
- not approval ceremony or reasoning traces.
104
- - `evals/runs/` — raw logs, gitignored.
105
-
106
- ## Global policy
107
-
110
+ 3. Add a dedicated changelog heading, commit and push, merge the green pull request to `main`, and
111
+ create the matching tag before publishing. Never publish npm from a dirty worktree.
112
+ 4. Pack the npm artifact and verify a clean direct install for both hosts, then publish it.
113
+ 5. Create the non-draft GitHub Release, confirm the newest stable release is marked `Latest`, wait
114
+ for Validate and Docs/Pages on current `main`, and run `node scripts/verify-release.mjs <version>`.
115
+ A release is incomplete until source, npm, GitHub, changelog, and live docs all pass that gate.
116
+
117
+ ## Documentation site
118
+
119
+ `docs-site/` is a [VitePress](https://vitepress.dev) site published to GitHub Pages by
120
+ `.github/workflows/docs.yml` on every push to `main` that touches `docs-site/**`.
121
+
122
+ ```bash
123
+ npm --prefix docs-site install
124
+ npm --prefix docs-site run dev
125
+ ```
126
+
127
+ The base path in `docs-site/.vitepress/config.mjs` is `/agent-os/` and must match the repository
128
+ name. A skill edit and its documentation page are one change — the pages under `skills/` and
129
+ `reference/` mirror the skill files and go stale first.
130
+
131
+ ## Evals
132
+
133
+ - `evals/cases/` — versioned trigger and behavior cases plus `manifest.json`, which indexes at least
134
+ 2 positive and 2 negative cases per skill.
135
+ - `evals/RESULTS.md` — historical forward-test results. New results evaluate observable contracts,
136
+ not approval ceremony or reasoning traces.
137
+ - `evals/behavior/` — runner-independent behavior cases, normalized run records, deterministic
138
+ scorecard graders, and explicit human/model judgments.
139
+ - `evals/runners/` — thin Promptfoo and Inspect AI adapters around the Agent OS scorecard.
140
+ - `evals/runs/` — raw logs, gitignored.
141
+
142
+ ## Experiments
143
+
144
+ Experimental work is kept outside the installable package until evidence supports promotion. The
145
+ first recorded Codex experiment replaces a large shared GPT-5.6 prompt with smaller
146
+ risk-calibrated core and Auto Review prompts, including exact text, eval evidence, local
147
+ installation, and rollback:
148
+
149
+ - [Codex custom instructions](https://github.com/sockulags/agent-os/blob/main/experimental/codex/custom_instructions.md)
150
+
151
+ ## Global policy
152
+
108
153
  `policy.md` is the source of truth. The npm installer and `init-agent-os global` install it as a
109
154
  managed block (`<!-- BEGIN/END AGENT OS -->`) in `~/.claude/CLAUDE.md` and
110
155
  `~/.codex/AGENTS.md`. Edit `policy.md`, never the installed blocks.
package/cli/index.mjs CHANGED
@@ -7,6 +7,10 @@ import os from 'node:os'
7
7
  import path from 'node:path'
8
8
  import { createInterface } from 'node:readline'
9
9
  import { fileURLToPath, pathToFileURL } from 'node:url'
10
+ import {
11
+ HOOK_TIMEOUT_SECONDS,
12
+ QUALITY_HOOK_MARKER
13
+ } from '../skills/quality-ratchet/scripts/quality-delta.mjs'
10
14
 
11
15
  const packageRoot = fileURLToPath(new URL('../', import.meta.url))
12
16
  const packagePath = path.join(packageRoot, 'package.json')
@@ -16,6 +20,7 @@ export const VERSION = packageJson.version
16
20
  export const PACKAGE_NAME = packageJson.name
17
21
  export const MARKETPLACE_SOURCE = 'sockulags/agent-os'
18
22
  export const INSTALL_MANIFEST = '.agent-os-install.json'
23
+ export const QUALITY_HOOK_EVENT = 'Stop'
19
24
 
20
25
  const BEGIN_MARKER = '<!-- BEGIN AGENT OS -->'
21
26
  const END_MARKER = '<!-- END AGENT OS -->'
@@ -77,6 +82,14 @@ function normalizeScope(value) {
77
82
  return normalized
78
83
  }
79
84
 
85
+ function quoteCommandArg(value) {
86
+ return '"' + String(value).replaceAll('"', '\\"') + '"'
87
+ }
88
+
89
+ export function buildManagedHookCommand(scriptPath, nodePath = process.execPath) {
90
+ return [quoteCommandArg(nodePath), quoteCommandArg(scriptPath), 'hook', QUALITY_HOOK_MARKER].join(' ')
91
+ }
92
+
80
93
  export function parseArgs(argv) {
81
94
  const result = {
82
95
  command: 'install',
@@ -163,6 +176,23 @@ export function targetSkillRoot(platform, scope, {
163
176
  throw new CliError('Local scope is available only with --method plugin.')
164
177
  }
165
178
 
179
+ export function hookConfigPath(platform, scope, {
180
+ homeDir = os.homedir(),
181
+ cwd = process.cwd()
182
+ } = {}) {
183
+ if (scope === 'user') {
184
+ return platform === 'codex'
185
+ ? path.join(homeDir, '.codex', 'hooks.json')
186
+ : path.join(homeDir, '.claude', 'settings.json')
187
+ }
188
+ if (scope === 'project') {
189
+ return platform === 'codex'
190
+ ? path.join(cwd, '.codex', 'hooks.json')
191
+ : path.join(cwd, '.claude', 'settings.json')
192
+ }
193
+ throw new CliError('Local scope is available only with --method plugin.')
194
+ }
195
+
166
196
  export function buildPlan(options, pathOptions = {}) {
167
197
  const { command, platform, method = 'direct', scope = 'user', policy = true } = options
168
198
  const steps = []
@@ -178,6 +208,13 @@ export function buildPlan(options, pathOptions = {}) {
178
208
  description: (command === 'update' ? 'Update' : 'Install') +
179
209
  ' Agent OS managed skills for ' + config.label + '.'
180
210
  })
211
+ steps.push({
212
+ platform: name,
213
+ kind: 'install-hooks',
214
+ command: 'filesystem',
215
+ args: [hookConfigPath(name, scope, pathOptions)],
216
+ description: 'Merge the Agent OS Stop hook into the ' + config.label + ' configuration.'
217
+ })
181
218
  continue
182
219
  }
183
220
 
@@ -391,6 +428,95 @@ function listPackagedSkills(sourceRoot, fsImpl = fs) {
391
428
  return entries
392
429
  }
393
430
 
431
+ function containsHookMarker(value) {
432
+ if (typeof value === 'string') return value.includes(QUALITY_HOOK_MARKER)
433
+ if (Array.isArray(value)) return value.some(containsHookMarker)
434
+ if (value && typeof value === 'object') return Object.values(value).some(containsHookMarker)
435
+ return false
436
+ }
437
+
438
+ function managedCommandHooks(value, matches = []) {
439
+ if (Array.isArray(value)) {
440
+ value.forEach((item) => managedCommandHooks(item, matches))
441
+ return matches
442
+ }
443
+ if (!value || typeof value !== 'object') return matches
444
+ if (typeof value.command === 'string' && value.command.includes(QUALITY_HOOK_MARKER)) {
445
+ matches.push(value)
446
+ }
447
+ Object.entries(value).forEach(([key, item]) => {
448
+ if (key !== 'command') managedCommandHooks(item, matches)
449
+ })
450
+ return matches
451
+ }
452
+
453
+ export function planManagedHookConfig(content, command, target = 'Agent OS hook configuration') {
454
+ let config
455
+ if (!content.trim()) {
456
+ config = {}
457
+ } else {
458
+ try {
459
+ config = JSON.parse(content)
460
+ } catch (cause) {
461
+ throw new CliError('Cannot read ' + target + ': ' + cause.message + '; no files were changed.')
462
+ }
463
+ }
464
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
465
+ throw new CliError('Refusing to merge the Agent OS hook into malformed ' + target + '; no files were changed.')
466
+ }
467
+ if (config.hooks === undefined) config.hooks = {}
468
+ if (!config.hooks || typeof config.hooks !== 'object' || Array.isArray(config.hooks)) {
469
+ throw new CliError('Refusing to merge the Agent OS hook into malformed ' + target + '.hooks; no files were changed.')
470
+ }
471
+ if (config.hooks[QUALITY_HOOK_EVENT] === undefined) config.hooks[QUALITY_HOOK_EVENT] = []
472
+ if (!Array.isArray(config.hooks[QUALITY_HOOK_EVENT])) {
473
+ throw new CliError('Refusing to merge the Agent OS hook into malformed ' + target + '.hooks.Stop; no files were changed.')
474
+ }
475
+
476
+ const managed = []
477
+ for (const [event, value] of Object.entries(config.hooks)) {
478
+ const matches = managedCommandHooks(value)
479
+ if (matches.length && event !== QUALITY_HOOK_EVENT) {
480
+ throw new CliError('Refusing to update an Agent OS hook outside hooks.Stop in ' + target + '; no files were changed.')
481
+ }
482
+ managed.push(...matches)
483
+ }
484
+ if (containsHookMarker(config) && managed.length === 0) {
485
+ throw new CliError('Refusing to update an ambiguous Agent OS hook marker in ' + target + '; no files were changed.')
486
+ }
487
+ if (managed.length > 1) {
488
+ throw new CliError('Refusing to update multiple Agent OS hook entries in ' + target + '; no files were changed.')
489
+ }
490
+
491
+ if (managed.length === 1) {
492
+ const entry = managed[0]
493
+ if (entry.type !== 'command') {
494
+ throw new CliError('Refusing to update a malformed Agent OS command hook in ' + target + '; no files were changed.')
495
+ }
496
+ const changed = entry.command !== command || entry.timeout !== HOOK_TIMEOUT_SECONDS
497
+ entry.command = command
498
+ entry.timeout = HOOK_TIMEOUT_SECONDS
499
+ return {
500
+ changed,
501
+ status: changed ? 'UPDATED' : 'OK',
502
+ content: changed ? JSON.stringify(config, null, 2) + '\n' : content
503
+ }
504
+ }
505
+
506
+ config.hooks[QUALITY_HOOK_EVENT].push({
507
+ hooks: [{
508
+ type: 'command',
509
+ command,
510
+ timeout: HOOK_TIMEOUT_SECONDS
511
+ }]
512
+ })
513
+ return {
514
+ changed: true,
515
+ status: 'ADDED',
516
+ content: JSON.stringify(config, null, 2) + '\n'
517
+ }
518
+ }
519
+
394
520
  function readInstallManifest(root, fsImpl = fs) {
395
521
  const manifestPath = path.join(root, INSTALL_MANIFEST)
396
522
  if (!fsImpl.existsSync(manifestPath)) return null
@@ -400,7 +526,8 @@ function readInstallManifest(root, fsImpl = fs) {
400
526
  } catch (error) {
401
527
  throw new CliError('Cannot read Agent OS install manifest at ' + manifestPath + ': ' + error.message)
402
528
  }
403
- if (manifest.package !== PACKAGE_NAME || !Array.isArray(manifest.skills)) {
529
+ if (manifest.package !== PACKAGE_NAME || !Array.isArray(manifest.skills) ||
530
+ ![1, 2].includes(manifest.schemaVersion ?? 1)) {
404
531
  throw new CliError('Refusing to use an unrecognized install manifest at ' + manifestPath)
405
532
  }
406
533
  return manifest
@@ -410,10 +537,69 @@ function directTargets(options, { homeDir, cwd }) {
410
537
  return selectedPlatforms(options.platform).map((platform) => ({
411
538
  platform,
412
539
  scope: options.scope,
413
- root: targetSkillRoot(platform, options.scope, { homeDir, cwd })
540
+ root: targetSkillRoot(platform, options.scope, { homeDir, cwd }),
541
+ hookPath: hookConfigPath(platform, options.scope, { homeDir, cwd })
414
542
  }))
415
543
  }
416
544
 
545
+ function prepareHookPlans(options, { homeDir, cwd, fsImpl = fs }) {
546
+ return directTargets(options, { homeDir, cwd }).map((target) => {
547
+ const scriptPath = path.join(target.root, 'quality-ratchet', 'scripts', 'quality-delta.mjs')
548
+ const command = buildManagedHookCommand(scriptPath)
549
+ const current = fsImpl.existsSync(target.hookPath)
550
+ ? fsImpl.readFileSync(target.hookPath, 'utf8')
551
+ : ''
552
+ return {
553
+ ...target,
554
+ command,
555
+ ...planManagedHookConfig(current, command, target.hookPath)
556
+ }
557
+ })
558
+ }
559
+
560
+ function writeFileAtomic(target, content, fsImpl = fs) {
561
+ const directory = path.dirname(target)
562
+ const temporary = path.join(
563
+ directory,
564
+ '.' + path.basename(target) + '.agent-os-' + randomUUID() + '.tmp'
565
+ )
566
+ fsImpl.mkdirSync(directory, { recursive: true })
567
+ try {
568
+ fsImpl.writeFileSync(temporary, content)
569
+ fsImpl.renameSync(temporary, target)
570
+ } finally {
571
+ if (fsImpl.existsSync(temporary)) fsImpl.rmSync(temporary, { force: true })
572
+ }
573
+ }
574
+
575
+ function applyHookPlans(plans, { output, fsImpl = fs }) {
576
+ const applied = []
577
+ try {
578
+ for (const plan of plans) {
579
+ if (plan.changed) {
580
+ const previous = fsImpl.existsSync(plan.hookPath)
581
+ ? fsImpl.readFileSync(plan.hookPath, 'utf8')
582
+ : null
583
+ applied.push({ ...plan, previous })
584
+ writeFileAtomic(plan.hookPath, plan.content, fsImpl)
585
+ }
586
+ output.write(plan.status.padEnd(7) + plan.hookPath + '\n')
587
+ }
588
+ } catch (cause) {
589
+ let rollbackFailure = null
590
+ for (const plan of applied.reverse()) {
591
+ try {
592
+ if (plan.previous === null) fsImpl.rmSync(plan.hookPath, { force: true })
593
+ else writeFileAtomic(plan.hookPath, plan.previous, fsImpl)
594
+ } catch (rollbackCause) {
595
+ rollbackFailure ??= rollbackCause
596
+ }
597
+ }
598
+ throw new CliError('Failed to update Agent OS hook configuration: ' + cause.message +
599
+ (rollbackFailure ? '; rollback also failed: ' + rollbackFailure.message : ''))
600
+ }
601
+ }
602
+
417
603
  function preflightDirectTarget(target, skillNames, fsImpl = fs) {
418
604
  const manifest = readInstallManifest(target.root, fsImpl)
419
605
  const managed = new Set(manifest?.skills || [])
@@ -463,14 +649,21 @@ function replaceManagedSkills(target, sourceRoot, skillNames, previousManifest,
463
649
  }
464
650
 
465
651
  const manifest = {
466
- schemaVersion: 1,
652
+ schemaVersion: 2,
467
653
  package: PACKAGE_NAME,
468
654
  version: VERSION,
469
655
  platform: target.platform,
470
656
  scope: target.scope,
471
- skills: skillNames
657
+ skills: skillNames,
658
+ integrations: {
659
+ hooks: {
660
+ configPath: target.hookPath,
661
+ event: QUALITY_HOOK_EVENT,
662
+ marker: QUALITY_HOOK_MARKER
663
+ }
664
+ }
472
665
  }
473
- fsImpl.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
666
+ writeFileAtomic(manifestPath, JSON.stringify(manifest, null, 2) + '\n', fsImpl)
474
667
  } catch (error) {
475
668
  for (const name of installed.reverse()) {
476
669
  const destination = path.join(target.root, name)
@@ -483,7 +676,7 @@ function replaceManagedSkills(target, sourceRoot, skillNames, previousManifest,
483
676
  if (previousManifestText === null) {
484
677
  if (fsImpl.existsSync(manifestPath)) fsImpl.rmSync(manifestPath, { force: true })
485
678
  } else {
486
- fsImpl.writeFileSync(manifestPath, previousManifestText)
679
+ writeFileAtomic(manifestPath, previousManifestText, fsImpl)
487
680
  }
488
681
  throw new CliError('Failed to update managed skills in ' + target.root + ': ' + error.message)
489
682
  } finally {
@@ -492,8 +685,7 @@ function replaceManagedSkills(target, sourceRoot, skillNames, previousManifest,
492
685
  }
493
686
  }
494
687
 
495
- function executeDirect(options, {
496
- output,
688
+ function prepareDirectInstall(options, {
497
689
  fsImpl,
498
690
  homeDir,
499
691
  cwd,
@@ -502,13 +694,83 @@ function executeDirect(options, {
502
694
  const skillNames = listPackagedSkills(sourceRoot, fsImpl)
503
695
  const targets = directTargets(options, { homeDir, cwd })
504
696
  const manifests = targets.map((target) => preflightDirectTarget(target, skillNames, fsImpl))
697
+ return { skillNames, targets, manifests, sourceRoot }
698
+ }
505
699
 
506
- targets.forEach((target, index) => {
700
+ function prepareManagedSkillRollback(plan, fsImpl = fs) {
701
+ const snapshots = []
702
+ try {
703
+ plan.targets.forEach((target, index) => {
704
+ const previousNames = plan.manifests[index]?.skills || []
705
+ const backupRoot = path.join(target.root, '.agent-os-transaction-' + randomUUID())
706
+ const backedUpNames = previousNames.filter((name) =>
707
+ fsImpl.existsSync(path.join(target.root, name)))
708
+ const manifestPath = path.join(target.root, INSTALL_MANIFEST)
709
+ const previousManifestText = fsImpl.existsSync(manifestPath)
710
+ ? fsImpl.readFileSync(manifestPath, 'utf8')
711
+ : null
712
+ const snapshot = { target, backupRoot, previousNames, backedUpNames, previousManifestText }
713
+ snapshots.push(snapshot)
714
+ if (backedUpNames.length > 0) {
715
+ fsImpl.mkdirSync(backupRoot, { recursive: true })
716
+ for (const name of backedUpNames) {
717
+ fsImpl.cpSync(path.join(target.root, name), path.join(backupRoot, name), { recursive: true })
718
+ }
719
+ }
720
+ })
721
+ return snapshots
722
+ } catch (cause) {
723
+ for (const snapshot of snapshots) {
724
+ if (fsImpl.existsSync(snapshot.backupRoot)) {
725
+ fsImpl.rmSync(snapshot.backupRoot, { recursive: true, force: true })
726
+ }
727
+ }
728
+ throw new CliError('Failed to prepare managed skill rollback: ' + cause.message)
729
+ }
730
+ }
731
+
732
+ function cleanupManagedSkillRollback(snapshots, fsImpl = fs) {
733
+ for (const snapshot of snapshots) {
734
+ if (fsImpl.existsSync(snapshot.backupRoot)) {
735
+ fsImpl.rmSync(snapshot.backupRoot, { recursive: true, force: true })
736
+ }
737
+ }
738
+ }
739
+
740
+ function rollbackManagedSkills(plan, snapshots, fsImpl = fs) {
741
+ let failure = null
742
+ snapshots.slice().reverse().forEach((snapshot) => {
743
+ try {
744
+ const names = [...new Set([...plan.skillNames, ...snapshot.previousNames])]
745
+ for (const name of names) {
746
+ const destination = path.join(snapshot.target.root, name)
747
+ if (fsImpl.existsSync(destination)) fsImpl.rmSync(destination, { recursive: true, force: true })
748
+ }
749
+ for (const name of snapshot.backedUpNames) {
750
+ const backup = path.join(snapshot.backupRoot, name)
751
+ if (fsImpl.existsSync(backup)) fsImpl.renameSync(backup, path.join(snapshot.target.root, name))
752
+ }
753
+ const manifestPath = path.join(snapshot.target.root, INSTALL_MANIFEST)
754
+ if (snapshot.previousManifestText === null) fsImpl.rmSync(manifestPath, { force: true })
755
+ else writeFileAtomic(manifestPath, snapshot.previousManifestText, fsImpl)
756
+ } catch (cause) {
757
+ failure ??= cause
758
+ }
759
+ })
760
+ if (failure) throw new CliError('Failed to restore managed skills: ' + failure.message)
761
+ cleanupManagedSkillRollback(snapshots, fsImpl)
762
+ }
763
+
764
+ function applyDirectInstall(options, plan, {
765
+ output,
766
+ fsImpl
767
+ }) {
768
+ plan.targets.forEach((target, index) => {
507
769
  const config = PLATFORM_CONFIG[target.platform]
508
770
  output.write('\n[' + config.label + ']\n')
509
771
  output.write((options.command === 'update' ? 'Updating' : 'Installing') +
510
- ' ' + skillNames.length + ' managed skills in ' + target.root + '...\n')
511
- replaceManagedSkills(target, sourceRoot, skillNames, manifests[index], fsImpl)
772
+ ' ' + plan.skillNames.length + ' managed skills in ' + target.root + '...\n')
773
+ replaceManagedSkills(target, plan.sourceRoot, plan.skillNames, plan.manifests[index], fsImpl)
512
774
  output.write('Done. Start a new ' + config.label + ' session to load the skills.\n')
513
775
  })
514
776
  }
@@ -653,11 +915,35 @@ export async function executeInstall(options, {
653
915
  const policyPlans = options.policy
654
916
  ? preparePolicyPlans({ fsImpl, homeDir, policyFile })
655
917
  : null
918
+ const directPlan = options.method === 'plugin'
919
+ ? null
920
+ : prepareDirectInstall(options, { fsImpl, homeDir, cwd, sourceRoot })
921
+ const hookPlans = options.method === 'plugin'
922
+ ? null
923
+ : prepareHookPlans(options, { fsImpl, homeDir, cwd })
656
924
 
657
925
  if (options.method === 'plugin') {
658
926
  executePlugin(options, { output, execute, exists })
659
927
  } else {
660
- executeDirect(options, { output, fsImpl, homeDir, cwd, sourceRoot })
928
+ const rollback = prepareManagedSkillRollback(directPlan, fsImpl)
929
+ try {
930
+ applyDirectInstall(options, directPlan, { output, fsImpl })
931
+ output.write('\n[Quality ratchet hooks]\n')
932
+ applyHookPlans(hookPlans, { output, fsImpl })
933
+ } catch (cause) {
934
+ try {
935
+ rollbackManagedSkills(directPlan, rollback, fsImpl)
936
+ } catch (rollbackCause) {
937
+ throw new CliError(cause.message + '; ' + rollbackCause.message)
938
+ }
939
+ throw cause
940
+ }
941
+ try {
942
+ cleanupManagedSkillRollback(rollback, fsImpl)
943
+ } catch (cause) {
944
+ throw new CliError('Agent OS direct install committed, but failed to clean transaction backups: ' +
945
+ cause.message + '. Installed skills and hooks were not rolled back.')
946
+ }
661
947
  }
662
948
 
663
949
  if (options.policy) {
@@ -673,6 +959,7 @@ export function printHelp(output = process.stdout) {
673
959
  ' npx ' + PACKAGE_NAME + ' install\n' +
674
960
  ' npx ' + PACKAGE_NAME + ' update\n\n' +
675
961
  'Direct installation is the default and does not require Codex or Claude Code CLI.\n\n' +
962
+ 'Direct installation also merges the Agent OS quality-ratchet Stop hook without replacing unrelated hooks.\n\n' +
676
963
  'Options:\n' +
677
964
  ' -p, --platform <name> claude, codex, or both\n' +
678
965
  ' -m, --method <name> direct (default) or plugin\n' +