agent-personalizer 0.6.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,11 +17,11 @@
17
17
  (level 2 creates it, and level 2+ repoints them). Level 3 copies rules/ (yours to edit from
18
18
  then on) with the renderer, hook and gate. .agent-personalizer.json stores only the answers that
19
19
  differ from the defaults.
20
- Writes only the files for the chosen AIs and level. Never overwrites a file that exists
21
- (except the marker block inside rendered files it owns, .agent-personalizer.json, which
22
- is its own record and is merged, never blindly replaced, and USER.md when, and only when,
23
- the answers changed and the file still equals the render of the previous answers byte for
24
- byte; an edited USER.md is kept and the changed answers are named as a conflict).
20
+ Writes only the chosen AIs and the highest installed level. Re-runs replace untouched
21
+ installer-owned copies using recorded hashes, with a static release-hash fallback for older
22
+ installs. Edited files and pointer lines are kept and named. Previous notes folders stay in
23
+ place and in the uninstall inventory. The config is merged; USER.md is regenerated only
24
+ when it still equals the previous answer render. All writes roll back if rendering fails.
25
25
  PREFLIGHT: every path is probed and every existing rendered target is decoded and its marker
26
26
  block checked BEFORE the first write, so a refusal leaves the folder as it was. The notes
27
27
  folder the scaffold creates and the home files point at is your notes_path (disk tools) or
@@ -45,11 +45,12 @@ const HOME_NAMES = new Set(['CLAUDE.md', 'AGENTS.md']);
45
45
  const PKG = path.resolve(__dirname, '..');
46
46
  const onboarding = require(path.join(PKG, 'render', 'onboarding.cjs'));
47
47
  const markers = require(path.join(PKG, 'render', 'render.cjs')); // markerState, for the preflight; render.cjs runs nothing on require
48
- const { installPlan } = require('./install-plan.cjs');
48
+ const { installPlan, validateInventory, knownVersions, ownership, migrateHome, recordedHash } = require('./install-plan.cjs');
49
49
  const AIS = ['claude', 'agents', 'gemini', 'chatgpt', 'prompt'];
50
50
  const AI_LABEL = { claude: 'Claude (Claude Code, Claude apps)', agents: 'Codex / Cursor / anything that reads AGENTS.md', gemini: 'Gemini', chatgpt: 'ChatGPT custom instructions', prompt: 'a plain system prompt (shareable, no profile)' };
51
51
 
52
- function die(msg) { console.error(`agent-personalizer: ${msg}`); process.exit(2); }
52
+ let committing = false;
53
+ function die(msg) { if (committing) throw new markers.Refusal(msg); console.error(`agent-personalizer: ${msg}`); process.exit(2); }
53
54
 
54
55
  const VALUE_OPTS = ['--dir', '--ai', '--level', '--answers'];
55
56
  const FLAG_OPTS = ['--yes', '--defaults', '--quick', '--full', '--uninstall', '--dry', '--help', '--version', '-h', '-v'];
@@ -63,7 +64,7 @@ const USAGE = `agent-personalizer ${require(path.join(PKG, 'package.json')).vers
63
64
  Interactive when flags are missing and stdin is a terminal; the onboarding interview runs then.
64
65
  The interview is SHORT by default: the seven questions that change behaviour (name, tone, length,
65
66
  notes tool and path, write policy, always-ask), plus any question the notes tool you pick makes
66
- apply. Every other answer takes its default.
67
+ apply. Other answers keep their saved values, or take defaults on the first install.
67
68
  --full ask every question instead of the short set. Interactive only.
68
69
  --quick the short interview. It is now the default; the flag is kept so older commands still work.
69
70
  --answers a JSON file of answers, or "-" to read the JSON from stdin. Unknown keys and values are refused.
@@ -100,11 +101,11 @@ function arg(name, dflt) { return name in ARGS ? ARGS[name] : dflt; }
100
101
  if (ARGS['--help'] || ARGS['-h']) { process.stdout.write(USAGE); process.exit(0); }
101
102
  if (ARGS['--version'] || ARGS['-v']) { process.stdout.write(require(path.join(PKG, 'package.json')).version + '\n'); process.exit(0); }
102
103
 
103
- async function ask(q, dflt) {
104
+ async function ask(q, dflt, saved = false) {
104
105
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
105
- const a = await new Promise(res => rl.question(`${q}${dflt ? ` [${dflt}]` : ''}: `, res));
106
+ const a = await new Promise(res => rl.question(`${q}${dflt || saved ? ` [${dflt}]` : ''}: `, res));
106
107
  rl.close();
107
- return (a || dflt || '').trim();
108
+ return saved ? a.trim() : (a || dflt || '').trim();
108
109
  }
109
110
 
110
111
  /* Resolve <root>/<rel> such that every existing component is a real directory (never a
@@ -147,12 +148,42 @@ function probe(root, rel) {
147
148
  die('unreachable');
148
149
  }
149
150
 
150
- function copyIfAbsent(src, root, rel) {
151
- const { full, exists } = safeDest(root, rel);
152
- if (exists) { console.log(`kept ${rel} (exists)`); return false; }
153
- fs.copyFileSync(src, full, fs.constants.COPYFILE_EXCL);
154
- console.log(`wrote ${rel}`);
155
- return true;
151
+ // Read the stored config once. The interview uses it before any directories or files are created;
152
+ // non-interactive answer sources retain their existing handling below.
153
+ function readConfig(root, level) {
154
+ const { full: cfgPath, exists: cfgExists } = probe(root, '.agent-personalizer.json');
155
+ let cfg = { targets: [], level };
156
+ let prevAnswers = null;
157
+ if (cfgExists) {
158
+ try { cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch (e) { die(`.agent-personalizer.json is not valid JSON (${e.message}); fix or remove it`); }
159
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) die('.agent-personalizer.json must be an object');
160
+ if ('targets' in cfg) {
161
+ if (!Array.isArray(cfg.targets)) die('.agent-personalizer.json "targets" must be a list');
162
+ const KNOWN = [...AIS, 'onboarding'];
163
+ const bad = cfg.targets.filter(t => !KNOWN.includes(t));
164
+ if (bad.length) die(`.agent-personalizer.json lists unknown target(s): ${bad.join(', ')} (known: ${KNOWN.join(', ')}); fix or remove them`);
165
+ if (new Set(cfg.targets).size !== cfg.targets.length) die('.agent-personalizer.json lists a target twice');
166
+ }
167
+ if ('level' in cfg && !(Number.isInteger(cfg.level) && cfg.level >= 1 && cfg.level <= 4)) die(`.agent-personalizer.json "level" must be an integer 1-4 (found ${JSON.stringify(cfg.level)})`);
168
+ try { validateInventory(cfg); } catch (e) { die(`.agent-personalizer.json: ${e.message}; nothing was written`); }
169
+ markers.DIE_THROWS = true;
170
+ try { markers.validatePreservedTargets(cfg); }
171
+ catch (e) { if (e instanceof markers.Refusal) die(e.message); throw e; }
172
+ finally { markers.DIE_THROWS = false; }
173
+ if (cfg.onboarding) {
174
+ try { prevAnswers = onboarding.validate(cfg.onboarding); } catch (e) { die(`.agent-personalizer.json onboarding answers: ${e.message}`); }
175
+ }
176
+ }
177
+ return { cfgPath, cfgExists, cfg, prevAnswers };
178
+ }
179
+
180
+ // Follow the requested folder once, without creating its missing tail.
181
+ function resolveDestination(dir) {
182
+ const requested = path.resolve(String(dir));
183
+ let existing = requested; const missing = [];
184
+ while (!fs.existsSync(existing)) { missing.unshift(path.basename(existing)); const parent = path.dirname(existing); if (parent === existing) die(`cannot create ${requested}`); existing = parent; }
185
+ const realExisting = fs.realpathSync(existing);
186
+ return { requested, realExisting, missing, root: path.join(realExisting, ...missing) };
156
187
  }
157
188
 
158
189
  async function main() {
@@ -195,6 +226,7 @@ async function main() {
195
226
  if (arg('--quick', false) && arg('--full', false)) die('--quick and --full are exclusive; the short interview is the default');
196
227
  if (arg('--quick', false) && (answersFile || arg('--defaults', false) || !interactive)) die('--quick is the short interview; it needs a terminal and no --answers, --defaults or --yes');
197
228
  if (arg('--full', false) && (answersFile || arg('--defaults', false) || !interactive)) die('--full is the long interview; it needs a terminal and no --answers, --defaults or --yes');
229
+ let destination = null, stored = null;
198
230
  if (answersFile) {
199
231
  let raw;
200
232
  const label = answersFile === '-' ? 'stdin' : answersFile;
@@ -206,59 +238,50 @@ async function main() {
206
238
  if (!arg('--defaults', false) && !process.stdin.isTTY) console.error('agent-personalizer: stdin is not a terminal, so the interview cannot run; using the default answers (pass --answers <file.json>, --answers -, or --defaults to silence this)');
207
239
  answersSource = process.stdin.isTTY ? 'defaults (pass --answers <file.json>, or run without --yes, to answer the interview)' : 'defaults (stdin is not a terminal; pass --answers <file.json> or --answers - to script them)';
208
240
  } else {
241
+ destination = resolveDestination(dir);
242
+ const { requested, root, missing } = destination;
243
+ if (!missing.length && !fs.lstatSync(root).isDirectory()) die(`--dir ${requested} is not a directory`);
244
+ stored = readConfig(root, level);
245
+ const saved = stored.prevAnswers;
209
246
  const full = !!arg('--full', false);
210
- console.log('\nOnboarding: how should an AI work with you? Enter accepts the default in brackets.');
247
+ console.log(saved
248
+ ? '\nOnboarding: how should an AI work with you? Enter keeps the saved answer shown in brackets.'
249
+ : '\nOnboarding: how should an AI work with you? Enter accepts the default in brackets.');
211
250
  console.log(full
212
251
  ? `Full interview: up to ${onboarding.QUESTIONS.length} questions, some of which apply only to certain notes tools.\n`
213
- : `Short interview: the ${onboarding.QUICK.length} questions that change behaviour, plus any the notes tool you pick makes apply. Every other answer takes its default; --full asks up to ${onboarding.QUESTIONS.length}, skipping questions that do not apply to your notes tool.\n`);
214
- const raw = {};
252
+ : `Short interview: the ${onboarding.QUICK.length} questions that change behaviour, plus any the notes tool you pick makes apply. ${saved ? 'Every other answer keeps its saved value' : 'Every other answer takes its default'}; --full asks up to ${onboarding.QUESTIONS.length}, skipping questions that do not apply to your notes tool.\n`);
253
+ const raw = saved ? onboarding.interviewAnswers(saved) : {};
215
254
  for (const q of onboarding.QUESTIONS) {
216
255
  if (!onboarding.asks(q, raw, full)) continue;
217
256
  if (q.options) for (const [v, l] of q.options) console.log(` ${v.padEnd(30)} ${l}`);
218
- const dflt = Array.isArray(q.default) ? q.default.join(', ') : q.default;
219
- raw[q.id] = onboarding.parseAnswer(q, await ask(q.ask, dflt || ''));
257
+ const value = onboarding.interviewDefault(q, saved);
258
+ const dflt = Array.isArray(value) ? value.join(', ') : value;
259
+ raw[q.id] = onboarding.parseAnswer({ ...q, default: value }, await ask(q.ask, dflt || '', !!saved));
220
260
  }
221
261
  try { answers = onboarding.validate(raw); } catch (e) { die(`onboarding: ${e.message}`); }
222
- answersSource = full ? 'your interview answers' : 'your short-interview answers (the rest are defaults)';
262
+ answersSource = full ? 'your interview answers' : `your short-interview answers (the rest are ${saved ? 'kept saved values' : 'defaults'})`;
223
263
  }
224
264
 
225
265
  // The folder you name is followed once (realpath of its deepest EXISTING ancestor); the
226
266
  // missing tail is created one level at a time, so nothing is ever created through a
227
267
  // symlink that did not exist when you ran the command. Everything beneath root is then
228
268
  // symlink-free by construction (safeDest refuses any).
229
- const requested = path.resolve(String(dir));
230
- let existing = requested; const missing = [];
231
- while (!fs.existsSync(existing)) { missing.unshift(path.basename(existing)); const parent = path.dirname(existing); if (parent === existing) die(`cannot create ${requested}`); existing = parent; }
232
- let root = fs.realpathSync(existing);
233
- for (const part of missing) { root = path.join(root, part); fs.mkdirSync(root); }
269
+ const { requested, root, realExisting, missing } = destination || resolveDestination(dir);
270
+ let creating = realExisting;
271
+ for (const part of missing) { creating = path.join(creating, part); fs.mkdirSync(creating); }
234
272
  if (!fs.lstatSync(root).isDirectory()) die(`--dir ${requested} is not a directory`);
235
273
  // Config: the one file this installer rewrites. Read and VALIDATED here, before the first write, so a malformed
236
274
  // stored config refuses the whole run and leaves the folder untouched. Existing onboarding answers are kept unless
237
275
  // --answers or the interview supplied new ones; targets are merged; "onboarding" is always a target.
238
- const { full: cfgPath, exists: cfgExists } = probe(root, '.agent-personalizer.json');
239
- let cfg = { targets: [], level };
240
- let prevAnswers = null;
241
- if (cfgExists) {
242
- try { cfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8')); } catch (e) { die(`.agent-personalizer.json is not valid JSON (${e.message}); fix or remove it`); }
243
- if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) die('.agent-personalizer.json must be an object');
244
- if ('targets' in cfg) {
245
- if (!Array.isArray(cfg.targets)) die('.agent-personalizer.json "targets" must be a list');
246
- const KNOWN = [...AIS, 'onboarding'];
247
- const bad = cfg.targets.filter(t => !KNOWN.includes(t));
248
- if (bad.length) die(`.agent-personalizer.json lists unknown target(s): ${bad.join(', ')} (known: ${KNOWN.join(', ')}); fix or remove them`);
249
- if (new Set(cfg.targets).size !== cfg.targets.length) die('.agent-personalizer.json lists a target twice');
250
- }
251
- if ('level' in cfg && !(Number.isInteger(cfg.level) && cfg.level >= 1 && cfg.level <= 4)) die(`.agent-personalizer.json "level" must be an integer 1-4 (found ${JSON.stringify(cfg.level)})`);
252
- markers.DIE_THROWS = true;
253
- try { markers.validatePreservedTargets(cfg); }
254
- catch (e) { if (e instanceof markers.Refusal) die(e.message); throw e; }
255
- finally { markers.DIE_THROWS = false; }
256
- if (cfg.onboarding) {
257
- try { prevAnswers = onboarding.validate(cfg.onboarding); } catch (e) { die(`.agent-personalizer.json onboarding answers: ${e.message}`); }
258
- if (!answersFile && answersSource.startsWith('defaults')) { answers = prevAnswers; answersSource = 'kept from .agent-personalizer.json'; }
259
- }
276
+ const storedConfig = stored || readConfig(root, level);
277
+ const { cfgPath, cfgExists, prevAnswers } = storedConfig;
278
+ let cfg = storedConfig.cfg;
279
+ if (prevAnswers && !answersFile && answersSource.startsWith('defaults')) {
280
+ answers = prevAnswers; answersSource = 'kept from .agent-personalizer.json';
260
281
  }
261
282
  const allTargets = [...new Set([...(Array.isArray(cfg.targets) ? cfg.targets : []), ...targets, 'onboarding'])];
283
+ const installedLevel = Math.max(level, cfg.level || 0);
284
+ const effectiveLevel = Math.min(installedLevel, 3);
262
285
  const base = onboarding.baseFor(answers); // the folder scaffolds and home-file pointers use
263
286
  const kind = onboarding.kindOf(answers);
264
287
  // Bytes actually written, by tracked path, so --uninstall never has to re-derive them from
@@ -266,17 +289,39 @@ async function main() {
266
289
  // only ever added to here, never pruned (a config predating this field has none, and falls
267
290
  // back to the older comparison; see uninstall.cjs).
268
291
  const installedHashes = { ...(cfg.installed && typeof cfg.installed === 'object' ? cfg.installed : {}) };
292
+ const createdDirectories = new Set(cfg.createdDirectories || []);
293
+ const toolingVersions = { ...(cfg.toolingVersions || {}) };
294
+ const toolingVersion = require(path.join(PKG, 'package.json')).version;
295
+ const legacy = cfgExists && !!prevAnswers && !Object.hasOwn(cfg, 'installed');
269
296
 
270
297
  console.log(`\nInstalling level ${level} for ${targets.join(', ')} into ${root}\nOnboarding answers: ${answersSource}\n`);
271
298
 
272
299
  // ---- PLAN: every file this run would create, computed before anything is written ----
273
300
  const scaffoldExists = (() => { try { return fs.statSync(path.join(root, base, 'README.md')).isFile(); } catch (_) { return false; } })();
274
- const willScaffold = level >= 2 && kind !== 'cloud'; // this run's own scaffold, written further down
301
+ const willScaffold = effectiveLevel >= 2 && kind !== 'cloud';
275
302
  const notesScaffolded = kind !== 'cloud' && (scaffoldExists || willScaffold);
276
- const { plan, stripSig, notesWhy, NOTES_ONE_LINE, NOTES_LATER } = installPlan({ answers, level, targets, notesScaffolded });
303
+ const { plan } = installPlan({ answers, level: effectiveLevel, targets: allTargets, notesScaffolded });
304
+ const plannedBytes = new Map();
305
+ for (const p of plan) {
306
+ const bytes = p.src ? fs.readFileSync(p.src) : Buffer.from(p.text);
307
+ if (plannedBytes.has(p.rel) && !plannedBytes.get(p.rel).equals(bytes)) die(`${p.rel}: conflicting install paths; nothing was written`);
308
+ plannedBytes.set(p.rel, bytes);
309
+ }
310
+ const previousBase = prevAnswers ? onboarding.baseFor(prevAnswers) : null;
311
+ const previousNotesExists = previousBase && !!probe(root, `${previousBase}/README.md`).exists;
312
+ const previousNotesScaffolded = prevAnswers && onboarding.kindOf(prevAnswers) !== 'cloud' && ((cfg.level || 1) >= 2 || previousNotesExists);
313
+ const previousPlan = prevAnswers ? installPlan({ answers: prevAnswers, level: Math.min(cfg.level || 1, 3), targets: cfg.targets || [], notesScaffolded: previousNotesScaffolded }).plan : [];
277
314
 
278
315
  // ---- PREFLIGHT: refuse now, with nothing written, everything the renderer would refuse later ----
279
- for (const p of plan) probe(root, p.rel); // symlinks and non-directories on the way
316
+ for (const p of plan) {
317
+ const destination = probe(root, p.rel);
318
+ if (destination.exists && !fs.lstatSync(destination.full).isFile()) die(`${p.rel} exists and is not a regular file; nothing was written`);
319
+ }
320
+ for (const rel of Object.keys(installedHashes)) probe(root, rel);
321
+ for (const rel of createdDirectories) {
322
+ const destination = probe(root, rel);
323
+ if (destination.exists && !fs.lstatSync(destination.full).isDirectory()) die(`${rel} is not a directory; nothing was written`);
324
+ }
280
325
  // sources already in the folder (a kept rules/ file, a kept USER.md): parsed exactly as the renderer will parse them
281
326
  markers.DIE_THROWS = true;
282
327
  try { markers.preflightSources(root); }
@@ -327,46 +372,99 @@ async function main() {
327
372
  if (userAction === 'keep' && notesScaffolded && !current.includes(`\`${base}/README.md\``)) staleNotesInUser = true;
328
373
  }
329
374
 
330
- // Upgrade from a lower level. Two repairs, each matched byte for byte against a line THIS installer
331
- // wrote, so anything the user edited is left alone:
332
- // level 3: the pointer lines said "the rendered block below"; now that rules/ arrives they name it.
333
- // level 2: the one-line notes placeholder a level-1 install wrote becomes the real pointers, now
334
- // that the folder behind them exists.
375
+ // Previous answers identify the exact installer lines to migrate. Each unchanged line is
376
+ // replaced or removed on its own; all other outside-marker bytes stay exactly as read.
335
377
  const upgrades = [];
336
- if (level >= 2) for (const name of ['CLAUDE.md', 'AGENTS.md']) {
337
- if (!(name === 'CLAUDE.md' ? targets.includes('claude') : targets.includes('agents'))) continue;
378
+ const outside = (text, name) => {
379
+ const ms = markers.markerState(text, name);
380
+ return ms.kind === 'one' ? text.slice(0, ms.bStart) + text.slice(ms.eEnd) : text;
381
+ };
382
+ for (const name of ['CLAUDE.md', 'AGENTS.md']) {
383
+ const prior = previousPlan.find(p => p.rel === name);
384
+ const next = plan.find(p => p.rel === name);
385
+ if (!prior || !next) continue;
338
386
  const { full, exists } = probe(root, name);
339
387
  if (!exists || !fs.lstatSync(full).isFile()) continue;
340
- const tmpl = stripSig(fs.readFileSync(path.join(PKG, 'templates', name), 'utf8')).split('\n');
341
- const lines = fs.readFileSync(full, 'utf8').split('\n');
342
- const why = [];
343
- if (level >= 3) {
344
- let repointed = false;
345
- for (const t of tmpl) {
346
- if (!/`\[owner: rules\/[^\]]+\]`/.test(t)) continue;
347
- const placeholder = t.replace(/`\[owner: rules\/[^\]]+\]`/g, '`[owner: the rendered block below]`');
348
- for (let i = 0; i < lines.length; i++) if (lines[i] === placeholder) { lines[i] = t; repointed = true; }
349
- }
350
- const rulesLine = tmpl.find(l => /Rules, one file each, the owning copy/.test(l));
351
- const anchorIdx = lines.findIndex(l => /AGENT_ONBOARDING\.md`$/.test(l) && /^- /.test(l));
352
- if (rulesLine && !lines.includes(rulesLine) && anchorIdx !== -1 && repointed) lines.splice(anchorIdx + 1, 0, rulesLine);
353
- if (repointed) why.push('rule pointers now name rules/, which this level installs');
388
+ const current = fs.readFileSync(full, 'utf8');
389
+ if (outside(current, name) !== outside(prior.text, name)) preservedTargets.add(name === 'CLAUDE.md' ? 'claude' : 'agents');
390
+ const migration = migrateHome(current, prior.text, next.text, text => markers.markerState(text, name));
391
+ for (const line of migration.edited) console.log(`kept ${name} (edited pointer; manual review): ${line}`);
392
+ if (migration.changed) {
393
+ 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';
394
+ upgrades.push({ rel: name, bytes: Buffer.from(migration.text), report: `update ${name} (${why})` });
354
395
  }
355
- if (!notesWhy) { // this run creates the folder the four lines name
356
- const idx = lines.indexOf(NOTES_ONE_LINE(NOTES_LATER));
357
- if (idx !== -1) {
358
- lines.splice(idx, 1, ...tmpl.filter(l => /`notes\//.test(l)).map(l => base === 'notes' ? l : l.replace(/\bnotes\//g, `${base}/`)));
359
- why.push(`notes pointers now name ${base}/, which this level installs`);
360
- }
396
+ }
397
+
398
+ const writes = [...upgrades], removals = [];
399
+ // Legacy installs have no hashes. Only an exact prior recipe or committed release hash
400
+ // can establish ownership; an existing file in a fresh folder is never adopted.
401
+ if (legacy) for (const p of previousPlan) {
402
+ if (HOME_NAMES.has(p.rel)) continue;
403
+ const destination = probe(root, p.rel);
404
+ if (!destination.exists || !fs.lstatSync(destination.full).isFile()) continue;
405
+ const bytes = fs.readFileSync(destination.full);
406
+ const expected = p.src ? fs.readFileSync(p.src) : Buffer.from(p.text);
407
+ if (ownership(cfg, p.rel, bytes, { legacy: true, expected }).unedited) installedHashes[p.rel] = sha256(bytes);
408
+ }
409
+ // Learn an old tool's origin from known untouched peer copies, never by executing them.
410
+ let previousToolingVersion = cfg.toolingVersion;
411
+ if (!previousToolingVersion && cfgExists) {
412
+ let candidates = null;
413
+ for (const p of previousPlan.filter(p => p.src)) {
414
+ const destination = probe(root, p.rel);
415
+ if (!destination.exists) continue;
416
+ const versions = knownVersions(p.rel, fs.readFileSync(destination.full));
417
+ if (versions.length) candidates = candidates === null ? versions : candidates.filter(version => versions.includes(version));
418
+ }
419
+ if (candidates?.length === 1) previousToolingVersion = candidates[0];
420
+ }
421
+ const editedCopy = (rel, version) => `kept ${rel} (edited${version ? `; from version ${version}` : ''}; to take version ${toolingVersion}, save your edits, remove ${rel} and re-run)`;
422
+ for (const p of plan) {
423
+ const destination = probe(root, p.rel);
424
+ const bytes = p.src ? fs.readFileSync(p.src) : Buffer.from(p.text);
425
+ if (HOME_NAMES.has(p.rel)) {
426
+ if (!destination.exists) writes.push({ rel: p.rel, bytes, report: `wrote ${p.rel} (${p.note})` });
427
+ continue;
361
428
  }
362
- if (why.length) { try { fs.accessSync(full, fs.constants.W_OK); } catch (_) { die(`${name} is not writable; nothing was written`); } upgrades.push({ name, full, text: lines.join('\n'), why }); }
429
+ if (destination.exists) {
430
+ const existing = fs.readFileSync(destination.full);
431
+ const old = previousPlan.find(prior => prior.rel === p.rel);
432
+ const expected = old && (old.src ? fs.readFileSync(old.src) : Buffer.from(old.text));
433
+ const owner = ownership(cfg, p.rel, existing, { legacy: legacy && !!old, expected });
434
+ if (!owner.unedited) {
435
+ const tracked = recordedHash(cfg, p.rel) || (legacy && old) || Object.hasOwn(cfg.toolingVersions || {}, p.rel);
436
+ const origin = (cfg.toolingVersions || {})[p.rel] || previousToolingVersion || owner.version;
437
+ if (tracked && origin && (p.src || p.rel.startsWith('rules/'))) toolingVersions[p.rel] = origin;
438
+ console.log(tracked ? editedCopy(p.rel, origin) : `kept ${p.rel} (pre-existing; manual review)`);
439
+ continue;
440
+ }
441
+ if (existing.equals(bytes)) {
442
+ installedHashes[p.rel] = sha256(bytes);
443
+ if (p.src || p.rel.startsWith('rules/')) toolingVersions[p.rel] = toolingVersion;
444
+ console.log(`kept ${p.rel} (unchanged)`);
445
+ continue;
446
+ }
447
+ writes.push({ rel: p.rel, bytes, report: `update ${p.rel} (untouched installer copy refreshed${p.src || p.rel.startsWith('rules/') ? ` to version ${toolingVersion}` : ''})` });
448
+ } else writes.push({ rel: p.rel, bytes, report: `wrote ${p.rel}${p.note ? ` (${p.note})` : ''}` });
449
+ installedHashes[p.rel] = sha256(bytes);
450
+ if (p.src || p.rel.startsWith('rules/')) toolingVersions[p.rel] = toolingVersion;
451
+ }
452
+ // Retire only copied rules that the current answers omit. An old notes folder always
453
+ // stays, even when no current recipe mentions it; its hashes remain in the inventory.
454
+ const currentPaths = new Set(plan.map(p => p.rel));
455
+ for (const rel of Object.keys(installedHashes)) {
456
+ if (!rel.startsWith('rules/') || currentPaths.has(rel)) continue;
457
+ const destination = probe(root, rel);
458
+ if (!destination.exists) continue;
459
+ if (!fs.lstatSync(destination.full).isFile()) die(`${rel} is not a regular file; nothing was written`);
460
+ if (sha256(fs.readFileSync(destination.full)) === installedHashes[rel]) removals.push({ rel, report: `remove ${rel} (untouched installer copy; the new answers omit it)` });
461
+ else console.log(editedCopy(rel, toolingVersions[rel] || previousToolingVersion));
363
462
  }
463
+ if (previousBase && previousBase !== base && previousNotesExists) console.log(`kept ${previousBase}/ (previous notes folder; current notes folder: ${base}/; kept in the uninstall inventory)`);
364
464
 
365
- // ---- WRITE ----
366
- for (const u of upgrades) { fs.writeFileSync(u.full, u.text); console.log(`update ${u.name} (${u.why.join('; ')})`); }
367
465
  if (userAction === 'create' || userAction === 'regenerate' || userAction === 'relevel') {
368
466
  const rendered = onboarding.renderUser(answers, { notesScaffolded });
369
- fs.writeFileSync(user.full, rendered, userAction === 'create' ? { flag: 'wx' } : undefined);
467
+ writes.push({ rel: 'USER.md', bytes: Buffer.from(rendered) });
370
468
  installedHashes['USER.md'] = sha256(Buffer.from(rendered));
371
469
  if (userAction === 'create') console.log('wrote USER.md (from your answers)');
372
470
  else if (userAction === 'regenerate') console.log(`update USER.md (regenerated: it matched your previous answers byte for byte; changed: ${changedKeys.join(', ')})`);
@@ -380,33 +478,89 @@ async function main() {
380
478
  console.log('kept USER.md (exists)');
381
479
  if (staleNotesInUser) console.log(` NOTE: you edited USER.md while it still said there is no local notes folder. ${base}/ exists now. Fix the two "Where things live" lines by hand, or delete USER.md and re-run.`);
382
480
  }
383
- for (const p of plan) {
384
- if (p.src) {
385
- if (copyIfAbsent(p.src, root, p.rel)) installedHashes[p.rel] = sha256(fs.readFileSync(p.src));
386
- } else {
387
- const { full, exists } = safeDest(root, p.rel);
388
- if (exists) console.log(`kept ${p.rel} (exists)`);
389
- else {
390
- fs.writeFileSync(full, p.text, { flag: 'wx' });
391
- console.log(`wrote ${p.rel}${p.note ? ` (${p.note})` : ''}`);
392
- // CLAUDE.md/AGENTS.md are only a pointer template here; render.cjs below splices in the
393
- // rendered block and records the finished file's hash itself.
394
- if (!HOME_NAMES.has(p.rel)) installedHashes[p.rel] = sha256(Buffer.from(p.text));
395
- }
481
+ // Snapshot every possible output and check every parent before the first write. The
482
+ // renderer runs from this package, not from a potentially edited installed executable.
483
+ const outputPaths = new Set(['.agent-personalizer.json', ...writes.map(p => p.rel), ...removals.map(p => p.rel)]);
484
+ for (const target of allTargets.map(key => TARGETS[key])) {
485
+ outputPaths.add(target.file);
486
+ for (const rel of Object.values(target.boxFiles || {})) outputPaths.add(rel);
487
+ }
488
+ for (const rel of outputPaths) {
489
+ let parent = path.posix.dirname(rel);
490
+ while (parent !== '.') {
491
+ if (outputPaths.has(parent)) die(`${parent}: install path is both a file and a directory; nothing was written`);
492
+ parent = path.posix.dirname(parent);
396
493
  }
397
494
  }
398
- if (level >= 3) {
399
- const hp = path.join(root, 'hooks', 'claude-code', 'session-start.sh');
400
- const st = fs.lstatSync(hp);
401
- if (!st.isFile() || st.isSymbolicLink()) die('hook file changed underneath the installer; not chmod-ing it');
402
- fs.chmodSync(hp, 0o755);
495
+ const saved = new Map(), newDirectories = new Set();
496
+ for (const rel of outputPaths) {
497
+ const destination = probe(root, rel);
498
+ if (destination.exists) {
499
+ const info = fs.lstatSync(destination.full);
500
+ if (!info.isFile()) die(`${rel} is not a regular file; nothing was written`);
501
+ saved.set(rel, { bytes: fs.readFileSync(destination.full), mode: info.mode & 0o777, dev: info.dev, ino: info.ino });
502
+ } else saved.set(rel, null);
503
+ let parent = path.posix.dirname(rel);
504
+ while (parent !== '.') {
505
+ if (!probe(root, parent).exists) newDirectories.add(parent);
506
+ parent = path.posix.dirname(parent);
507
+ }
508
+ let ancestor = path.dirname(destination.full);
509
+ while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor);
510
+ try { fs.accessSync(ancestor, fs.constants.W_OK); } catch (_) { die(`${rel}: parent is not writable; nothing was written`); }
403
511
  }
404
- cfg = { ...cfg, targets: allTargets, level: Math.max(level, cfg.level || 0), onboarding: onboarding.sparse(answers), preservedTargets: [...preservedTargets], installed: installedHashes }; // sparse answers, original home ownership, and the bytes written so far (render.cjs below adds the home files)
405
- fs.writeFileSync(cfgPath, JSON.stringify(cfg, null, 2) + '\n');
406
- console.log(`${cfgExists ? 'update' : 'wrote '} .agent-personalizer.json (onboarding: ${answersSource})`);
407
-
408
- // Render the FULL merged target list (what a plain `render.cjs --dir .` will use from now on), from the package's renderer.
409
- execFileSync(process.execPath, [path.join(PKG, 'render', 'render.cjs'), '--dir', root, '--targets', allTargets.join(',')], { stdio: 'inherit' });
512
+ for (const rel of newDirectories) createdDirectories.add(rel);
513
+ cfg = { ...cfg, targets: allTargets, level: installedLevel, onboarding: onboarding.sparse(answers), preservedTargets: [...preservedTargets], installed: installedHashes, createdDirectories: [...createdDirectories].sort(), toolingVersion, toolingVersions };
514
+ writes.push({ rel: '.agent-personalizer.json', bytes: Buffer.from(JSON.stringify(cfg, null, 2) + '\n'), report: `${cfgExists ? 'update' : 'wrote '} .agent-personalizer.json (onboarding: ${answersSource})` });
515
+ const replace = (rel, bytes, mode) => {
516
+ const destination = safeDest(root, rel);
517
+ const tmp = path.join(path.dirname(destination.full), `.${path.basename(rel)}.${crypto.randomBytes(8).toString('hex')}.agent-personalizer.tmp`);
518
+ try {
519
+ fs.writeFileSync(tmp, bytes, { flag: 'wx', ...(mode === undefined ? {} : { mode }) });
520
+ if (mode !== undefined) fs.chmodSync(tmp, mode);
521
+ probe(root, rel);
522
+ fs.renameSync(tmp, destination.full);
523
+ } finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); }
524
+ };
525
+ const assertSaved = rel => {
526
+ const destination = probe(root, rel), before = saved.get(rel);
527
+ if (!!before !== destination.exists) die(`${rel} changed during preflight; nothing was written`);
528
+ if (before) {
529
+ const info = fs.lstatSync(destination.full);
530
+ if (info.dev !== before.dev || info.ino !== before.ino || !fs.readFileSync(destination.full).equals(before.bytes)) die(`${rel} changed during preflight; nothing was written`);
531
+ }
532
+ };
533
+ committing = true;
534
+ const touched = new Set();
535
+ try {
536
+ for (const rel of outputPaths) assertSaved(rel);
537
+ for (const p of removals) { assertSaved(p.rel); fs.unlinkSync(probe(root, p.rel).full); touched.add(p.rel); console.log(p.report); }
538
+ for (const p of writes) {
539
+ assertSaved(p.rel);
540
+ touched.add(p.rel);
541
+ const mode = p.rel === 'hooks/claude-code/session-start.sh' ? 0o755 : saved.get(p.rel)?.mode;
542
+ replace(p.rel, p.bytes, mode);
543
+ if (p.report) console.log(p.report);
544
+ }
545
+ // Include renderer outputs in rollback even when it committed before reporting a failure.
546
+ for (const rel of outputPaths) touched.add(rel);
547
+ execFileSync(process.execPath, [path.join(PKG, 'render', 'render.cjs'), '--dir', root, '--targets', allTargets.join(',')], { stdio: 'inherit' });
548
+ } catch (e) {
549
+ const incomplete = [];
550
+ for (const rel of [...touched].reverse()) {
551
+ try {
552
+ const before = saved.get(rel), destination = probe(root, rel);
553
+ if (before) replace(rel, before.bytes, before.mode);
554
+ else if (destination.exists) fs.unlinkSync(destination.full);
555
+ } catch (failure) { incomplete.push(`${rel}: ${failure.message}`); }
556
+ }
557
+ for (const rel of [...newDirectories].sort((a, b) => b.split('/').length - a.split('/').length)) {
558
+ try { const destination = probe(root, rel); if (destination.exists && fs.readdirSync(destination.full).length === 0) fs.rmdirSync(destination.full); }
559
+ catch (failure) { incomplete.push(`${rel}/: ${failure.message}`); }
560
+ }
561
+ console.error(incomplete.length ? `agent-personalizer: ROLLBACK INCOMPLETE\n${incomplete.join('\n')}` : 'agent-personalizer: install failed; every changed file was restored');
562
+ throw e;
563
+ } finally { committing = false; }
410
564
 
411
565
  const DOCS = onboarding.DOCS;
412
566
  // the rerun command a user can actually type: the npx form when this ran from npm's cache, else the local path that just worked
@@ -421,7 +575,7 @@ async function main() {
421
575
  const AUTO = { claude: 'CLAUDE.md (Claude Code)', agents: 'AGENTS.md (Codex, Cursor, anything that reads AGENTS.md)', gemini: 'GEMINI.md (Gemini CLI)' };
422
576
  const PASTE = {
423
577
  claude: 'claude.ai and the Claude apps read no files: paste the body of USER.md, then AGENT_ONBOARDING.md, into the project or profile instructions',
424
- chatgpt: 'ChatGPT: paste chatgpt-box1.txt and chatgpt-box2.txt into its two custom-instruction boxes',
578
+ chatgpt: 'ChatGPT: open Settings → Personalization and enable customization. Copy the exported profile (chatgpt-box1.txt) and response instructions (chatgpt-box2.txt) into the fields your current interface provides, checking its displayed limits',
425
579
  prompt: 'system-prompt.md: paste it wherever you set a system prompt',
426
580
  };
427
581
  const auto = targets.filter(t => AUTO[t]).map(t => AUTO[t]);
@@ -430,7 +584,7 @@ async function main() {
430
584
  steps.push('Read AGENT_ONBOARDING.md once: that is what every AI will be told about working with you. Re-run this installer with new answers to change it.\n USER.md is yours to edit freely; the onboarding file is regenerated from .agent-personalizer.json.');
431
585
  steps.push(level >= 3
432
586
  ? `Re-render after editing: node render/render.cjs --dir ${DIR} (drift check: add --check)`
433
- : `Re-render after editing by running this installer again (it keeps your files and only refreshes the rendered blocks):\n ${SELF} --dir ${DIR} --ai ${targets.join(',')} --level ${level} --yes`);
587
+ : `Re-render after editing by running this installer again (it refreshes generated outputs and untouched installer copies, and keeps and names edited files):\n ${SELF} --dir ${DIR} --ai ${targets.join(',')} --level ${level} --yes`);
434
588
  steps.push([
435
589
  auto.length ? `Read from ${root} automatically, nothing to paste: ${auto.join(', ')}.` : null,
436
590
  paste.length ? `Still needs a paste: ${paste.join('; ')}.` : null,
@@ -452,4 +606,4 @@ async function main() {
452
606
  console.log('\nIf this saved you time, a star helps people find it: https://github.com/aunysillyme/agent-personalizer');
453
607
  }
454
608
 
455
- main().catch(e => { if (e && e.status !== undefined) process.exit(e.status || 1); console.error(e.message); process.exit(1); });
609
+ main().catch(e => { if (e && e.status !== undefined) process.exit(e.status || 1); console.error(e.message); process.exit(e instanceof markers.Refusal ? 2 : 1); });