agent-personalizer 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,22 @@ Every entry names the adversarial audit round that produced it where one did. Au
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.1] - 2026-10-17
10
+
11
+ ### Fixed
12
+
13
+ - Re-render keeps user text outside generated blocks out of whole-file ownership updates and leaves legacy configurations without `installed` on the legacy removal path, so uninstall retains added instructions and removes untouched legacy targets (Codex audit 2026-10-17, F1; agy audit, A3).
14
+ - Local notes paths inside tool-owned paths are refused, `learn` preserves edited or pre-existing `.agent-personalizer/.gitignore` and `digest.md` files without adopting their hashes, and uninstall keeps unrecorded or edited digest-folder files (Codex audit 2026-10-17, F2; agy audit, A5).
15
+ - Renderer ownership configuration writes share target staging and rollback, with clean diagnostics on failure (Codex audit 2026-10-17, F3).
16
+ - Session and Codex memory privacy filtering strips control characters before matching and checks the final text after context removal, including private terms rejoined across newlines, item boundaries or spaces (Codex audit 2026-10-17, F4; agy audit, A1 and A6).
17
+ - ChatGPT exports every declined entry in full and reports overflow; `--strict` refuses over-budget lists before writing (Codex audit 2026-10-17, F5).
18
+ - Render, drift checks and uninstall strip a leading UTF-8 BOM before fence, marker and `LEARNED.md` parsing while preserving it byte for byte on output (Codex audit 2026-10-17, F6; agy audit, A2 and A4).
19
+ - The demo recorder follows the current folder, AI selection and default-No session-consent prompts (Codex audit 2026-10-17, F7).
20
+ - Uninstall restores a pre-existing home file byte for byte: it removes the blank separator line install added along with the block. An untouched `LEARNED.md` template is removed, and `.agent-personalizer.json` is removed when only stripped home files remain (#32).
21
+ - Inside a git repo, install adds `USER.md`, `LEARNED.md`, `.agent-personalizer.json` and the ChatGPT paste files to `.git/info/exclude` in one marked block per install folder, and notes that the home files carry your profile. Uninstall removes the block (#30).
22
+ - Learning reads sessions from the current project by default; `--all-projects` explicitly includes sessions from other projects (#31).
23
+ - The F5 historical-install check skips when its version tags are absent, including in shallow clones, and reports the skip separately from a pass (#34).
24
+
9
25
  ## [0.8.0] - 2026-10-06
10
26
 
11
27
  ### Added
@@ -283,7 +299,8 @@ Thirteen issues (#3 to #15) filed against `5972b32` by an independent installati
283
299
  - Installer: safe destination resolution, strict options, duplicate `--ai` refused, `--dir` created one level at a time.
284
300
  - Harness: exact exit codes, adversarial fixtures, fault injection for the rollback path.
285
301
 
286
- [Unreleased]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.0...HEAD
302
+ [Unreleased]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.1...HEAD
303
+ [0.8.1]: https://github.com/aunysillyme/agent-personalizer/compare/v0.8.0...v0.8.1
287
304
  [0.8.0]: https://github.com/aunysillyme/agent-personalizer/compare/v0.7.2...v0.8.0
288
305
  [0.7.2]: https://github.com/aunysillyme/agent-personalizer/compare/v0.7.1...v0.7.2
289
306
  [0.7.1]: https://github.com/aunysillyme/agent-personalizer/compare/v0.7.0...v0.7.1
package/README.md CHANGED
@@ -166,11 +166,11 @@ Re-run `npx agent-personalizer --dir . --ai claude,agents --level 3 --yes --defa
166
166
 
167
167
  ### How do I uninstall agent-personalizer and keep my notes?
168
168
 
169
- Preview with `npx agent-personalizer --uninstall --dir . --dry`, then run `npx agent-personalizer --uninstall --dir .`. Edited files, user-written notes and `LEARNED.md` stay; the local digest is removed.
169
+ 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.
170
170
 
171
171
  ## Uninstall
172
172
 
173
- Preview with --uninstall --dry. Removal compares recorded install hashes, keeps edited files, notes and `LEARNED.md`, removes the local digest, and lists any hook registration you must remove.
173
+ 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.
174
174
 
175
175
  ```bash
176
176
  npx agent-personalizer --uninstall --dir . --dry
@@ -30,7 +30,7 @@ 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', '--yes', '--defaults', '--quick', '--full', '--uninstall', '--dry', '--help', '--version', '-h', '-v'];
33
+ const FLAG_OPTS = ['--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]
@@ -38,7 +38,7 @@ const USAGE = `agent-personalizer ${require(path.join(PKG, 'package.json')).vers
38
38
  [--help | -h] [--version | -v]
39
39
  npx agent-personalizer --uninstall --dir <folder> [--dry]
40
40
 
41
- npx agent-personalizer learn [--dir <folder>] [--yes]
41
+ npx agent-personalizer learn [--dir <folder>] [--all-projects] [--yes]
42
42
  npx agent-personalizer learn --forget [--dir <folder>]
43
43
 
44
44
  First interactive install: choose your AIs, then choose whether to read your recent sessions.
@@ -49,8 +49,9 @@ const USAGE = `agent-personalizer ${require(path.join(PKG, 'package.json')).vers
49
49
  --defaults accept defaults on first install; a re-run keeps saved answers.
50
50
  --yes scripted first install: needs --dir, --ai and --level. Never reads session history.
51
51
  learn with your yes, write a local digest for up to five evidence-backed questions.
52
+ --all-projects include sessions from projects other than --dir; default reads only --dir.
52
53
  --forget with learn, remove the digest; your AI apps' own history stays as it is.
53
- --uninstall remove unchanged installed files; keep LEARNED.md and edited files.
54
+ --uninstall remove unchanged installed files; keep edited files and LEARNED.md with entries.
54
55
  --dry preview --uninstall without changing files.
55
56
  Levels: 1 profile, onboarding and home file(s); nothing else (the rules render from the package)
56
57
  2 + the notes folder: its README, a weekly session log, a decisions log and an inbox
@@ -169,11 +170,13 @@ async function main() {
169
170
  if (ARGS.command === 'learn') {
170
171
  for (const opt of ['--ai', '--level', '--answers', '--defaults', '--quick', '--full', '--uninstall', '--dry'])
171
172
  if (opt in ARGS) die(`${opt} is not a learn option`);
173
+ if (ARGS['--forget'] && ARGS['--all-projects']) die('--all-projects cannot be used with --forget');
172
174
  if (ARGS['--forget'] && ARGS['--yes']) die('--forget and --yes are exclusive');
173
175
  const learning = require('./learn.cjs');
174
- return ARGS['--forget'] ? learning.forget(arg('--dir', '.')) : learning.learn({ dir: arg('--dir', '.'), yes: !!ARGS['--yes'] });
176
+ return ARGS['--forget'] ? learning.forget(arg('--dir', '.')) : learning.learn({ dir: arg('--dir', '.'), yes: !!ARGS['--yes'], allProjects: !!ARGS['--all-projects'] });
175
177
  }
176
178
  if (ARGS['--forget']) die('--forget needs learn');
179
+ if (ARGS['--all-projects']) die('--all-projects needs learn');
177
180
  if (ARGS['--uninstall']) {
178
181
  if (!ARGS['--dir']) die('--uninstall needs --dir <folder>');
179
182
  for (const opt of ['--ai', '--level', '--answers', '--defaults', '--quick', '--full'])
@@ -360,6 +363,8 @@ async function main() {
360
363
  if (migration.changed) {
361
364
  const why = effectiveLevel >= 3 && (cfg.level || 1) < 3 ? 'rule pointers now name rules/, which this level installs' : 'unchanged installer pointer lines migrated to the new answers';
362
365
  upgrades.push({ rel: name, bytes: Buffer.from(migration.text), report: `update ${name} (${why})` });
366
+ // Only an unchanged owned file can advance its whole-file ownership after migration.
367
+ if (installedHashes[name] === sha256(Buffer.from(current))) installedHashes[name] = sha256(Buffer.from(migration.text));
363
368
  }
364
369
  }
365
370
 
@@ -391,7 +396,10 @@ async function main() {
391
396
  const destination = probe(root, p.rel);
392
397
  const bytes = p.src ? fs.readFileSync(p.src) : Buffer.from(p.text);
393
398
  if (HOME_NAMES.has(p.rel)) {
394
- if (!destination.exists) writes.push({ rel: p.rel, bytes, report: `wrote ${p.rel} (${p.note})` });
399
+ if (!destination.exists) {
400
+ writes.push({ rel: p.rel, bytes, report: `wrote ${p.rel} (${p.note})` });
401
+ installedHashes[p.rel] = sha256(bytes);
402
+ }
395
403
  continue;
396
404
  }
397
405
  if (destination.exists && p.firstOnly) { console.log(`kept ${p.rel} (user-owned)`); continue; }
@@ -534,6 +542,8 @@ async function main() {
534
542
  throw e;
535
543
  } finally { committing = false; }
536
544
 
545
+ require('./git-exclude.cjs').protect(root);
546
+
537
547
  if (interactive && !cfgExists && !learnRequested) console.log('Nothing was read. Run npx agent-personalizer learn any time.');
538
548
 
539
549
  const DOCS = onboarding.DOCS;
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+ // Keep personal outputs out of `git status` when the install folder sits inside a git repo.
3
+ // Lines go in .git/info/exclude (local to this clone, never committed) inside a block marked
4
+ // with the install folder, so re-runs replace the block and uninstall removes exactly it.
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const crypto = require('crypto');
8
+ const { spawnSync } = require('child_process');
9
+
10
+ // Profile, entries, answers and ChatGPT paste copies are personal. Home files (CLAUDE.md,
11
+ // AGENTS.md, GEMINI.md) and AGENT_ONBOARDING.md are often committed on purpose, so they get a
12
+ // warning instead; tooling (rules/, render/, check/, hooks/, .claude/commands/) is shareable.
13
+ const PRIVATE = ['USER.md', 'LEARNED.md', '.agent-personalizer.json', '.agent-personalizer/digest.md', 'chatgpt-custom-instructions.md', 'chatgpt-box1.txt', 'chatgpt-box2.txt'];
14
+ const SHARED_PERSONAL = ['CLAUDE.md', 'AGENTS.md', 'GEMINI.md', 'AGENT_ONBOARDING.md'];
15
+
16
+ function git(cwd, args) {
17
+ const env = { ...process.env };
18
+ for (const name of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR']) delete env[name];
19
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', env });
20
+ return r.error ? { missing: r.error.code === 'ENOENT', code: null, out: '' } : { code: r.status, out: r.stdout || '' };
21
+ }
22
+ function hasDotGit(root) {
23
+ for (let dir = root; ; dir = path.dirname(dir)) {
24
+ if (fs.existsSync(path.join(dir, '.git'))) return true;
25
+ if (path.dirname(dir) === dir) return false;
26
+ }
27
+ }
28
+ // { exclude, top, prefix } when root is a committable folder in a work tree; { warn } when
29
+ // that cannot be decided; null when there is no repo or the whole folder is already ignored.
30
+ function locate(root) {
31
+ const r = git(root, ['rev-parse', '--show-toplevel', '--git-path', 'info/exclude']);
32
+ if (r.code === null) return r.missing && hasDotGit(root) ? { warn: 'git is not on PATH, so .git/info/exclude was not updated' } : null;
33
+ if (r.code !== 0) return null;
34
+ const [top, gitPath] = r.out.split('\n');
35
+ if (!top || !gitPath) return null;
36
+ const prefix = path.relative(fs.realpathSync(top), root).split(path.sep).join('/');
37
+ if (prefix.startsWith('..')) return null;
38
+ if (prefix && git(top, ['check-ignore', '-q', '--', `${prefix}/`]).code === 0) return null;
39
+ return { exclude: path.resolve(root, gitPath), top: fs.realpathSync(top), prefix };
40
+ }
41
+ const pattern = (prefix, rel) => '/' + (prefix ? `${prefix}/${rel}` : rel).replace(/[\\*?[]/g, '\\$&').replace(/ $/, '\\ ');
42
+ const markers = prefix => [`# agent-personalizer begin: ${prefix || '.'} (private outputs; uninstall removes this block)`, `# agent-personalizer end: ${prefix || '.'}`];
43
+
44
+ function readExclude(file) {
45
+ let info;
46
+ try { info = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return ''; throw e; }
47
+ if (!info.isFile()) throw new Error(`${file} is not a regular file`);
48
+ return fs.readFileSync(file, 'utf8');
49
+ }
50
+ // Remove this folder's block, the separator line before it and its terminator.
51
+ function without(text, prefix) {
52
+ const [begin, end] = markers(prefix);
53
+ const lines = text.split('\n');
54
+ const b = lines.indexOf(begin), e = lines.indexOf(end, b + 1);
55
+ if (b === -1 || e === -1) return { text, found: false };
56
+ const from = b > 0 && lines[b - 1] === '' ? b - 1 : b;
57
+ lines.splice(from, e - from + 1);
58
+ return { text: lines.join('\n'), found: true };
59
+ }
60
+ function writeExclude(file, text) {
61
+ fs.mkdirSync(path.dirname(file), { recursive: true });
62
+ const tmp = path.join(path.dirname(file), `.exclude.${crypto.randomBytes(8).toString('hex')}.agent-personalizer.tmp`);
63
+ try { fs.writeFileSync(tmp, text, { flag: 'wx' }); fs.renameSync(tmp, file); }
64
+ finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); }
65
+ }
66
+
67
+ // Never fails the install: any problem is printed as a warning naming the files to protect.
68
+ function protect(root, log = console.log) {
69
+ let where;
70
+ try { where = locate(root); } catch (e) { where = { warn: e.message }; }
71
+ if (!where) return;
72
+ const present = PRIVATE.filter(rel => fs.existsSync(path.join(root, rel)));
73
+ if (where.warn) { log(`WARNING: this folder is inside a git repo and ${where.warn}. Keep ${present.join(', ')} out of commits.`); return; }
74
+ const rel = path.relative(where.top, where.exclude).split(path.sep).join('/');
75
+ try {
76
+ const current = readExclude(where.exclude);
77
+ const base = without(current, where.prefix).text;
78
+ const [begin, end] = markers(where.prefix);
79
+ const block = [begin, ...present.map(p => pattern(where.prefix, p)), end].join('\n') + '\n';
80
+ const next = base + (base && !base.endsWith('\n') ? '\n' : '') + (base ? '\n' : '') + block;
81
+ if (next !== current) writeExclude(where.exclude, next);
82
+ log(`${next === current ? 'ok ' : 'update'} ${rel} (git ignores ${present.join(', ')} in this clone)`);
83
+ } catch (e) {
84
+ log(`WARNING: could not update ${rel} (${e.message}). Keep ${present.join(', ')} out of commits.`);
85
+ }
86
+ const tracked = git(where.top, ['ls-files', '--', ...PRIVATE.map(p => where.prefix ? `${where.prefix}/${p}` : p)]).out.split('\n').filter(Boolean);
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
+ 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.`);
90
+ }
91
+
92
+ function unprotect(root, { dry = false, log = console.log } = {}) {
93
+ let where;
94
+ try { where = locate(root); } catch (_) { return; }
95
+ if (!where || where.warn) return;
96
+ const rel = path.relative(where.top, where.exclude).split(path.sep).join('/');
97
+ try {
98
+ const current = readExclude(where.exclude);
99
+ const { text, found } = without(current, where.prefix);
100
+ if (!found) return;
101
+ if (!dry) writeExclude(where.exclude, text);
102
+ log(`${dry ? 'would ' : ''}update ${rel} (removed the agent-personalizer lines for this folder)`);
103
+ } catch (e) {
104
+ log(`WARNING: could not update ${rel} (${e.message}); remove the agent-personalizer block by hand`);
105
+ }
106
+ }
107
+
108
+ module.exports = { protect, unprotect, PRIVATE, SHARED_PERSONAL, locate };
package/bin/learn.cjs CHANGED
@@ -13,10 +13,13 @@ const IGNORE = `${FOLDER}/.gitignore`;
13
13
  const SOURCE = { claude: 'claude-code', agents: 'codex', gemini: 'gemini-cli' };
14
14
 
15
15
  function refuse(message) { throw new renderer.Refusal(message); }
16
- function consentScreen() {
16
+ function consentScreen({ allProjects = false } = {}) {
17
+ const scope = allProjects ? 'all projects' : 'the --dir project';
18
+ const scopeHint = allProjects ? 'Sessions from every project are included.' : 'Use --all-projects to include sessions from other projects.';
17
19
  return `Learn from your past sessions?
18
- agent-personalizer can read up to 20 of your most recent sessions that
19
- Claude Code, Codex and Gemini CLI still keep, to find corrections you repeat.
20
+ agent-personalizer can read up to 20 of your most recent sessions from ${scope}
21
+ that Claude Code, Codex and Gemini CLI still keep, to find corrections you repeat.
22
+ · ${scopeHint}
20
23
  · Only what you typed, never the AI's replies.
21
24
  · Stays on this computer, saved to .agent-personalizer/digest.md.
22
25
  · Your AI reads that file next time you open it, like anything you share with it.
@@ -30,12 +33,13 @@ Claude Code, Codex and Gemini CLI still keep, to find corrections you repeat.
30
33
  Read your last 20 sessions? (y/N)`;
31
34
  }
32
35
 
33
- async function requestConsent({ yes = false } = {}) {
36
+ async function requestConsent({ yes = false, allProjects = false } = {}) {
37
+ const screen = consentScreen({ allProjects });
34
38
  if (!yes && !process.stdin.isTTY) refuse('learn needs your yes: run it in a terminal, or pass --yes');
35
- if (yes) { console.log(consentScreen()); return true; }
39
+ if (yes) { console.log(screen); return true; }
36
40
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
37
41
  const answer = await new Promise(resolve => {
38
- rl.question(consentScreen() + ' ', resolve);
42
+ rl.question(screen + ' ', resolve);
39
43
  rl.once('close', () => resolve(''));
40
44
  });
41
45
  rl.close();
@@ -131,27 +135,47 @@ function replace(root, rel, text) {
131
135
  } finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); }
132
136
  }
133
137
 
134
- async function learn({ dir = '.', yes = false, consented = false } = {}) {
138
+ const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
139
+ function canOverwrite(cfg, prior, rel) {
140
+ if (!prior.exists) return true;
141
+ if (!cfg.installed || !Object.hasOwn(cfg.installed, rel)) return false;
142
+ return sha256(fs.readFileSync(prior.full)) === cfg.installed[rel];
143
+ }
144
+
145
+ async function learn({ dir = '.', yes = false, consented = false, allProjects = false } = {}) {
135
146
  const root = projectRoot(dir);
136
147
  const cfg = readInstall(root);
137
- const consent = consented || await requestConsent({ yes });
148
+ const consent = consented || await requestConsent({ yes, allProjects });
138
149
  if (!consent) { console.log('Nothing was read.'); return false; }
139
150
  probe(root, FOLDER, 'dir');
140
- probe(root, DIGEST);
141
- probe(root, IGNORE);
151
+ const priorDigest = probe(root, DIGEST);
152
+ const priorIgnore = probe(root, IGNORE);
142
153
  probe(root, 'LEARNED.md');
143
154
  const list = probe(root, 'check/forbidden.local.txt');
144
155
  const terms = list.exists ? require('../check/gate.cjs').loadList(list.full, { allowEmpty: true }).terms : [];
145
156
  const entries = renderer.readLearned(root);
146
157
  const sources = [...new Set((cfg.targets || []).map(target => SOURCE[target]).filter(Boolean))];
147
158
  const home = os.homedir();
148
- const data = await require('./sessions.cjs').readSessions({ home, sources, limit: 20, privateTerms: terms });
159
+ const data = await require('./sessions.cjs').readSessions({ home, projectDir: root, allProjects, sources, limit: 20, privateTerms: terms });
149
160
  const now = new Date().toISOString();
150
161
  const text = digestText(data, entries, { sources, home, terms, now });
151
162
  const folder = probe(root, FOLDER, 'dir');
152
- if (!folder.exists) fs.mkdirSync(folder.full, { mode: 0o700 });
153
- replace(root, IGNORE, '*\n');
154
- replace(root, DIGEST, text);
163
+ const writeIgnore = canOverwrite(cfg, priorIgnore, IGNORE);
164
+ const writeDigest = canOverwrite(cfg, priorDigest, DIGEST);
165
+ if (!folder.exists && (writeIgnore || writeDigest)) fs.mkdirSync(folder.full, { mode: 0o700 });
166
+ if (writeIgnore) replace(root, IGNORE, '*\n');
167
+ else console.log(`kept ${IGNORE} (edited or pre-existing)`);
168
+ if (writeDigest) replace(root, DIGEST, text);
169
+ else console.log(`kept ${DIGEST} (edited or pre-existing; not overwritten)`);
170
+ // Record only the outputs this run wrote, never other or edited files sharing the folder.
171
+ if (cfg.installed && (writeIgnore || writeDigest || !folder.exists)) {
172
+ const saved = JSON.parse(fs.readFileSync(path.join(root, CONFIG), 'utf8'));
173
+ if (writeIgnore) saved.installed[IGNORE] = sha256('*\n');
174
+ if (writeDigest) saved.installed[DIGEST] = sha256(text);
175
+ if (!folder.exists && (writeIgnore || writeDigest)) saved.createdDirectories = [...new Set([...(saved.createdDirectories || []), FOLDER])];
176
+ replace(root, CONFIG, JSON.stringify(saved, null, 2) + '\n');
177
+ }
178
+ if (!writeIgnore) require('./git-exclude.cjs').protect(root);
155
179
  for (const file of data.filesRead) console.log(`read ${shownFile(file, home, terms)}`);
156
180
  console.log(`Files checked: ${data.filesChecked}. Files read: ${data.filesRead.length}. Sessions: ${data.sessions.length}. Memory notes: ${data.memories.length}.`);
157
181
  console.log(`Skipped by reason: ${Object.entries(data.skipped).map(([reason, count]) => `${reason}: ${count}`).join(', ') || 'none'}`);
@@ -162,14 +186,15 @@ async function learn({ dir = '.', yes = false, consented = false } = {}) {
162
186
 
163
187
  function forget(dir = '.', { dry = false } = {}) {
164
188
  const root = projectRoot(dir);
165
- readInstall(root);
189
+ const cfg = readInstall(root);
166
190
  const folder = probe(root, FOLDER, 'dir');
167
191
  const digest = probe(root, DIGEST);
168
192
  const ignore = probe(root, IGNORE);
169
193
  if (!digest.exists) console.log('No digest to forget.');
170
194
  const removes = digest.exists ? [DIGEST] : [];
171
195
  const names = folder.exists ? fs.readdirSync(folder.full) : [];
172
- const emptyAfter = folder.exists && names.every(name => name === 'digest.md' || name === '.gitignore');
196
+ const ignoreOwned = !ignore.exists || !cfg.installed || (Object.hasOwn(cfg.installed, IGNORE) && sha256(fs.readFileSync(ignore.full)) === cfg.installed[IGNORE]);
197
+ const emptyAfter = folder.exists && ignoreOwned && names.every(name => name === 'digest.md' || name === '.gitignore');
173
198
  if (emptyAfter && ignore.exists) removes.push(IGNORE);
174
199
  for (const rel of removes) {
175
200
  if (!dry) fs.unlinkSync(probe(root, rel).full);
package/bin/sessions.cjs CHANGED
@@ -3,22 +3,42 @@
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const os = require('node:os');
6
+ const crypto = require('node:crypto');
6
7
 
7
8
  const MAX_LINE = 8 * 1024 * 1024;
8
9
  const MAX_FILE = 64 * 1024 * 1024;
10
+ const MAX_MEMORIES = 20;
9
11
  const SOURCES = new Set(['claude-code', 'codex', 'gemini-cli']);
10
12
  const CONTEXT_HEADERS = ['# AGENTS.md instructions', '# Files mentioned by the user', '# Response annotations', '# Browser comments'];
11
13
 
12
- function bump(state, reason) {
13
- state.skipped[reason] = (state.skipped[reason] || 0) + 1;
14
+ function bump(state, reason, count = 1) {
15
+ state.skipped[reason] = (state.skipped[reason] || 0) + count;
16
+ }
17
+
18
+ function claudeProjectNames(projectDir) {
19
+ const absolute = path.resolve(projectDir);
20
+ return [...new Set([absolute.replace(/[\\/]/g, '-'), absolute.replace(/[:\\/]/g, '-')])];
21
+ }
22
+
23
+ function belongsToProject(cwd, projectDir) {
24
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return false;
25
+ const relative = path.relative(projectDir, path.resolve(cwd));
26
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
14
27
  }
15
28
 
16
29
  /* Both sides are compared in NFC and lower case: macOS often stores accents decomposed (NFD),
17
30
  which would otherwise let a listed name through. Audit 0.8.0 F2. */
18
- const fold = (text) => String(text).normalize('NFC').toLowerCase();
31
+ const CTRL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
32
+ const fold = (text) => String(text).replace(CTRL, '').normalize('NFC').toLowerCase();
33
+ const compact = (text) => fold(text).replace(/\s+/g, '');
19
34
  function privateMatch(text, terms) {
20
35
  const lower = fold(text);
21
- return terms.some(term => lower.includes(term));
36
+ const collapsed = compact(text);
37
+ return terms.some(raw => {
38
+ const term = fold(raw).trim();
39
+ const tight = compact(raw);
40
+ return (term && lower.includes(term)) || (tight && collapsed.includes(tight));
41
+ });
22
42
  }
23
43
 
24
44
  function cutContextBlocks(text) {
@@ -44,15 +64,16 @@ function typedText(items, state) {
44
64
  if (privateMatch(items.join('\n'), state.privateTerms) || privateMatch(items.join(''), state.privateTerms)) { bump(state, 'private_match'); return null; }
45
65
  const kept = [];
46
66
  for (const item of items) {
47
- let text = item.trim();
67
+ let text = String(item).replace(CTRL, '').trim();
48
68
  if (/^<[A-Za-z][A-Za-z0-9_:-]*/.test(text) || CONTEXT_HEADERS.some(prefix => text.startsWith(prefix))) {
49
69
  bump(state, 'automation_text');
50
70
  continue;
51
71
  }
52
- text = cutContextBlocks(text).trim();
72
+ text = cutContextBlocks(text).replace(CTRL, '').trim();
53
73
  if (text) kept.push(text);
54
74
  }
55
75
  const text = kept.join('\n');
76
+ if (privateMatch(text, state.privateTerms) || privateMatch(kept.join(''), state.privateTerms)) { bump(state, 'private_match'); return null; }
56
77
  if (!text) { bump(state, 'empty_message'); return null; }
57
78
  if (text.length > 2000) { bump(state, 'long_message'); return null; }
58
79
  return text;
@@ -97,10 +118,14 @@ async function discover(home, sources, state) {
97
118
  const app = path.join(home, '.claude');
98
119
  if (await statPath(app, 'directory', state)) {
99
120
  const projects = path.join(app, 'projects');
100
- for (const project of await children(projects, state)) {
101
- const dir = path.join(projects, project);
102
- for (const name of await children(dir, state)) {
103
- if (name.endsWith('.jsonl')) await candidate(path.join(dir, name), 'claude-code', project, 'claude', state);
121
+ if (await statPath(projects, 'directory', state)) {
122
+ const projectNames = state.allProjects ? await children(projects, state) : claudeProjectNames(state.projectDir);
123
+ for (const project of projectNames) {
124
+ const dir = path.join(projects, project);
125
+ if (!await statPath(dir, 'directory', state)) continue;
126
+ for (const name of await children(dir, state)) {
127
+ if (name.endsWith('.jsonl')) await candidate(path.join(dir, name), 'claude-code', project, 'claude', state);
128
+ }
104
129
  }
105
130
  }
106
131
  }
@@ -132,17 +157,20 @@ async function discover(home, sources, state) {
132
157
  const app = path.join(home, '.gemini');
133
158
  if (await statPath(app, 'directory', state)) {
134
159
  const tmp = path.join(app, 'tmp');
135
- for (const project of await children(tmp, state)) {
136
- const dir = path.join(tmp, project);
137
- if (!await statPath(dir, 'directory', state)) continue;
138
- for (const name of await children(path.join(dir, 'chats'), state)) {
139
- if (name.startsWith('session-') && name.endsWith('.jsonl')) await candidate(path.join(dir, 'chats', name), 'gemini-cli', project, 'gemini', state);
160
+ if (await statPath(tmp, 'directory', state)) {
161
+ const projects = state.allProjects ? await children(tmp, state) : [state.geminiProjectHash];
162
+ for (const project of projects) {
163
+ const dir = path.join(tmp, project);
164
+ if (!await statPath(dir, 'directory', state)) continue;
165
+ for (const name of await children(path.join(dir, 'chats'), state)) {
166
+ if (name.startsWith('session-') && name.endsWith('.jsonl')) await candidate(path.join(dir, 'chats', name), 'gemini-cli', project, 'gemini', state);
167
+ }
168
+ const logs = path.join(dir, 'logs.json');
169
+ try {
170
+ await fs.promises.lstat(logs);
171
+ await candidate(logs, 'gemini-cli', project, 'gemini-logs', state);
172
+ } catch (error) { if (error.code !== 'ENOENT') bump(state, 'unreadable'); }
140
173
  }
141
- const logs = path.join(dir, 'logs.json');
142
- try {
143
- await fs.promises.lstat(logs);
144
- await candidate(logs, 'gemini-cli', project, 'gemini-logs', state);
145
- } catch (error) { if (error.code !== 'ENOENT') bump(state, 'unreadable'); }
146
174
  }
147
175
  }
148
176
  }
@@ -178,14 +206,15 @@ async function safeOpen(file, state) {
178
206
  async function scanLines(file, state, onLine) {
179
207
  const handle = await safeOpen(file, state);
180
208
  if (!handle) return false;
181
- let fragments = [], length = 0, oversize = false;
209
+ let fragments = [], length = 0, oversize = false, stopped = false;
182
210
  function line() {
183
- if (!oversize && length) onLine(Buffer.concat(fragments, length).toString('utf8'));
211
+ if (!oversize && length && onLine(Buffer.concat(fragments, length).toString('utf8')) === false) stopped = true;
184
212
  fragments = []; length = 0; oversize = false;
185
213
  }
186
214
  try {
187
215
  const stream = handle.createReadStream({ autoClose: false, highWaterMark: 64 * 1024, start: 0, end: MAX_FILE - 1 });
188
216
  for await (const chunk of stream) {
217
+ if (stopped) break;
189
218
  let start = 0;
190
219
  for (let end = chunk.indexOf(10); ; end = chunk.indexOf(10, start)) {
191
220
  const stop = end === -1 ? chunk.length : end;
@@ -196,12 +225,16 @@ async function scanLines(file, state, onLine) {
196
225
  }
197
226
  if (end === -1) break;
198
227
  line();
228
+ if (stopped) break;
199
229
  start = end + 1;
200
230
  }
231
+ if (stopped) break;
201
232
  }
202
233
  // A capped file's partial final record is not a complete JSON line.
203
- const stat = await handle.stat();
204
- if (stat.size <= MAX_FILE) line();
234
+ if (!stopped) {
235
+ const stat = await handle.stat();
236
+ if (stat.size <= MAX_FILE) line();
237
+ }
205
238
  return true;
206
239
  } catch { bump(state, 'unreadable'); return false; }
207
240
  finally { await handle.close(); }
@@ -221,13 +254,19 @@ function baseSession(file) {
221
254
 
222
255
  async function readClaude(file, state) {
223
256
  const session = baseSession(file);
224
- let known = false, automation = false;
257
+ if (!state.allProjects) session.project = path.basename(state.projectDir);
258
+ let known = false, automation = false, sessionCwd = null;
225
259
  const ok = await scanLines(file.file, state, line => {
226
260
  const record = parsedLine(line, state);
227
261
  if (!record) return;
262
+ if (typeof record.cwd === 'string') sessionCwd = record.cwd;
228
263
  if (typeof record.entrypoint === 'string' && record.entrypoint.startsWith('sdk')) automation = true;
229
264
  if (record.type !== 'user') return;
230
265
  known = true;
266
+ if (!state.allProjects && !belongsToProject(sessionCwd, state.projectDir)) {
267
+ bump(state, typeof sessionCwd === 'string' ? 'other_project' : 'project_unknown');
268
+ return;
269
+ }
231
270
  if (record.isMeta || record.isSidechain || record.isCompactSummary || record.isVisibleInTranscriptOnly) { bump(state, 'non_typed'); return; }
232
271
  if (typeof record.sessionId === 'string') session.sessionId = record.sessionId;
233
272
  const text = typedText(textItems(record.message && record.message.content, 'text'), state);
@@ -241,7 +280,7 @@ async function readClaude(file, state) {
241
280
 
242
281
  async function readCodex(file, state) {
243
282
  const session = baseSession(file);
244
- let known = false, automation = false;
283
+ let known = false, automation = false, projectMatches = state.allProjects;
245
284
  const ok = await scanLines(file.file, state, line => {
246
285
  const record = parsedLine(line, state);
247
286
  if (!record) return;
@@ -250,17 +289,30 @@ async function readCodex(file, state) {
250
289
  const meta = record.payload;
251
290
  if (meta.source === 'exec' || (meta.source && typeof meta.source === 'object' && Object.prototype.hasOwnProperty.call(meta.source, 'subagent'))) automation = true;
252
291
  if (typeof meta.id === 'string') session.sessionId = meta.id;
292
+ if (!state.allProjects) {
293
+ projectMatches = belongsToProject(meta.cwd, state.projectDir);
294
+ if (!projectMatches) {
295
+ bump(state, typeof meta.cwd === 'string' ? 'other_project' : 'project_unknown');
296
+ return false;
297
+ }
298
+ }
253
299
  if (typeof meta.cwd === 'string') session.project = path.basename(meta.cwd);
254
300
  return;
255
301
  }
256
302
  if (record.type !== 'response_item' || !record.payload || record.payload.type !== 'message' || record.payload.role !== 'user') return;
257
303
  known = true;
304
+ if (!projectMatches) {
305
+ if (!state.allProjects) bump(state, 'project_unknown');
306
+ if (!state.allProjects) return false;
307
+ return;
308
+ }
258
309
  const text = typedText(textItems(record.payload.content, 'input_text'), state);
259
310
  if (text) session.messages.push(text);
260
311
  });
261
312
  if (!ok) return [];
262
313
  if (automation) { bump(state, 'automation_session'); return []; }
263
314
  if (!known) bump(state, 'unknown_format');
315
+ if (!projectMatches) return [];
264
316
  return session.messages.length ? [session] : [];
265
317
  }
266
318
 
@@ -347,18 +399,21 @@ async function readGeminiLogs(file, state) {
347
399
  async function readMemory(file, state) {
348
400
  const lines = [];
349
401
  if (!await scanLines(file.file, state, line => lines.push(line))) return null;
350
- const text = lines.join('\n').trim();
402
+ const text = lines.join('\n').replace(CTRL, '').trim();
351
403
  if (!text) return null;
352
404
  if (privateMatch(text, state.privateTerms)) { bump(state, 'private_match'); return null; }
353
405
  return { file: file.file, text, date: new Date(file.mtimeMs).toISOString() };
354
406
  }
355
407
 
356
- async function readSessions({ home = os.homedir(), sources = [], limit = 20, privateTerms = [] } = {}) {
408
+ async function readSessions({ home = os.homedir(), projectDir = process.cwd(), allProjects = false, sources = [], limit = 20, privateTerms = [] } = {}) {
357
409
  const selectedSources = new Set(Array.isArray(sources) ? sources.filter(source => SOURCES.has(source)) : []);
358
410
  const maximum = Number.isInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 20;
411
+ projectDir = path.resolve(projectDir);
359
412
  const state = {
360
- home: path.resolve(home), candidates: [], memoryFiles: [], filesRead: [], filesChecked: 0, skipped: {},
361
- privateTerms: Array.isArray(privateTerms) ? privateTerms.filter(term => typeof term === 'string' && term).map(fold) : []
413
+ home: path.resolve(home), projectDir, allProjects,
414
+ geminiProjectHash: crypto.createHash('sha256').update(projectDir).digest('hex'),
415
+ candidates: [], memoryFiles: [], filesRead: [], filesChecked: 0, skipped: {},
416
+ privateTerms: Array.isArray(privateTerms) ? privateTerms.filter(term => typeof term === 'string' && fold(term).trim()).map(fold) : []
362
417
  };
363
418
  await discover(state.home, selectedSources, state);
364
419
  state.candidates.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file));
@@ -382,7 +437,8 @@ async function readSessions({ home = os.homedir(), sources = [], limit = 20, pri
382
437
  }
383
438
  const memories = [];
384
439
  state.memoryFiles.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file));
385
- for (const file of state.memoryFiles) {
440
+ for (const file of state.memoryFiles.slice(MAX_MEMORIES)) bump(state, 'memory_limit');
441
+ for (const file of state.memoryFiles.slice(0, MAX_MEMORIES)) {
386
442
  const memory = await readMemory(file, state);
387
443
  if (memory) memories.push(memory);
388
444
  }
package/bin/uninstall.cjs CHANGED
@@ -12,6 +12,16 @@ const CONFIG = '.agent-personalizer.json';
12
12
  const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
13
13
 
14
14
  function refuse(message) { throw new renderer.Refusal(message); }
15
+ // Install appends "\n" + block + "\n" to a pre-existing file that ends in a newline
16
+ // (render.cjs splice). Take back exactly that: the newline ending the end marker and one
17
+ // separator newline before the begin marker, so an untouched file returns byte for byte.
18
+ function stripBlock(existing, ms) {
19
+ let before = existing.slice(0, ms.bStart), after = existing.slice(ms.eEnd);
20
+ if (after.startsWith('\r\n')) after = after.slice(2);
21
+ else if (after.startsWith('\n')) after = after.slice(1);
22
+ if (before.endsWith('\n\n')) before = before.slice(0, -1);
23
+ return before + after;
24
+ }
15
25
  function uninstall(dir, { dry = false } = {}) {
16
26
  const previousThrows = renderer.DIE_THROWS;
17
27
  renderer.DIE_THROWS = true;
@@ -91,7 +101,7 @@ function run(dir, dry) {
91
101
  }
92
102
  const tracked = new Set(modern ? [CONFIG, ...Object.keys(cfg.installed)] : [CONFIG, 'USER.md', ...recipe.map(p => p.rel)]);
93
103
  tracked.delete('LEARNED.md');
94
- // The digest is disposable private material, independent of installed-file hashes.
104
+ // Digest files use the same ownership proof as every other installed file.
95
105
  const digestFolder = '.agent-personalizer';
96
106
  const digestFiles = [];
97
107
  function collectDigest(rel) {
@@ -99,7 +109,7 @@ function run(dir, dry) {
99
109
  if (!full) return;
100
110
  const names = fs.readdirSync(full).sort();
101
111
  observations.get(rel).children = names;
102
- dirs.add(rel);
112
+ if ((cfg.createdDirectories || []).includes(rel)) dirs.add(rel);
103
113
  for (const name of names) {
104
114
  const child = `${rel}/${name}`;
105
115
  const info = fs.lstatSync(path.join(root, child));
@@ -107,8 +117,7 @@ function run(dir, dry) {
107
117
  else { read(child); digestFiles.push(child); }
108
118
  }
109
119
  }
110
- // The whole private folder is removed by uninstall. Validate even unexpected descendants
111
- // before planning any deletion, so a symlink cannot turn this into a wider removal.
120
+ // Validate even unexpected descendants, then keep anything without a matching creation hash.
112
121
  collectDigest(digestFolder);
113
122
  for (const rel of digestFiles) tracked.add(rel);
114
123
  const learned = read('LEARNED.md');
@@ -137,7 +146,10 @@ function run(dir, dry) {
137
146
  : renderer.renderedContents(root, cfg);
138
147
  const plan = [];
139
148
  const add = (rel, action, output, reason) => plan.push({ rel, action, output, reason });
140
- for (const rel of digestFiles) if (read(rel)) add(rel, 'remove', null, 'private digest data');
149
+ for (const rel of digestFiles) {
150
+ const bytes = read(rel), recorded = recordedHash(cfg, rel);
151
+ if (bytes) add(rel, recorded && sha256(bytes) === recorded ? 'remove' : 'keep', null, 'unrecorded or edited digest-folder file');
152
+ }
141
153
  for (const entry of rendered) {
142
154
  const { rel, key, block, raw } = entry;
143
155
  if (!tracked.has(rel)) continue;
@@ -165,7 +177,7 @@ function run(dir, dry) {
165
177
  // edited (or vice versa).
166
178
  const currentBlock = renderer.between(existing, rel);
167
179
  const blockUnedited = recorded ? (currentBlock !== null && sha256(Buffer.from(currentBlock)) === recorded) : matchesBlock;
168
- if (blockUnedited) add(rel, 'strip', Buffer.from(existing.slice(0, ms.bStart) + existing.slice(ms.eEnd)), 'pre-existing file; removed only the marked block');
180
+ if (blockUnedited) add(rel, 'strip', Buffer.from(stripBlock(existing, ms)), 'pre-existing file; removed only the marked block');
169
181
  else add(rel, 'keep', null, ms.kind === 'none' ? 'pre-existing file; block already absent' : 'edited');
170
182
  continue;
171
183
  }
@@ -205,6 +217,11 @@ function run(dir, dry) {
205
217
  const unedited = recorded ? sha256(existing) === recorded : existing.equals(bytes);
206
218
  add(rel, unedited ? 'remove' : 'keep', null, 'edited');
207
219
  }
220
+ // LEARNED.md belongs to the user once it holds anything they wrote. Only the exact template
221
+ // bytes this package recorded writing are removed; a pre-existing or edited file stays.
222
+ const recordedLearned = recordedHash(cfg, 'LEARNED.md');
223
+ const learnedUntouched = !!learned && !!recordedLearned && sha256(learned) === recordedLearned;
224
+ if (learnedUntouched) add('LEARNED.md', 'remove', null, 'untouched template');
208
225
  // Earlier notes folders, retired rules and all other recorded paths are inventory too.
209
226
  // Current answers cannot erase history, and an unrecorded file is never adopted here.
210
227
  const planned = new Set(plan.map(p => p.rel));
@@ -214,7 +231,8 @@ function run(dir, dry) {
214
231
  if (bytes) add(rel, sha256(bytes) === recordedHash(cfg, rel) ? 'remove' : 'keep', null, 'edited');
215
232
  }
216
233
  if (new Set(plan.map(p => p.rel)).size !== plan.length) refuse('conflicting tracked paths; nothing was removed');
217
- const retained = plan.filter(p => p.action !== 'remove');
234
+ // A pre-existing home file with only its block removed holds nothing of ours to review.
235
+ const retained = plan.filter(p => p.action === 'keep');
218
236
  const removeConfig = retained.length === 0;
219
237
  const gone = new Set(plan.filter(p => p.action === 'remove').map(p => p.rel));
220
238
  const emptyDirs = [];
@@ -240,7 +258,7 @@ function run(dir, dry) {
240
258
  }
241
259
  const label = dry ? 'would ' : '';
242
260
  if (dry) console.log('Dry run: preview only; no files changed.');
243
- if (learned) console.log('kept LEARNED.md (your entries, edited or untouched)');
261
+ if (learned && !learnedUntouched) console.log('kept LEARNED.md (your entries)');
244
262
  for (const p of plan) {
245
263
  if (p.action === 'keep') { console.log(`kept ${p.rel} (${p.reason})`); continue; }
246
264
  if (!dry) {
@@ -268,16 +286,16 @@ function run(dir, dry) {
268
286
  }
269
287
  console.log(`${label}remove ${rel}/ (empty)`);
270
288
  }
271
- if (!dry && probe(digestFolder, 'dir')) refuse(`${digestFolder}/ changed during removal; ${CONFIG} kept, review its remaining contents`);
272
289
  // Config is always the final removal. A kept tracked path keeps the record for review.
273
290
  if (removeConfig) {
274
291
  if (!dry) {
275
- for (const p of plan) if (probe(p.rel)) refuse(`${p.rel} still exists; ${CONFIG} kept`);
292
+ for (const p of plan) if (p.action === 'remove' && probe(p.rel)) refuse(`${p.rel} still exists; ${CONFIG} kept`);
276
293
  const full = probe(CONFIG);
277
294
  if (!full || !fs.readFileSync(full).equals(observations.get(CONFIG).bytes)) refuse(`${CONFIG} changed; config kept`);
278
295
  fs.unlinkSync(full);
279
296
  }
280
297
  console.log(`${label}remove ${CONFIG}`);
298
+ require('./git-exclude.cjs').unprotect(root, { dry });
281
299
  } else console.log(`kept ${CONFIG} (tracked files remain; review the kept paths above)`);
282
300
  if (level >= 3) console.log('Manual step: remove any SessionStart entry for hooks/claude-code/session-start.sh from .claude/settings.json or ~/.claude/settings.json if you registered it. Settings are kept.');
283
301
  }
@@ -8,8 +8,8 @@ Each render comes from `USER.md`, `LEARNED.md`, the selected rule source and the
8
8
 
9
9
  - **One profile source:** edit `USER.md`, then regenerate. Every profile-bearing target uses it, including `chatgpt-box1.txt`. Untouched generated profiles retain the compact ChatGPT export. Edited generated identity fields can still compact; custom text or structure falls back to the profile's own text, with the same budget warning.
10
10
  - **Rule and onboarding sources:** edit the rule files or onboarding answers, then regenerate the selected AI files together. Each target receives the rules selected for its format and budget.
11
- - **Entry source:** `LEARNED.md` is installed once and kept on re-runs. Confirmed entries reach personal targets; declined entries reach their "Never ask again" lists. Proposed entries render nowhere. ChatGPT may shorten declined lists for its budget; the plain system prompt has no entries.
12
- - **Byte fidelity:** the renderer preserves bytes outside generated markers, including line endings.
11
+ - **Entry source:** `LEARNED.md` is installed once and kept on re-runs. Confirmed entries reach personal targets; declined entries reach their "Never ask again" lists. Proposed entries render nowhere. ChatGPT exports both lists in full, with budget warnings and `--strict` refusal on overflow; the plain system prompt has no entries.
12
+ - **Byte fidelity:** the renderer preserves bytes outside generated markers, including line endings and a leading UTF-8 BOM.
13
13
  - **Drift detection:** `node render/render.cjs --dir . --check` compares the current generated blocks and both ChatGPT paste files with what the sources would render now. Success is silent with exit `0`; it exits `1` and names drift when they differ.
14
14
  - **Paste updates:** re-paste regenerated files into chat-app instruction fields. The check compares files on disk.
15
15
  - **ChatGPT budget:** each box reports its character count against the limit in `render/targets.json`. Over-budget text is preserved and flagged. `--strict` exits `1` before writing when a box exceeds that limit.
@@ -20,11 +20,12 @@ The check measures rendered-file consistency. The [instruction tiers](tiers.md)
20
20
 
21
21
  The installer validates answers, configuration, source files and target marker structure before its write phase. The renderer validates its full target plan before replacing files.
22
22
 
23
- - **Paths:** paths beneath the installation root must be real files and directories. Symlinks and paths outside the root are refused.
23
+ - **Paths:** paths beneath the installation root must be real files and directories. Symlinks and paths outside the root are refused. Local notes paths must sit outside tool-owned paths, including `.agent-personalizer/`.
24
+ - **Git exclude:** the one write outside the installed files. Inside a git work tree, the installer adds `USER.md`, `LEARNED.md`, `.agent-personalizer.json` and the ChatGPT paste files to the repo's `.git/info/exclude` (the path `git rev-parse --git-path info/exclude` names) in one block marked with the install folder. Re-runs replace that block; it is never committed. A folder git already ignores is left alone, a symlinked or unwritable exclude file gets a warning instead, and so does a private file git already tracks. `CLAUDE.md`, `AGENTS.md`, `GEMINI.md` and `AGENT_ONBOARDING.md` stay committable with a note to review them.
24
25
  - **Markers:** each target may have one correctly ordered generated block or be ready for its first block. Malformed blocks are refused.
25
26
  - **Encoding:** sources and targets must contain valid UTF-8; invalid bytes are refused instead of re-encoded.
26
27
  - **Existing work:** edited and pre-existing profiles, notes templates, rules and tools are kept and named. Untouched installer-owned files update to the current answers and package. Obsolete untouched copies are removed; edited copies stay and are named.
27
- - **Recovery:** the installer validates its complete plan before writing and restores changed files on failure. The renderer stages target writes with backups and rolls back a failed write. An incomplete restore keeps and names its backup with exit `2`.
28
+ - **Recovery:** the installer validates its complete plan before writing and restores changed files on failure. The renderer stages targets and their ownership configuration together with backups and rolls back a failed write. An incomplete restore keeps and names its backup with exit `2`.
28
29
  - **Local operation:** the tool uses HOME to find the AI apps' folders. Before consent, it may check whether `~/.claude`, `~/.codex` and `~/.gemini` exist for target pre-selection; it opens or lists their contents only after a yes. A non-interactive install and a re-run never read sessions. The tool makes no network calls and sends no telemetry. `npx` fetches the package before execution.
29
30
 
30
31
  On a re-run, each home-file line that byte-matches the previous template is migrated to the new template or removed when obsolete. An edited pointer stays byte for byte and is named with its file and line for manual review. Other outer text stays byte for byte. The renderer owns only the marked block.
@@ -35,7 +36,7 @@ On a re-run, each home-file line that byte-matches the previous template is migr
35
36
  - **Notes history:** changing the notes path creates the new scaffold and keeps the old folder. The log names both paths once; the recorded files from both remain available to uninstall.
36
37
  - **Tool updates:** a recorded install hash recognizes untouched tools and rules. For older installs without hashes, a shipped table of earlier release hashes recognizes untouched verbatim copies. Edited tools remain intact; the log names the known origin version and the replacement step. The configuration records the installed tooling version.
37
38
  - **Removal inventory:** uninstall checks the union of recorded installed paths across all runs. A matching hash permits removal, a changed file is kept and named, and a missing file is skipped. An unrecorded file is left alone. Legacy configurations without hashes use their known install recipe.
38
- - **Entries and evidence:** uninstall always keeps `LEARNED.md`, edited or untouched, and removes the local digest, its `.gitignore` and private folder. `learn --forget` removes only agent-personalizer's digest and its empty folder. Neither changes the AI apps' own history.
39
+ - **Entries and evidence:** uninstall keeps `LEARNED.md` once it holds anything you wrote (an untouched template is removed). It removes a digest and `.gitignore` only with matching creation hashes, and a recorded private folder only when empty. Unrecorded or edited files in that folder stay, including digests from older installs without creation records. `learn --forget` removes only agent-personalizer's digest and its empty folder. Neither changes the AI apps' own history.
39
40
  - **Removal paths:** every tracked path is validated before the first unlink and re-probed before each unlink. Removal is file by file. Only recorded install-created, empty directories are removed.
40
41
  - **Configuration last:** the configuration is removed after tracked files are gone. Retained tracked files are named and keep the configuration for review.
41
42
  - **Preview and manual steps:** `--uninstall --dry` makes the same decisions as removal and changes no files. A missing configuration exits `2` naming its path. Hook registration and pasted instructions are printed as manual cleanup steps.
package/docs/install.md CHANGED
@@ -148,14 +148,15 @@ npx agent-personalizer --uninstall --dir /path/to/project
148
148
  The uninstaller reads `/path/to/project/.agent-personalizer.json` and compares files with their recorded install hashes. Its inventory includes every path recorded by any install run, including files under a previous notes path and rules omitted by later answers. Files absent from that inventory are left alone. Configurations from before hashes were recorded use the legacy comparison for their known recipe.
149
149
 
150
150
  - **Generated files:** removed when unchanged. Edited files are kept and named in the output.
151
- - **Existing home files:** user text stays; only an unchanged generated block is removed.
151
+ - **Existing home files:** user text stays; only an unchanged generated block and the blank separator line the installer added are removed, so an untouched file returns byte for byte. (A file that had no final newline before install keeps the one the installer added.)
152
152
  - **`USER.md`:** removed only when it matches its recorded install hash. Edited and pre-existing profiles stay.
153
- - **`LEARNED.md`:** always kept, whether edited or untouched. It holds the entries you approved or declined.
153
+ - **`LEARNED.md`:** kept once it holds anything you wrote, and kept if it existed before install. An untouched template that matches its recorded install hash is removed.
154
154
  - **Session digest:** `.agent-personalizer/digest.md`, its `.gitignore` and private folder are removed. Your AI apps' history is untouched.
155
155
  - **Notes scaffold:** unchanged historically installed templates are removed. Edited templates are kept and named; user-written notes stay byte for byte. A directory is removed only when the install recorded that it created it and it is empty.
156
+ - **Git exclude:** after the configuration is removed, the block install added to `.git/info/exclude` for this folder is removed, and the rest of the file stays byte for byte. While an edited file keeps the configuration, the block stays too.
156
157
  - **Rules and tools:** unchanged installed copies are removed file by file, including the session-start hook. Edited copies stay.
157
158
  - **Hook registration:** remove the matching `SessionStart` entry from `.claude/settings.json` or `~/.claude/settings.json` yourself. The uninstaller prints this step; it never edits settings outside the installation.
158
159
  - **Paths:** the whole removal plan is preflighted before the first unlink, and each path is re-probed before it is unlinked. The uninstaller never follows symlinks, deletes recursively or removes a path outside the named folder. A refused preflight leaves the removal plan unapplied.
159
- - **Configuration:** `.agent-personalizer.json` is removed last, only after every path it tracks is gone. A retained file, including a pre-existing home file with its block removed, keeps the configuration available for review.
160
+ - **Configuration:** `.agent-personalizer.json` is removed last, only after every path it tracks is gone or, for a pre-existing home file, has had its block removed. An edited file the uninstaller retained keeps the configuration available for review.
160
161
 
161
162
  `--dry` previews the same decisions without writing. A missing configuration exits `2` and names the expected path. Keep the configuration while reviewing any edited files the uninstaller retained.
package/docs/learning.md CHANGED
@@ -8,8 +8,10 @@ The first interactive install asks which AIs you use, then shows this consent sc
8
8
 
9
9
  ```text
10
10
  Learn from your past sessions?
11
- agent-personalizer can read up to 20 of your most recent sessions that
12
- Claude Code, Codex and Gemini CLI still keep, to find corrections you repeat.
11
+ agent-personalizer can read up to 20 of your most recent sessions from this
12
+ project that Claude Code, Codex and Gemini CLI still keep, to find corrections you repeat.
13
+ · By default, only sessions for this --dir project are included.
14
+ · Use --all-projects to include sessions from other projects.
13
15
  · Only what you typed, never the AI's replies.
14
16
  · Stays on this computer, saved to .agent-personalizer/digest.md.
15
17
  · Your AI reads that file next time you open it, like anything you share with it.
@@ -44,9 +46,11 @@ The saved AI selection chooses the sources. The reader takes up to 20 of the new
44
46
  | `gemini` | Gemini CLI: `~/.gemini/tmp/<hash>/chats/session-*.jsonl` and the older `logs.json` |
45
47
  | `chatgpt`, `prompt` | No local session reader |
46
48
 
47
- The digest contains typed user messages and, when Codex is selected, Codex's own memory notes in a separate section. AI replies, tool output, reasoning, automation sessions and injected context are dropped. Large likely pastes are dropped too. Gemini chat snapshots replace earlier messages; a message repeated in the chat and logs is included once.
49
+ By default, only sessions associated with the `--dir` folder or one of its subfolders are included. Claude Code and Codex sessions are matched by their recorded working directory; Gemini CLI uses the SHA-256 project folder it creates from that path. If a session does not provide enough path information to match it safely, it is skipped. Use `npx agent-personalizer learn --dir . --all-projects` to include sessions from every project.
48
50
 
49
- The reader streams session files, skips oversized lines and stops a file at its size limit. Symlinks, unreadable files and unknown or malformed formats are skipped and counted. The terminal lists every file read and the skip counts; message text is never printed there. Vendor format changes may mean fewer usable sessions until the reader is updated.
51
+ The digest contains typed user messages and, when Codex is selected, up to 20 of the newest Codex memory files in a separate section. AI replies, tool output, reasoning, automation sessions and injected context are dropped. Large likely pastes are dropped too. Gemini chat snapshots replace earlier messages; a message repeated in the chat and logs is included once. The all-projects option affects session history; the memory file limit still applies.
52
+
53
+ The reader streams session files, skips oversized lines and stops a file at its size limit. Symlinks, unreadable files, other-project sessions and unknown or malformed formats are skipped and counted. Codex session headers are inspected to determine their project; message content from other projects is not scanned. The terminal lists files read and skip counts; message text is never printed there. Vendor format changes may mean fewer usable sessions until the reader is updated.
50
54
 
51
55
  ## Privacy before reading
52
56
 
@@ -86,7 +90,7 @@ npx agent-personalizer --uninstall --dir . --dry
86
90
  npx agent-personalizer --uninstall --dir .
87
91
  ```
88
92
 
89
- `learn --forget` deletes agent-personalizer's digest and removes its empty private folder. It keeps approved entries. Uninstall removes the digest, its `.gitignore` and private folder, and always keeps `LEARNED.md`, edited or untouched. Neither changes the AI apps' own history. To stop questions, decline the consent screen and do not run `learn --yes`; to change an entry, edit its owning line and re-render.
93
+ `learn --forget` deletes agent-personalizer's digest and removes its empty private folder. It keeps approved entries. Uninstall removes the digest, its `.gitignore` and private folder, and keeps `LEARNED.md` once it holds anything you wrote; an untouched template is removed. Neither changes the AI apps' own history. To stop questions, decline the consent screen and do not run `learn --yes`; to change an entry, edit its owning line and re-render.
90
94
 
91
95
  ## How the loop closes
92
96
 
package/docs/tiers.md CHANGED
@@ -81,7 +81,7 @@ A word on the stories below: each is one setup's experience of what held and wha
81
81
 
82
82
  **Story.** A memory file said the user preferred a certain tool. The user had never said so; an earlier session had inferred it from one choice. Three sessions built on it. The status field exists so the next session can tell the difference between "she said" and "I guessed," and so a contradicted fact gets marked `superseded` with a pointer rather than silently overwritten.
83
83
 
84
- **Rule inside the tier.** Ask before keeping an entry as confirmed. A no is recorded as declined and never asked again. Re-render after an entry changes; `--check` catches an unrendered edit. The digest of past messages is temporary evidence, separate from the entries: `learn --forget` removes it, and uninstall always keeps `LEARNED.md`. See [learning.md](learning.md).
84
+ **Rule inside the tier.** Ask before keeping an entry as confirmed. A no is recorded as declined and never asked again. Re-render after an entry changes; `--check` catches an unrendered edit. The digest of past messages is temporary evidence, separate from the entries: `learn --forget` removes it, and uninstall keeps `LEARNED.md` once it holds anything you wrote. See [learning.md](learning.md).
85
85
 
86
86
  ---
87
87
 
@@ -52,6 +52,6 @@
52
52
  "installed": {
53
53
  "CLAUDE.md": "3ea7661f6ea1ad2f23072c20bc952ea0cf3d2acafdc486edee86f095266dc979",
54
54
  "AGENTS.md": "e870580a758b363c07e767e040f683e32890d0248726d0bcd4f0be0d83f3f423",
55
- "AGENT_ONBOARDING.md": "004a28c24352f9f55ca6f01a0c70bc1547c15ed530488cc7b7dc74fd95b18e7f"
55
+ "AGENT_ONBOARDING.md": "2b949bba0f33c9a75823ff142be849d8b5ef391fd472935de6a3fa8e00702919"
56
56
  }
57
57
  }
@@ -34,7 +34,7 @@ _Generated by agent-personalizer from your saved preferences (stored in `.agent-
34
34
 
35
35
  ### Where you may write
36
36
 
37
- - **Notes live in Obsidian:** reach them as the vault at `notes/`, through **obsidian-tc** (governed MCP: folder ACLs, human-in-the-loop confirmation for destructive tools, audit log) rather than raw filesystem access; see https://github.com/aunysillyme/agent-personalizer/blob/v0.8.0/docs/companions.md.
37
+ - **Notes live in Obsidian:** reach them as the vault at `notes/`, through **obsidian-tc** (governed MCP: folder ACLs, human-in-the-loop confirmation for destructive tools, audit log) rather than raw filesystem access; see https://github.com/aunysillyme/agent-personalizer/blob/v0.8.1/docs/companions.md.
38
38
  - You may create and edit files anywhere under `notes/`, under that folder's rules. Nowhere else without being asked.
39
39
  - **Every folder you write into has a README.** Any write, edit or delete means that README is corrected in the same pass: the file's one-line description, the folder's status, settled decisions, next steps. A stale index is worse than none, because the next agent believes it.
40
40
  - **Session log:** append a dated section to this week's note in `notes/sessions/`. **Decisions:** one line each in `notes/decisions.md`. **Inbox:** one file per item in `notes/inbox/`; finished items are deleted, not marked done.
package/hooks/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # hooks/
2
2
 
3
- Tier 3 from the tiers doc (https://github.com/aunysillyme/agent-personalizer/blob/v0.8.0/docs/tiers.md): the few rules that must be in context at the moment of decision, injected in full at the start of every session. Injection puts the text in front of the model; whether the model follows it is up to the model and the host. This is the strongest placement available, not a guarantee.
3
+ Tier 3 from the tiers doc (https://github.com/aunysillyme/agent-personalizer/blob/v0.8.1/docs/tiers.md): the few rules that must be in context at the moment of decision, injected in full at the start of every session. Injection puts the text in front of the model; whether the model follows it is up to the model and the host. This is the strongest placement available, not a guarantee.
4
4
 
5
5
  Which rules? The ones with `inject: true` in their frontmatter. Keep that set small. Every injected rule costs tokens every session.
6
6
 
package/llms.txt CHANGED
@@ -6,7 +6,7 @@ Install with `npx agent-personalizer`. Node 22 or 24 (active LTS) is recommended
6
6
 
7
7
  The installer asks which AIs you use and whether it may learn from your recent sessions, with No as the default. It writes USER.md, LEARNED.md, AGENT_ONBOARDING.md and each selected AI's instruction files. With a yes, it reads up to 20 recent sessions from Claude Code, Codex and Gemini CLI, plus Codex memory notes, and saves a local digest. The user's AI asks up to five evidence-backed questions; confirmed entries reach every selected personal target and declined entries are never asked again. Level 2 adds local notes scaffolds for local and fallback notes tools. Level 3 adds editable rules, a renderer, a session-start hook, a drift check and a forbidden-string gate.
8
8
 
9
- Re-runs ask nothing, keep saved answers and update untouched installed files and pointer lines. Edited copies stay and are named, old notes folders stay in place, and upgrades refresh untouched tools. USER.md supplies every profile export, including ChatGPT; LEARNED.md owns the shared entries. `npx agent-personalizer learn --dir .` asks for consent before collecting new evidence. `learn --forget` deletes the digest. Uninstall keeps LEARNED.md and removes the digest; neither touches the AI apps' history. Preview removal with `npx agent-personalizer --uninstall --dir . --dry`.
9
+ Re-runs ask nothing, keep saved answers and update untouched installed files and pointer lines. Edited copies stay and are named, old notes folders stay in place, and upgrades refresh untouched tools. USER.md supplies every profile export, including ChatGPT; LEARNED.md owns the shared entries. `npx agent-personalizer learn --dir .` asks for consent before collecting new evidence. `learn --forget` deletes the digest. Uninstall keeps a LEARNED.md with entries, removes the digest and restores untouched files byte for byte; neither touches the AI apps' history. Preview removal with `npx agent-personalizer --uninstall --dir . --dry`.
10
10
 
11
11
  Session data stays local until the user's AI reads it and sends it to its provider again. Only reuse history you may share, filter other people's details with check/forbidden.local.txt and check agreements for work accounts. The tool makes no network calls. It is not affiliated with Anthropic, OpenAI or Google, and their saved formats can change.
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-personalizer",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "AI custom instructions from approved entries: a profile and rules for Claude Code, Codex, Cursor, Gemini CLI and ChatGPT, kept in sync from one source.",
5
5
  "author": "aunysillyme (https://github.com/aunysillyme)",
6
6
  "license": "MIT",
@@ -17,7 +17,7 @@
17
17
  DOCS points at the matching tag on GitHub so an installed copy never links to a file the
18
18
  destination does not have.
19
19
  */
20
- const VERSION = '0.8.0';
20
+ const VERSION = '0.8.1';
21
21
  const DOCS = `https://github.com/aunysillyme/agent-personalizer/blob/v${VERSION}/docs`;
22
22
 
23
23
  /* THE single source for notes tools. Add a tool here and nowhere else: the saved choice option, the
@@ -173,6 +173,9 @@ function validate(input) {
173
173
  // no "..", no empty segment, no backslash, nothing but [A-Za-z0-9._ -] per segment.
174
174
  if (kindOf(out) === 'disk' && !SAFE_REL.test(out.notes_path))
175
175
  throw new Error(`"notes_path" for ${out.notes_tool} must be a relative folder path such as "notes" or "docs/vault" (letters, digits, space, . _ -, segments joined by /; no leading /, no ..)`);
176
+ const owned = ['.agent-personalizer', '.agent-personalizer.json', '.claude', 'render', 'rules', 'check', 'hooks', 'USER.md', 'LEARNED.md', 'CLAUDE.md', 'AGENTS.md', 'GEMINI.md', 'AGENT_ONBOARDING.md', 'system-prompt.md', 'chatgpt-custom-instructions.md', 'chatgpt-box1.txt', 'chatgpt-box2.txt'];
177
+ if (kindOf(out) === 'disk' && owned.some(p => out.notes_path.toLowerCase() === p.toLowerCase() || out.notes_path.toLowerCase().startsWith(p.toLowerCase() + '/')))
178
+ throw new Error('"notes_path" must be outside agent-personalizer tool-owned paths, including .agent-personalizer/');
176
179
  return out;
177
180
  }
178
181
  const SAFE_REL = /^(?!\.\.?(?:\/|$))[A-Za-z0-9._ -]+(?:\/(?!\.\.?(?:\/|$))[A-Za-z0-9._ -]+)*$/;
@@ -504,6 +507,7 @@ function compactProfileFromUser(text, answers, opts) {
504
507
 
505
508
  // Entry status is explicit: a guess does not become an approved instruction by being saved.
506
509
  function parseLearned(text, where = 'LEARNED.md', warn = console.error) {
510
+ text = String(text).replace(/^\ufeff/, '');
507
511
  if (/<!--\s*agent-personalizer/i.test(text)) throw new Error(`${where}: contains a reserved render marker token`);
508
512
  const out = { confirmed: [], declined: [], proposed: [], asked: [] };
509
513
  let section = '';
package/render/render.cjs CHANGED
@@ -119,6 +119,7 @@ function mustBe(p, kind, where) {
119
119
  }
120
120
 
121
121
  function parseFrontmatter(text, where) {
122
+ text = String(text).replace(/^\ufeff/, '');
122
123
  if (!text.startsWith('---\n')) return { meta: {}, body: text };
123
124
  const close = text.indexOf('\n---\n', 4);
124
125
  if (close === -1) die(`${where}: frontmatter opened with --- but never closed`);
@@ -157,6 +158,7 @@ function parseFrontmatter(text, where) {
157
158
  }
158
159
 
159
160
  function parseSections(body, where) {
161
+ body = String(body).replace(/^\ufeff/, '');
160
162
  const sections = {};
161
163
  let current = null;
162
164
  const lines = body.split('\n');
@@ -187,7 +189,8 @@ function fenceMap(lines, where) {
187
189
  const inside = new Array(lines.length).fill(false);
188
190
  let open = null; // { ch, len, line }
189
191
  lines.forEach((raw, i) => {
190
- const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
192
+ const clean = i === 0 && raw.startsWith('\ufeff') ? raw.slice(1) : raw;
193
+ const line = clean.endsWith('\r') ? clean.slice(0, -1) : clean;
191
194
  const m = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
192
195
  if (open) {
193
196
  inside[i] = true;
@@ -205,6 +208,10 @@ function rejectMarkers(text, where) {
205
208
  if (text.includes(BEGIN) || text.includes(END)) die(`${where}: contains a render marker token; those are reserved for rendered files`);
206
209
  }
207
210
 
211
+ function hasUtf8Bom(bytes) {
212
+ return bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
213
+ }
214
+
208
215
  function decodeUtf8(bytes, where) {
209
216
  try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
210
217
  catch (_) { die(`${where}: not valid UTF-8. Nothing was written`); }
@@ -241,7 +248,7 @@ function validatePreservedTargets(cfg) {
241
248
 
242
249
  function readSource(p, where) {
243
250
  mustBe(p, 'file', where);
244
- const text = decodeUtf8(fs.readFileSync(p), where).replace(/\r\n/g, '\n');
251
+ const text = decodeUtf8(fs.readFileSync(p), where).replace(/^\ufeff/, '').replace(/\r\n/g, '\n');
245
252
  rejectMarkers(text, where);
246
253
  return text;
247
254
  }
@@ -373,13 +380,7 @@ function renderTarget(key, target, profile, rules, cfg, root, learned) {
373
380
  if (target.personal) {
374
381
  if (learned.confirmed.length) box1 += '\nConfirmed entries:\n' + learned.confirmed.map(x => '- ' + x.entry).join('\n');
375
382
  if (learned.declined.length) {
376
- const label = '\nNever ask again:\n';
377
- const declined = [];
378
- for (const x of learned.declined) {
379
- const line = '- ' + x.entry;
380
- if ((box1 + label + [...declined, line].join('\n')).length <= target.limit) declined.push(line);
381
- }
382
- if (declined.length) box1 += label + declined.join('\n');
383
+ box1 += '\nNever ask again:\n' + learned.declined.map(x => '- ' + x.entry).join('\n');
383
384
  }
384
385
  lines.push(`_LEARNED.md source: ${learned.hash}_`, '');
385
386
  }
@@ -421,7 +422,7 @@ function markerState(text, where) {
421
422
  lines.forEach((raw, i) => {
422
423
  if (!fenced[i]) {
423
424
  const t = (raw.endsWith('\r') ? raw.slice(0, -1) : raw).trim();
424
- if (t === BEGIN) b.push([pos, pos + raw.length]);
425
+ if (t === BEGIN) b.push([pos + (i === 0 && raw.startsWith('\ufeff') ? 1 : 0), pos + raw.length]);
425
426
  else if (t === END) e.push([pos, pos + raw.length]);
426
427
  }
427
428
  pos += raw.length + 1;
@@ -515,30 +516,38 @@ function main() {
515
516
  if (!target) die(`unknown target "${key}" (known: ${KNOWN.join(', ')})`);
516
517
  const file = safeTargetPath(root, target.file, key);
517
518
  const block = renderTarget(key, target, profile, rules, cfg, root, learned);
518
- let existing = null;
519
+ let existing = null, existingBytes = null, hasBom = false;
519
520
  if (fs.existsSync(file)) {
520
- existing = decodeUtf8(fs.readFileSync(file), target.file);
521
+ existingBytes = fs.readFileSync(file);
522
+ hasBom = hasUtf8Bom(existingBytes);
523
+ existing = decodeUtf8(existingBytes, target.file);
521
524
  }
522
525
  if (!check) {
523
526
  try { fs.accessSync(existing == null ? path.dirname(file) : file, fs.constants.W_OK); }
524
527
  catch (_) { die(`${target.file}: not writable. Nothing was written`); }
525
528
  }
526
529
  const current = existing == null ? null : between(existing, target.file);
527
- const output = check ? null : splice(existing, block, target.file);
530
+ const body = check ? null : splice(existing, block, target.file);
528
531
  // the generated file must itself re-parse to exactly one block, or the next render would refuse it
529
- if (output != null) { const st = markerState(output, `${target.file} (generated)`); if (st.kind !== 'one' || between(output, `${target.file} (generated)`) !== block) die(`${target.file}: generated content would not re-parse cleanly; a fence in USER.md or a rule is unbalanced. Nothing was written`); }
532
+ if (body != null) { const st = markerState(body, `${target.file} (generated)`); if (st.kind !== 'one' || between(body, `${target.file} (generated)`) !== block) die(`${target.file}: generated content would not re-parse cleanly; a fence in USER.md or a rule is unbalanced. Nothing was written`); }
533
+ const output = body == null ? null : (hasBom ? '\ufeff' + body : body);
530
534
  const mode = existing == null ? 0o644 : (fs.statSync(file).mode & 0o777);
531
- const entry = { key, target, file, block, current, output, mode, report: report(target.file, existing, current, block, false) };
535
+ const entry = { key, target, file, block, current, existing, existingBytes, output, mode, report: report(target.file, existing, current, block, false) };
532
536
  if (!target.boxes) return entry;
533
537
  // the two plain paste files: whole-file outputs, no markers, compared whole in --check
534
538
  const raws = Object.entries(target.boxFiles || {}).map(([which, rel]) => {
535
539
  const rfile = safeTargetPath(root, rel, `${key}:${which}`);
536
540
  const text = renderTarget.boxes[which];
537
- let rexisting = null;
538
- if (fs.existsSync(rfile)) rexisting = decodeUtf8(fs.readFileSync(rfile), rel);
541
+ let rexisting = null, rhasBom = false;
542
+ if (fs.existsSync(rfile)) {
543
+ const rbytes = fs.readFileSync(rfile);
544
+ rhasBom = hasUtf8Bom(rbytes);
545
+ rexisting = decodeUtf8(rbytes, rel);
546
+ }
539
547
  if (!check) { try { fs.accessSync(rexisting == null ? path.dirname(rfile) : rfile, fs.constants.W_OK); } catch (_) { die(`${rel}: not writable. Nothing was written`); } }
540
548
  const rmode = rexisting == null ? 0o644 : (fs.statSync(rfile).mode & 0o777);
541
- return { key: `${key}:${which}`, target: { file: rel }, file: rfile, block: text, current: rexisting, output: check ? null : text, mode: rmode, raw: true, report: report(rel, rexisting, rexisting, text, true) };
549
+ const routput = check ? null : (rhasBom ? '\ufeff' + text : text);
550
+ return { key: `${key}:${which}`, target: { file: rel }, file: rfile, block: text, current: rexisting, output: routput, mode: rmode, raw: true, report: report(rel, rexisting, rexisting, text, true) };
542
551
  });
543
552
  return [entry, ...raws];
544
553
  }).flat();
@@ -547,6 +556,10 @@ function main() {
547
556
  console.error('render: --strict: a box is over its budget. Nothing was written');
548
557
  process.exit(1);
549
558
  }
559
+ if (!check) {
560
+ const config = installedConfig(root, plan);
561
+ if (config) plan.push(config);
562
+ }
550
563
 
551
564
  // Every final path must be distinct, and no final path may look like a staging file.
552
565
  // Checked in every mode, before any output.
@@ -618,36 +631,34 @@ function main() {
618
631
  } catch (e) { undo(`could not commit output (${e.message})`); }
619
632
  const leftovers = [];
620
633
  for (const c of committed) if (c.bak) tryUnlink(c.bak, leftovers, 'backup not removed');
621
- for (const s of staged) console.log(s.report);
634
+ for (const s of staged) if (s.report) console.log(s.report);
622
635
  for (const o of (renderTarget.overBudget || [])) console.log(`OVER BUDGET ${o} (written in full; trim by hand, bottom up)`);
623
636
  if (leftovers.length) {
624
637
  console.error('render: every target was written, but CLEANUP INCOMPLETE. Remove these by hand (they hold copies of the previous targets):');
625
638
  for (const l of leftovers) console.error(` ${l}`);
626
639
  process.exit(2);
627
640
  }
628
- recordInstalled(root, plan);
629
641
  }
630
642
 
631
- /* After a successful commit, record the exact bytes just written for each rendered target, so
632
- --uninstall can recognize them later even after this package has moved on to a newer release.
633
- For a target this run OWNS outright (not in the stored preservedTargets, i.e. not a file that
634
- already existed before its target was first installed), the whole file is generated by this
635
- tool, so the whole file's bytes are recorded. For a pre-existing home file, only the marker
636
- block belongs to this tool, so only the block is hashed; the surrounding bytes are the user's
637
- and are never fingerprinted. Read only; never runs during --check (nothing was written), and
638
- a config predating this field, or none at all, is left exactly as it is. */
639
- function recordInstalled(root, plan) {
643
+ /* Plan ownership updates in the same transaction as the targets. A whole-file hash can advance
644
+ only from bytes already recorded as ours; an edited outer file keeps its old hash so uninstall
645
+ retains it. Preserved targets record only the block. User bytes are never adopted on re-render.
646
+ A config predating the installed map stays without it so legacy recipe fallback still applies. */
647
+ function installedConfig(root, plan) {
640
648
  const cfgPath = path.join(root, '.agent-personalizer.json');
641
- let raw;
642
- try { raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch (_) { return; }
643
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return;
644
- const installed = (raw.installed && typeof raw.installed === 'object' && !Array.isArray(raw.installed)) ? { ...raw.installed } : {};
649
+ if (!mustBe(cfgPath, 'file', '.agent-personalizer.json')) return null;
650
+ const raw = readJson(cfgPath, 'config');
651
+ try { fs.accessSync(cfgPath, fs.constants.W_OK); }
652
+ catch (_) { die('.agent-personalizer.json: not writable. Nothing was written'); }
653
+ if (!raw.installed || typeof raw.installed !== 'object' || Array.isArray(raw.installed)) return null;
654
+ const installed = { ...raw.installed };
645
655
  for (const p of plan) {
646
656
  const preserved = !p.raw && Array.isArray(raw.preservedTargets) && raw.preservedTargets.includes(p.key);
657
+ if (!p.raw && !preserved && p.existingBytes !== null && installed[p.target.file] !== sha256(p.existingBytes)) continue;
647
658
  installed[p.target.file] = sha256(Buffer.from(preserved ? p.block : p.output));
648
659
  }
649
660
  raw.installed = installed;
650
- fs.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + '\n');
661
+ return { file: cfgPath, target: { file: '.agent-personalizer.json' }, output: JSON.stringify(raw, null, 2) + '\n', mode: fs.statSync(cfgPath).mode & 0o777 };
651
662
  }
652
663
 
653
664
  /* Everything the renderer would refuse about the SOURCES already present in a folder, checked without