agent-personalizer 0.8.3 → 0.8.5

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 (43) hide show
  1. package/CHANGELOG.md +40 -2
  2. package/CONTRIBUTING.md +2 -2
  3. package/README.md +18 -8
  4. package/RELEASING.md +1 -1
  5. package/SECURITY.md +4 -2
  6. package/bin/agent-personalizer.js +132 -82
  7. package/bin/git-exclude.cjs +1 -1
  8. package/bin/global.cjs +201 -0
  9. package/bin/home.cjs +15 -0
  10. package/bin/install-plan.cjs +7 -2
  11. package/bin/known-hashes.json +78 -0
  12. package/bin/learn.cjs +4 -2
  13. package/bin/sessions.cjs +64 -16
  14. package/bin/uninstall.cjs +2 -1
  15. package/docs/guarantees.md +2 -2
  16. package/docs/install.md +29 -5
  17. package/docs/learning.md +9 -6
  18. package/docs/paste-guide.md +5 -3
  19. package/docs/tiers.md +1 -1
  20. package/examples/freelance-illustrator/.agent-personalizer.json +3 -3
  21. package/examples/freelance-illustrator/AGENTS.md +1 -1
  22. package/examples/freelance-illustrator/AGENT_ONBOARDING.md +2 -2
  23. package/examples/freelance-illustrator/CLAUDE.md +1 -1
  24. package/examples/freelance-illustrator/rules/30-folder-index-is-part-of-the-change.md +2 -2
  25. package/examples/freelance-illustrator/rules/README.md +2 -0
  26. package/examples/lab-technician/.agent-personalizer.json +3 -3
  27. package/examples/lab-technician/AGENTS.md +1 -1
  28. package/examples/lab-technician/AGENT_ONBOARDING.md +1 -1
  29. package/examples/lab-technician/CLAUDE.md +1 -1
  30. package/examples/lab-technician/rules/30-folder-index-is-part-of-the-change.md +2 -2
  31. package/examples/lab-technician/rules/README.md +2 -0
  32. package/examples/product-designer/.agent-personalizer.json +3 -3
  33. package/examples/product-designer/AGENTS.md +1 -1
  34. package/examples/product-designer/AGENT_ONBOARDING.md +1 -1
  35. package/examples/product-designer/CLAUDE.md +1 -1
  36. package/examples/product-designer/rules/30-folder-index-is-part-of-the-change.md +2 -2
  37. package/examples/product-designer/rules/README.md +2 -0
  38. package/hooks/README.md +5 -3
  39. package/package.json +1 -1
  40. package/render/onboarding.cjs +6 -3
  41. package/render/render.cjs +14 -6
  42. package/rules/30-folder-index-is-part-of-the-change.md +2 -2
  43. package/rules/README.md +2 -0
package/CHANGELOG.md CHANGED
@@ -2,10 +2,46 @@
2
2
 
3
3
  All notable changes to this repo. Format after [Keep a Changelog](https://keepachangelog.com/en/2.0.0/) 2.0.0; versions follow [SemVer](https://semver.org/). Dates are the day the change was pushed.
4
4
 
5
- Every entry names the adversarial audit round that produced it where one did. Audits are read-only passes against `AUDIT_BRIEF.md`; every finding is reproduced before its fix.
5
+ Every entry names the adversarial audit round that produced it where one did. Audits are read-only passes against the stated release scope; every finding is reproduced before its fix.
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.5] - 2026-10-29
10
+
11
+ ### Fixed
12
+
13
+ - Audit 2026-10-29: find Claude Code sessions for project paths with spaces, dots and underscores while retaining legacy folder names.
14
+ - Audit 2026-10-29: skip whole messages and Codex memory notes that match conservative secret patterns, reporting only the skip count.
15
+ - Audit 2026-10-29: apply the 2,000-character message cap to Codex memory notes, retaining private-term filtering and the 20-file cap.
16
+ - Audit 2026-10-29: disclose global Codex memory scope and secret skips in consent, and document both project and global private lists.
17
+ - Audit 2026-10-29: preserve intra-word underscores in read-first filenames while escaping hostile Markdown.
18
+ - Audit 2026-10-29: refuse local notes paths containing .git, .github or node_modules segments, ignoring case.
19
+ - Audit 2026-10-29: remove the uninstalled folder-template path from rendered home files and refresh all three examples.
20
+ - Audit 2026-10-29: register the project session-start hook through CLAUDE_PROJECT_DIR so it runs from subfolders, and explain user-level absolute paths.
21
+ - Audit 2026-10-29: align memory status, global learning help, level errors, AI target contribution steps and symlink guidance with supported behaviour; remove the inaccessible audit-brief citation.
22
+ - Audit 2026-10-29: warn that profile and off-limits names enter home files that may be committed.
23
+ - Audit 2026-10-29: use short temporary bases for session-path fixtures so deep TMPDIR paths do not cause false failures.
24
+
25
+ ## [0.8.4] - 2026-10-28
26
+
27
+ ### Added
28
+
29
+ - `--global` applies a level-1 profile across Claude Code, Codex and Gemini CLI projects, with byte-preserving marked blocks, safe uninstall and shared atomic rollback (#29).
30
+
31
+ ### Changed
32
+
33
+ - Levels 1 and 2 render the Core 5 rules; level 3 keeps all eleven and editable rule sources. Untouched older generated files refresh through recorded ownership; edited files stay for review (#33).
34
+
35
+ ### Fixed
36
+
37
+ - The 0.8.4 follow-up audit adds the Windows `USERPROFILE` fallback and home-free project AI defaults, preserves outside edits when uninstalling adopted pre-existing targets, and checks Markdown links after blank lines and escaped backticks.
38
+ - The 0.8.4 follow-up audit fixes bound Claude and Codex session reads to contenders for the newest 20, validate and clamp message timestamps to file mtime, refuse foreign global blocks and invalid HOME values before writes, adopt explicitly re-rendered Core 5 upgrades, and keep code examples containing HTML comment openers from hiding later Markdown links.
39
+ - Session learning selects the newest 20 usable sessions by latest message timestamp across all sources, including legacy Gemini logs, with file mtime used only when a session has no valid timestamp (#38).
40
+ - Digest removal documentation now agrees with recorded-hash ownership and preserves edited or unrecorded files (#39).
41
+ - Markdown link checking strips nested and unterminated HTML comments completely (CodeQL `js/incomplete-multi-character-sanitization`).
42
+ - Security reporting links directly to private advisories and states the existing acknowledgement and fix windows (Scorecard Security-Policy).
43
+ - Publishing uses Node 24 and checks bundled npm is at least 11.5.1, replacing the mutable global npm install while retaining the pinned setup action (Scorecard Pinned-Dependencies).
44
+
9
45
  ## [0.8.3] - 2026-10-19
10
46
 
11
47
  ### Changed
@@ -311,7 +347,9 @@ Thirteen issues (#3 to #15) filed against `5972b32` by an independent installati
311
347
  - Installer: safe destination resolution, strict options, duplicate `--ai` refused, `--dir` created one level at a time.
312
348
  - Harness: exact exit codes, adversarial fixtures, fault injection for the rollback path.
313
349
 
314
- [Unreleased]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.3...HEAD
350
+ [Unreleased]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.5...HEAD
351
+ [0.8.5]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.4...v0.8.5
352
+ [0.8.4]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.3...v0.8.4
315
353
  [0.8.3]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.2...v0.8.3
316
354
  [0.8.2]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.1...v0.8.2
317
355
  [0.8.1]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.0...v0.8.1
package/CONTRIBUTING.md CHANGED
@@ -10,7 +10,7 @@ Contributions are welcome: a **new AI target**, a **notes tool**, an **example u
10
10
  ## Running the checks
11
11
 
12
12
  ```bash
13
- npm test # sh test/run.sh: 98 checks, exact exit codes, Linux and macOS
13
+ npm test # sh test/run.sh: 99 checks, exact exit codes, Linux and macOS
14
14
  node test/rollback.test.js "$(mktemp -d)" # after copying examples/freelance-illustrator into it
15
15
  node check/gate.cjs --self-test
16
16
  ```
@@ -26,7 +26,7 @@ The privacy gate (`check/gate.cjs` against a real list) needs a local `check/for
26
26
  ## Adding a notes tool or an AI target
27
27
 
28
28
  - A notes tool is ONE entry in the `TOOL` table at the top of `render/onboarding.cjs` (`kind`, `label`, `name`, `reach`, `posture`); the interview option, the validation and the write section all derive from it. Then a row in `docs/companions.md`, and an installer hint in `bin/agent-personalizer.js` if the tool needs one. Check 60 in the harness iterates every option; add yours to the right loop. Check 74 asserts the interview options equal the table's keys.
29
- - An AI target is an entry in `render/targets.json` plus a row in `docs/paste-guide.md`. If it has a binding, add `binding:<name>` blocks to the rules that need one; unknown binding names are refused.
29
+ - An AI target needs an entry in `render/targets.json`, a row in `docs/paste-guide.md`, and updates to the hardcoded AI lists: `AIS` and `AI_LABEL` in `bin/agent-personalizer.js`, the supported targets in `bin/global.cjs`, the learning and contract target lists in `render/render.cjs`, and `SOURCE` in `bin/learn.cjs`. Set the target's supported modes and local session source where applicable. If it has a binding, add `binding:<name>` blocks to the rules that need one; unknown binding names are refused.
30
30
 
31
31
  ## Pull requests
32
32
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # agent-personalizer
2
2
 
3
- [![npm](https://img.shields.io/npm/v/agent-personalizer.svg)](https://www.npmjs.com/package/agent-personalizer) [![harness](https://github.com/aunysillyme/agent-personalizer/actions/workflows/harness.yml/badge.svg)](https://github.com/aunysillyme/agent-personalizer/actions/workflows/harness.yml) [![release](https://img.shields.io/github/v/tag/aunysillyme/agent-personalizer?label=release)](https://github.com/aunysillyme/agent-personalizer/blob/main/CHANGELOG.md) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
3
+ [![npm](https://img.shields.io/npm/v/agent-personalizer.svg)](https://www.npmjs.com/package/agent-personalizer) [![harness](https://github.com/aunysillyme/agent-personalizer/actions/workflows/harness.yml/badge.svg)](https://github.com/aunysillyme/agent-personalizer/actions/workflows/harness.yml) [![release](https://img.shields.io/github/v/tag/aunysillyme/agent-personalizer?label=release)](https://github.com/aunysillyme/agent-personalizer/blob/main/CHANGELOG.md) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/aunysillyme/agent-personalizer/badge)](https://scorecard.dev/viewer/?uri=github.com/aunysillyme/agent-personalizer)
4
4
 
5
5
  **Every AI you use gets the same profile and the rules it can carry:** Claude Code, Codex, Cursor, Gemini CLI and ChatGPT, rendered from one source and kept in sync.
6
6
 
@@ -64,9 +64,9 @@ The first install asks for a folder if `--dir` is missing, then which AIs you us
64
64
 
65
65
  | Level | What you get |
66
66
  |---|---|
67
- | **1. Profile and home files** | The profile, onboarding and target-specific instructions for the AIs you pick. |
67
+ | **1. Profile and home files** | The profile, onboarding and five core rules for the AIs you pick. |
68
68
  | **2. Dynamic docs** | Everything above, plus local notes templates maintained under your writing policy. Cloud notes tools use connector pointers. |
69
- | **3. Mechanisms** | Everything above, plus local rule sources, the renderer, drift check, hook and forbidden-string gate. |
69
+ | **3. Mechanisms** | All eleven rules, plus editable rule sources, the renderer, drift check, hook and forbidden-string gate. |
70
70
 
71
71
  For a headless install with defaults:
72
72
 
@@ -74,15 +74,25 @@ For a headless install with defaults:
74
74
  npx agent-personalizer --dir . --ai claude,agents --level 1 --yes --defaults
75
75
  ```
76
76
 
77
+ For every project, install one global level-1 profile:
78
+
79
+ ```bash
80
+ npx agent-personalizer --global --ai claude,agents,gemini --yes
81
+ ```
82
+
83
+ The source lives in `~/.agent-personalizer/`; marked blocks go to `~/.claude/CLAUDE.md`, `~/.codex/AGENTS.md` and `~/.gemini/GEMINI.md`. User text outside the blocks stays byte for byte. `--global` supports those three targets and level 1; it excludes `--dir`. Re-run with `--global`, learn across all projects with `learn --global`, and remove owned global content with `--global --uninstall`. See [global installation](docs/install.md#every-project-with-one-profile).
84
+
85
+ Levels 1 and 2 carry the Core 5: read the profile first, evidence before assertion, output style, act or ask, and ask before it repeats. Level 3 retains all eleven, with each target's existing surface and signature selection.
86
+
77
87
  Node 22 or 24 (active LTS) is recommended; 18 or later runs. Published on npm with provenance. [Installation](docs/install.md) covers scripted answers, every flag, notes tools and manual copying.
78
88
 
79
- The tool runs locally after `npx` fetches the package. The installer and renderer make no network calls and send no telemetry. Writes stay inside the folder you name, with edited files preserved and named.
89
+ The tool runs locally after `npx` fetches the package. The installer and renderer make no network calls and send no telemetry. Project writes stay inside the folder you name; global writes use the profile and selected home paths above. Edited source files are preserved and named.
80
90
 
81
91
  ## Privacy
82
92
 
83
93
  With your yes, learning reads up to 20 recent sessions kept by your selected Claude Code, Codex or Gemini CLI apps, plus Codex memory notes. It keeps typed messages, drops AI replies and tool output, and saves one local `.agent-personalizer/digest.md` ignored by git. The terminal lists files and counts, never message text. Your AI reads the digest, so its contents go to that provider again, like anything you paste in.
84
94
 
85
- Reuse only history you are allowed to share. Past sessions can include other people's details; put their names or other private terms in `check/forbidden.local.txt` before accepting. Check your agreement for work or client accounts. `npx agent-personalizer learn --forget` deletes the digest, and uninstall removes it too; both leave your AI apps' history alone. agent-personalizer is not affiliated with Anthropic, OpenAI or Google, and their saved formats can change. See [learning and privacy](docs/learning.md).
95
+ Reuse only history you are allowed to share. Past sessions can include other people's details; put their names or other private terms in `check/forbidden.local.txt` before accepting. Check your agreement for work or client accounts. `npx agent-personalizer learn --forget` deletes the digest, and uninstall removes unchanged recorded digest files; both leave your AI apps' history alone. agent-personalizer is not affiliated with Anthropic, OpenAI or Google, and their saved formats can change. See [learning and privacy](docs/learning.md).
86
96
 
87
97
  ## Keep it in sync
88
98
 
@@ -167,11 +177,11 @@ Re-run `npx agent-personalizer --dir . --ai claude,agents --level 3 --yes --defa
167
177
 
168
178
  ### How do I uninstall agent-personalizer and keep my notes?
169
179
 
170
- Preview with `npx agent-personalizer --uninstall --dir . --dry`, then run `npx agent-personalizer --uninstall --dir .`. Edited files, user-written notes and a `LEARNED.md` with entries stay; the local digest is removed and untouched files return byte for byte.
180
+ Preview with `npx agent-personalizer --uninstall --dir . --dry`, then run `npx agent-personalizer --uninstall --dir .`. Edited files, user-written notes and a `LEARNED.md` with entries stay; unchanged recorded digest files are removed and untouched files return byte for byte.
171
181
 
172
182
  ## Uninstall
173
183
 
174
- Preview with --uninstall --dry. Removal compares recorded install hashes, keeps edited files, notes and a `LEARNED.md` with entries, removes the local digest, and lists any hook registration you must remove.
184
+ Preview with --uninstall --dry. Removal compares recorded install hashes, keeps edited files, notes and a `LEARNED.md` with entries, removes unchanged recorded digest files, and lists any hook registration you must remove.
175
185
 
176
186
  ```bash
177
187
  npx agent-personalizer --uninstall --dir . --dry
@@ -201,7 +211,7 @@ Contributions are welcome: a new AI target, a notes tool, an example user, or a
201
211
 
202
212
  Pull requests are accepted under the [contributor license agreement](CLA.md); the checkbox in the pull request template records your agreement.
203
213
 
204
- The harness (`test/run.sh: 98 checks`) tests exact exit codes and adversarial fixtures. The real forbidden-list check stays local and prints a skip when the private list is absent.
214
+ The harness (`test/run.sh: 99 checks`) tests exact exit codes and adversarial fixtures. The real forbidden-list check stays local and prints a skip when the private list is absent.
205
215
 
206
216
  ## License
207
217
 
package/RELEASING.md CHANGED
@@ -13,7 +13,7 @@ Maintainer notes. Follow the steps below for version sites, rendering, checks an
13
13
 
14
14
  **Verify.** `npm view agent-personalizer@X.Y.Z version` prints `X.Y.Z` (query the exact version: the bare `npm view agent-personalizer version` can lag a minute behind the run), and `https://registry.npmjs.org/-/npm/v1/attestations/agent-personalizer@X.Y.Z` returns a Sigstore bundle. In a fresh temp dir, `npx --yes agent-personalizer@X.Y.Z --version` prints the new version.
15
15
 
16
- **How `publish.yml` works.** Manual `workflow_dispatch` with the tag as its input, live since 0.4.1. 0.4.0 was published by hand from the tag checkout by a logged-in maintainer (`npm publish --access public`, no provenance is possible from a laptop), because npm only lets a trusted publisher be configured in the settings of a package that already exists. The job resolves the input through `refs/tags/` and checks out that commit by SHA, so a branch with a tag-like name cannot be published; the tag must equal the `package.json` version; it upgrades npm first (trusted publishing needs npm 11.5.1 or later and Node 22 bundles 10.x), runs the harness, then `npm publish --provenance --access public` with `id-token: write`. No npm token is stored anywhere. The trusted publisher on npm is GitHub Actions, this repository, workflow file `publish.yml`, direct publish allowed.
16
+ **How `publish.yml` works.** Manual `workflow_dispatch` with the tag as its input, live since 0.4.1. 0.4.0 was published by hand from the tag checkout by a logged-in maintainer (`npm publish --access public`, no provenance is possible from a laptop), because npm only lets a trusted publisher be configured in the settings of a package that already exists. The job resolves the input through `refs/tags/` and checks out that commit by SHA, so a branch with a tag-like name cannot be published; the tag must equal the `package.json` version; it runs on Node 24 and fails unless the bundled npm is 11.5.1 or later (the trusted-publishing minimum; no global npm install, since 0.8.4), runs the harness, then `npm publish --provenance --access public` with `id-token: write`. No npm token is stored anywhere. The trusted publisher on npm is GitHub Actions, this repository, workflow file `publish.yml`, direct publish allowed.
17
17
 
18
18
  **Two things GitHub will not tell you.** A workflow file it cannot parse is dropped silently: `gh workflow run` says the workflow has no `workflow_dispatch` trigger, and the workflow list shows the file path where its name should be. It happened here once over an unquoted `: ` in a step name; the harness now parses both workflow files. This guide ships in the tarball so its offline links work. Workflow-only changes can land without a package release.
19
19
 
package/SECURITY.md CHANGED
@@ -4,16 +4,18 @@ This is a small local tool: it reads your files, writes files into a folder you
4
4
 
5
5
  ## Reporting a vulnerability
6
6
 
7
- Use GitHub's private vulnerability reporting on this repository (Security tab → "Report a vulnerability"). That opens a private advisory only the maintainer can see. Please do not open a public issue for anything that could let an installer or renderer write outside the folder the user named, read a file it should not, or let `check/forbidden.local.txt` reach a commit.
7
+ Use [GitHub's private vulnerability reporting](https://github.com/aunysillyme/agent-personalizer/security/advisories/new) on this repository (Security tab → "Report a vulnerability"). That opens a private advisory only the maintainer can see. Please do not open a public issue for anything that could let an installer or renderer write outside the folder the user named, read a file it should not, or let `check/forbidden.local.txt` reach a commit.
8
8
 
9
9
  Report a leak of session data through that private route too; describe the reproduction with invented messages and keep real session text out of the report.
10
10
 
11
11
  You will get an acknowledgement within 7 days and a fix or a reasoned "won't fix" within 30. Credit is given in the changelog unless you ask otherwise.
12
12
 
13
+ Disclosure timeline: allow the 7-day acknowledgement and 30-day fix window before coordinated public disclosure.
14
+
13
15
  ## Scope
14
16
 
15
17
  In scope: `bin/`, including session reading, learning and removal, `render/`, `check/gate.cjs`, `hooks/`, the templates and the harness. Out of scope: the AI products this repo writes files for, and the companion tools it links to (report those to their own projects).
16
18
 
17
19
  ## What is already done
18
20
 
19
- Every release passes an adversarial read-only audit (see `CHANGELOG.md`, each entry names its round) and a 98-check harness with exact exit codes, on Linux and macOS in CI. The deferred residuals are stated in the code headers: TOCTOU between check and write, unicode look-alikes in the gate, the named `--dir` being followed once via realpath, and a hard process kill between two renames. On Windows, `O_NOFOLLOW` is unavailable to the flag the uninstaller opens tracked files with; nothing depends on it there, because the delete loop re-probes every path with `lstat` immediately before each unlink, so no destructive path exists without it.
21
+ Every release passes an adversarial read-only audit (see `CHANGELOG.md`, each entry names its round) and a 99-check harness with exact exit codes, on Linux and macOS in CI. The deferred residuals are stated in the code headers: TOCTOU between check and write, unicode look-alikes in the gate, the named `--dir` being followed once via realpath, and a hard process kill between two renames. On Windows, `O_NOFOLLOW` is unavailable to the flag the uninstaller opens tracked files with; nothing depends on it there, because the delete loop re-probes every path with `lstat` immediately before each unlink, so no destructive path exists without it.
@@ -10,7 +10,7 @@
10
10
  const fs = require('fs');
11
11
  const path = require('path');
12
12
  const readline = require('readline');
13
- const os = require('os');
13
+ const { resolveHome } = require('./home.cjs');
14
14
  const crypto = require('crypto');
15
15
  const { execFileSync } = require('child_process');
16
16
  const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
@@ -30,19 +30,23 @@ let committing = false;
30
30
  function die(msg) { if (committing) throw new markers.Refusal(msg); console.error(`agent-personalizer: ${msg}`); process.exit(2); }
31
31
 
32
32
  const VALUE_OPTS = ['--dir', '--ai', '--level', '--answers'];
33
- const FLAG_OPTS = ['--forget', '--all-projects', '--yes', '--defaults', '--quick', '--full', '--uninstall', '--dry', '--help', '--version', '-h', '-v'];
33
+ const FLAG_OPTS = ['--global', '--forget', '--all-projects', '--yes', '--defaults', '--quick', '--full', '--uninstall', '--dry', '--help', '--version', '-h', '-v'];
34
34
  const USAGE = `agent-personalizer ${require(path.join(PKG, 'package.json')).version}
35
35
 
36
36
  npx agent-personalizer [--dir <folder>] [--ai claude,agents,gemini,chatgpt,prompt] [--level 1|2|3]
37
37
  [--answers <file.json> | --answers - | --defaults] [--full] [--yes]
38
38
  [--help | -h] [--version | -v]
39
+ npx agent-personalizer --global [--ai claude,agents,gemini] [--yes]
40
+ npx agent-personalizer --global --uninstall [--dry]
39
41
  npx agent-personalizer --uninstall --dir <folder> [--dry]
40
42
 
41
43
  npx agent-personalizer learn [--dir <folder>] [--all-projects] [--yes]
44
+ npx agent-personalizer learn --global [--yes]
42
45
  npx agent-personalizer learn --forget [--dir <folder>]
43
46
 
44
47
  First interactive install: choose your AIs, then choose whether to read your recent sessions.
45
48
  Saved installs ask nothing and keep their AIs, level and answers unless you give replacements.
49
+ --global level-1 profile in ~/.agent-personalizer, applied across projects; excludes --dir.
46
50
  --full accepted for older commands; the interview is gone.
47
51
  --quick accepted for older commands; the interview is gone.
48
52
  --answers a JSON file of answers, or "-" to read JSON from stdin. Saved legacy keys stay valid.
@@ -166,7 +170,88 @@ function resolveDestination(dir) {
166
170
  return { requested, realExisting, missing, root: path.join(realExisting, ...missing) };
167
171
  }
168
172
 
173
+
174
+ // One transaction for project and global plans: snapshot before writes, replace atomically, restore on failure.
175
+ async function commitPlan(root, { writes, removals = [], outputPaths, prepare, finalize }) {
176
+ for (const rel of outputPaths) {
177
+ let parent = path.posix.dirname(rel);
178
+ while (parent !== '.') {
179
+ if (outputPaths.has(parent)) die(`${parent}: install path is both a file and a directory; nothing was written`);
180
+ parent = path.posix.dirname(parent);
181
+ }
182
+ }
183
+ const saved = new Map(), newDirectories = new Set();
184
+ for (const rel of outputPaths) {
185
+ const destination = probe(root, rel);
186
+ if (destination.exists) {
187
+ const info = fs.lstatSync(destination.full);
188
+ if (!info.isFile()) die(`${rel} is not a regular file; nothing was written`);
189
+ saved.set(rel, { bytes: fs.readFileSync(destination.full), mode: info.mode & 0o777, dev: info.dev, ino: info.ino });
190
+ } else saved.set(rel, null);
191
+ let parent = path.posix.dirname(rel);
192
+ while (parent !== '.') {
193
+ if (!probe(root, parent).exists) newDirectories.add(parent);
194
+ parent = path.posix.dirname(parent);
195
+ }
196
+ let ancestor = path.dirname(destination.full);
197
+ while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor);
198
+ try { fs.accessSync(ancestor, fs.constants.W_OK); } catch (_) { die(`${rel}: parent is not writable; nothing was written`); }
199
+ }
200
+ if (prepare) prepare(newDirectories);
201
+ const replace = (rel, bytes, mode) => {
202
+ const destination = safeDest(root, rel);
203
+ const tmp = path.join(path.dirname(destination.full), `.${path.basename(rel)}.${crypto.randomBytes(8).toString('hex')}.agent-personalizer.tmp`);
204
+ try {
205
+ fs.writeFileSync(tmp, bytes, { flag: 'wx', ...(mode === undefined ? {} : { mode }) });
206
+ if (mode !== undefined) fs.chmodSync(tmp, mode);
207
+ probe(root, rel);
208
+ fs.renameSync(tmp, destination.full);
209
+ } finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); }
210
+ };
211
+ const assertSaved = rel => {
212
+ const destination = probe(root, rel), before = saved.get(rel);
213
+ if (!!before !== destination.exists) die(`${rel} changed during preflight; nothing was written`);
214
+ if (before) {
215
+ const info = fs.lstatSync(destination.full);
216
+ if (info.dev !== before.dev || info.ino !== before.ino || !fs.readFileSync(destination.full).equals(before.bytes)) die(`${rel} changed during preflight; nothing was written`);
217
+ }
218
+ };
219
+ committing = true;
220
+ const touched = new Set();
221
+ try {
222
+ for (const rel of outputPaths) assertSaved(rel);
223
+ for (const p of removals) { assertSaved(p.rel); fs.unlinkSync(probe(root, p.rel).full); touched.add(p.rel); if (p.report) console.log(p.report); }
224
+ for (const p of writes) {
225
+ assertSaved(p.rel);
226
+ touched.add(p.rel);
227
+ const mode = p.rel === 'hooks/claude-code/session-start.sh' ? 0o755 : saved.get(p.rel)?.mode;
228
+ replace(p.rel, p.bytes, mode);
229
+ if (p.report) console.log(p.report);
230
+ }
231
+ // Include renderer outputs in rollback even when it committed before reporting a failure.
232
+ for (const rel of outputPaths) touched.add(rel);
233
+ if (finalize) await finalize();
234
+ } catch (e) {
235
+ const incomplete = [];
236
+ for (const rel of [...touched].reverse()) {
237
+ try {
238
+ const before = saved.get(rel), destination = probe(root, rel);
239
+ if (before) replace(rel, before.bytes, before.mode);
240
+ else if (destination.exists) fs.unlinkSync(destination.full);
241
+ } catch (failure) { incomplete.push(`${rel}: ${failure.message}`); }
242
+ }
243
+ for (const rel of [...newDirectories].sort((a, b) => b.split('/').length - a.split('/').length)) {
244
+ try { const destination = probe(root, rel); if (destination.exists && fs.readdirSync(destination.full).length === 0) fs.rmdirSync(destination.full); }
245
+ catch (failure) { incomplete.push(`${rel}/: ${failure.message}`); }
246
+ }
247
+ console.error(incomplete.length ? `agent-personalizer: ROLLBACK INCOMPLETE\n${incomplete.join('\n')}` : 'agent-personalizer: install failed; every changed file was restored');
248
+ throw e;
249
+ } finally { committing = false; }
250
+
251
+ }
252
+
169
253
  async function main() {
254
+ if (ARGS['--global']) return require('./global.cjs').run({ args: ARGS, commitPlan, probe, readConfig, ask });
170
255
  if (ARGS.command === 'learn') {
171
256
  for (const opt of ['--ai', '--level', '--answers', '--defaults', '--quick', '--full', '--uninstall', '--dry'])
172
257
  if (opt in ARGS) die(`${opt} is not a learn option`);
@@ -203,11 +288,14 @@ async function main() {
203
288
  console.log('\nWhich AIs do you use? Comma-separated from:');
204
289
  for (const k of AIS) console.log(` ${k.padEnd(8)} ${AI_LABEL[k]}`);
205
290
  // Existence is the only inspection of app folders permitted before consent.
206
- const found = [['.claude', 'claude'], ['.codex', 'agents'], ['.gemini', 'gemini']]
207
- .filter(([folder]) => fs.existsSync(path.join(os.homedir(), folder))).map(([, ai]) => ai);
291
+ let home;
292
+ try { home = resolveHome(); }
293
+ catch (e) { if (!(e instanceof markers.Refusal)) throw e; }
294
+ const found = home ? [['.claude', 'claude'], ['.codex', 'agents'], ['.gemini', 'gemini']]
295
+ .filter(([folder]) => fs.existsSync(path.join(home, folder))).map(([, ai]) => ai) : [];
208
296
  ais = await ask('\nAIs', ais || (found.length ? found.join(',') : 'claude,agents'));
209
297
  }
210
- if (!/^[1-4]$/.test(String(level))) die('level must be exactly 1, 2 or 3');
298
+ if (!/^[1-4]$/.test(String(level))) die('level must be 1, 2 or 3 (4 is accepted as 3)');
211
299
  level = Number(level);
212
300
  if (level === 4) console.log('note: --level 4 installs exactly what --level 3 installs. For model routing, see https://github.com/aunysillyme/model-orchestrator');
213
301
  const targets = String(ais || '').split(',').map(s => s.trim()).filter(Boolean);
@@ -279,7 +367,7 @@ async function main() {
279
367
  const previousBase = prevAnswers ? onboarding.baseFor(prevAnswers) : null;
280
368
  const previousNotesExists = previousBase && !!probe(root, `${previousBase}/README.md`).exists;
281
369
  const previousNotesScaffolded = prevAnswers && onboarding.kindOf(prevAnswers) !== 'cloud' && ((cfg.level || 1) >= 2 || previousNotesExists);
282
- const previousPlan = prevAnswers ? installPlan({ answers: prevAnswers, level: Math.min(cfg.level || 1, 3), targets: cfg.targets || [], notesScaffolded: previousNotesScaffolded }).plan : [];
370
+ const previousPlan = prevAnswers ? installPlan({ answers: prevAnswers, level: Math.min(cfg.level || 1, 3), targets: cfg.targets || [], notesScaffolded: previousNotesScaffolded, legacyRules: cfg.ruleSet !== 'core-5' }).plan : [];
283
371
 
284
372
  // ---- PREFLIGHT: refuse now, with nothing written, everything the renderer would refuse later ----
285
373
  for (const p of plan) {
@@ -298,6 +386,12 @@ async function main() {
298
386
  finally { markers.DIE_THROWS = false; }
299
387
  const TARGETS = JSON.parse(fs.readFileSync(path.join(PKG, 'render', 'targets.json'), 'utf8'));
300
388
  const preservedTargets = new Set(cfg.preservedTargets || []);
389
+ // A smaller rule set refreshes only an untouched older generated file. Keep an edited
390
+ // older target until the user explicitly re-renders or restores its recorded bytes.
391
+ const keptRuleTargets = new Set();
392
+ const adoptedRuleTargets = new Set();
393
+ const coreUpgrade = cfgExists && effectiveLevel < 3 && cfg.ruleSet !== 'core-5';
394
+
301
395
  for (const t of allTargets) {
302
396
  const rel = TARGETS[t].file;
303
397
  const { full, exists } = probe(root, rel);
@@ -343,6 +437,27 @@ async function main() {
343
437
  if (userAction === 'keep' && notesScaffolded && !current.includes(`\`${base}/README.md\``)) staleNotesInUser = true;
344
438
  }
345
439
 
440
+ const profileSource = ['keep', 'conflict'].includes(userAction) ? fs.readFileSync(user.full, 'utf8') : onboarding.renderUser(answers, { notesScaffolded, entries });
441
+ let currentRenders;
442
+ for (const t of allTargets) {
443
+ if (t === 'onboarding' || (!coreUpgrade && !(cfg.keptRuleTargets || []).includes(t))) continue;
444
+ const rel = TARGETS[t].file, destination = probe(root, rel), hash = recordedHash(cfg, rel);
445
+ if (destination.exists && hash && sha256(fs.readFileSync(destination.full)) !== hash) {
446
+ currentRenders ||= markers.renderedContents(root, { ...cfg, targets: allTargets, level: effectiveLevel, ruleSet: 'core-5', onboarding: answers }, { profileSource, learned: entries });
447
+ const current = fs.readFileSync(destination.full, 'utf8');
448
+ if (markers.markerState(current, rel).kind === 'one' && markers.between(current, rel) === currentRenders.find(entry => entry.key === t).block) {
449
+ // Adoption always marks the target preserved, so record the block hash uninstall compares for preserved files.
450
+ installedHashes[rel] = sha256(Buffer.from(markers.between(current, rel)));
451
+ adoptedRuleTargets.add(t);
452
+ preservedTargets.add(t);
453
+ continue;
454
+ }
455
+ keptRuleTargets.add(t);
456
+ const quote = value => `'${value.replace(/'/g, "'\\''")}'`;
457
+ console.log(`kept ${rel} (edited older generated file; re-render with: node ${quote(path.join(PKG, 'render/render.cjs'))} --dir ${quote(root)} --targets ${t})`);
458
+ }
459
+ }
460
+
346
461
  // Previous answers identify the exact installer lines to migrate. Each unchanged line is
347
462
  // replaced or removed on its own; all other outside-marker bytes stay exactly as read.
348
463
  const upgrades = [];
@@ -351,6 +466,7 @@ async function main() {
351
466
  return ms.kind === 'one' ? text.slice(0, ms.bStart) + text.slice(ms.eEnd) : text;
352
467
  };
353
468
  for (const name of ['CLAUDE.md', 'AGENTS.md']) {
469
+ if (keptRuleTargets.has(name === 'CLAUDE.md' ? 'claude' : 'agents') || adoptedRuleTargets.has(name === 'CLAUDE.md' ? 'claude' : 'agents')) continue;
354
470
  const prior = previousPlan.find(p => p.rel === name);
355
471
  const next = plan.find(p => p.rel === name);
356
472
  if (!prior || !next) continue;
@@ -464,83 +580,17 @@ async function main() {
464
580
  outputPaths.add(target.file);
465
581
  for (const rel of Object.values(target.boxFiles || {})) outputPaths.add(rel);
466
582
  }
467
- for (const rel of outputPaths) {
468
- let parent = path.posix.dirname(rel);
469
- while (parent !== '.') {
470
- if (outputPaths.has(parent)) die(`${parent}: install path is both a file and a directory; nothing was written`);
471
- parent = path.posix.dirname(parent);
472
- }
473
- }
474
- const saved = new Map(), newDirectories = new Set();
475
- for (const rel of outputPaths) {
476
- const destination = probe(root, rel);
477
- if (destination.exists) {
478
- const info = fs.lstatSync(destination.full);
479
- if (!info.isFile()) die(`${rel} is not a regular file; nothing was written`);
480
- saved.set(rel, { bytes: fs.readFileSync(destination.full), mode: info.mode & 0o777, dev: info.dev, ino: info.ino });
481
- } else saved.set(rel, null);
482
- let parent = path.posix.dirname(rel);
483
- while (parent !== '.') {
484
- if (!probe(root, parent).exists) newDirectories.add(parent);
485
- parent = path.posix.dirname(parent);
486
- }
487
- let ancestor = path.dirname(destination.full);
488
- while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor);
489
- try { fs.accessSync(ancestor, fs.constants.W_OK); } catch (_) { die(`${rel}: parent is not writable; nothing was written`); }
490
- }
491
- for (const rel of newDirectories) createdDirectories.add(rel);
492
- cfg = { ...cfg, targets: allTargets, level: installedLevel, onboarding: onboarding.sparse(answers), preservedTargets: [...preservedTargets].filter(t => allTargets.includes(t)), installed: installedHashes, createdDirectories: [...createdDirectories].sort(), toolingVersion, toolingVersions };
493
- writes.push({ rel: '.agent-personalizer.json', bytes: Buffer.from(JSON.stringify(cfg, null, 2) + '\n'), report: `${cfgExists ? 'update' : 'wrote '} .agent-personalizer.json (onboarding: ${answersSource})` });
494
- const replace = (rel, bytes, mode) => {
495
- const destination = safeDest(root, rel);
496
- const tmp = path.join(path.dirname(destination.full), `.${path.basename(rel)}.${crypto.randomBytes(8).toString('hex')}.agent-personalizer.tmp`);
497
- try {
498
- fs.writeFileSync(tmp, bytes, { flag: 'wx', ...(mode === undefined ? {} : { mode }) });
499
- if (mode !== undefined) fs.chmodSync(tmp, mode);
500
- probe(root, rel);
501
- fs.renameSync(tmp, destination.full);
502
- } finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); }
503
- };
504
- const assertSaved = rel => {
505
- const destination = probe(root, rel), before = saved.get(rel);
506
- if (!!before !== destination.exists) die(`${rel} changed during preflight; nothing was written`);
507
- if (before) {
508
- const info = fs.lstatSync(destination.full);
509
- if (info.dev !== before.dev || info.ino !== before.ino || !fs.readFileSync(destination.full).equals(before.bytes)) die(`${rel} changed during preflight; nothing was written`);
510
- }
511
- };
512
- committing = true;
513
- const touched = new Set();
514
- try {
515
- for (const rel of outputPaths) assertSaved(rel);
516
- for (const p of removals) { assertSaved(p.rel); fs.unlinkSync(probe(root, p.rel).full); touched.add(p.rel); console.log(p.report); }
517
- for (const p of writes) {
518
- assertSaved(p.rel);
519
- touched.add(p.rel);
520
- const mode = p.rel === 'hooks/claude-code/session-start.sh' ? 0o755 : saved.get(p.rel)?.mode;
521
- replace(p.rel, p.bytes, mode);
522
- if (p.report) console.log(p.report);
583
+ await commitPlan(root, { writes, removals, outputPaths,
584
+ prepare(newDirectories) {
585
+ for (const rel of newDirectories) createdDirectories.add(rel);
586
+ cfg = { ...cfg, targets: allTargets, level: installedLevel, ruleSet: 'core-5', keptRuleTargets: [...keptRuleTargets], onboarding: onboarding.sparse(answers), preservedTargets: [...preservedTargets].filter(t => allTargets.includes(t)), installed: installedHashes, createdDirectories: [...createdDirectories].sort(), toolingVersion, toolingVersions };
587
+ writes.push({ rel: '.agent-personalizer.json', bytes: Buffer.from(JSON.stringify(cfg, null, 2) + '\n'), report: `${cfgExists ? 'update' : 'wrote '} .agent-personalizer.json (onboarding: ${answersSource})` });
588
+ },
589
+ async finalize() {
590
+ if (learnRequested) await require('./learn.cjs').learn({ dir: root, consented: true });
591
+ execFileSync(process.execPath, [path.join(PKG, 'render', 'render.cjs'), '--dir', root, '--targets', allTargets.filter(t => !keptRuleTargets.has(t) && !adoptedRuleTargets.has(t)).join(',')], { stdio: 'inherit' });
523
592
  }
524
- // Include renderer outputs in rollback even when it committed before reporting a failure.
525
- for (const rel of outputPaths) touched.add(rel);
526
- if (learnRequested) await require('./learn.cjs').learn({ dir: root, consented: true });
527
- execFileSync(process.execPath, [path.join(PKG, 'render', 'render.cjs'), '--dir', root, '--targets', allTargets.join(',')], { stdio: 'inherit' });
528
- } catch (e) {
529
- const incomplete = [];
530
- for (const rel of [...touched].reverse()) {
531
- try {
532
- const before = saved.get(rel), destination = probe(root, rel);
533
- if (before) replace(rel, before.bytes, before.mode);
534
- else if (destination.exists) fs.unlinkSync(destination.full);
535
- } catch (failure) { incomplete.push(`${rel}: ${failure.message}`); }
536
- }
537
- for (const rel of [...newDirectories].sort((a, b) => b.split('/').length - a.split('/').length)) {
538
- try { const destination = probe(root, rel); if (destination.exists && fs.readdirSync(destination.full).length === 0) fs.rmdirSync(destination.full); }
539
- catch (failure) { incomplete.push(`${rel}/: ${failure.message}`); }
540
- }
541
- console.error(incomplete.length ? `agent-personalizer: ROLLBACK INCOMPLETE\n${incomplete.join('\n')}` : 'agent-personalizer: install failed; every changed file was restored');
542
- throw e;
543
- } finally { committing = false; }
593
+ });
544
594
 
545
595
  require('./git-exclude.cjs').protect(root);
546
596
 
@@ -86,7 +86,7 @@ function protect(root, log = console.log) {
86
86
  const tracked = git(where.top, ['ls-files', '--', ...PRIVATE.map(p => where.prefix ? `${where.prefix}/${p}` : p)]).out.split('\n').filter(Boolean);
87
87
  if (tracked.length) log(`WARNING: git already tracks ${tracked.join(', ')}; an exclude cannot hide a tracked file. Run git rm --cached on it if it should stay private.`);
88
88
  const shared = SHARED_PERSONAL.filter(p => fs.existsSync(path.join(root, p)));
89
- if (shared.length) log(`NOTE: ${shared.join(', ')} carry your profile, entries or answers and stay committable, since projects often share them. Review them before committing.`);
89
+ if (shared.length) log(`NOTE: ${shared.join(', ')} carry your profile, entries and answers, including names under off-limits. CLAUDE.md, AGENTS.md and GEMINI.md may be committed. Review them before committing.`);
90
90
  }
91
91
 
92
92
  function unprotect(root, { dry = false, log = console.log } = {}) {