agent-personalizer 0.8.2 → 0.8.4

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/bin/global.cjs ADDED
@@ -0,0 +1,201 @@
1
+ 'use strict';
2
+ // Global targets have fixed home-relative names; profile ownership stays inside its own folder.
3
+ const fs = require('fs');
4
+ const { resolveHome } = require('./home.cjs');
5
+ const path = require('path');
6
+ const renderer = require('../render/render.cjs');
7
+ const onboarding = require('../render/onboarding.cjs');
8
+ const { sha256, validateInventory } = require('./install-plan.cjs');
9
+ const SOURCE = '.agent-personalizer';
10
+ const CONFIG = `${SOURCE}/.agent-personalizer.json`;
11
+ const TARGETS = { claude: '.claude/CLAUDE.md', agents: '.codex/AGENTS.md', gemini: '.gemini/GEMINI.md' };
12
+ const HASH = /^[a-f0-9]{64}$/;
13
+ const refuse = message => { throw new renderer.Refusal(message); };
14
+
15
+ function decode(bytes, rel) {
16
+ try { return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); }
17
+ catch (_) { refuse(`${rel} is not valid UTF-8; nothing was written`); }
18
+ }
19
+ function blockHash(text, rel) {
20
+ const ms = renderer.markerState(text, rel);
21
+ if (ms.kind === 'malformed') refuse(`${rel}: malformed marker block; nothing was changed`);
22
+ return ms.kind === 'one' ? sha256(Buffer.from(text.slice(ms.bStart, ms.eEnd))) : null;
23
+ }
24
+ function validateGlobal(cfg) {
25
+ if (!cfg.global || cfg.level !== 1) refuse('global profile config must identify a level-1 global install');
26
+ for (const target of cfg.targets || []) if (!Object.hasOwn(TARGETS, target) && target !== 'onboarding') refuse(`unsupported global target: ${target}`);
27
+ if (cfg.globalFiles !== undefined && (!cfg.globalFiles || typeof cfg.globalFiles !== 'object' || Array.isArray(cfg.globalFiles))) refuse('invalid global target inventory');
28
+ for (const [key, info] of Object.entries(cfg.globalFiles || {})) {
29
+ if (!Object.hasOwn(TARGETS, key) || !info || typeof info.created !== 'boolean' || !HASH.test(info.blockHash) || !HASH.test(info.fileHash)
30
+ || !['', '\n', '\n\n'].includes(info.separator) || typeof info.appended !== 'boolean') refuse('invalid global target ownership');
31
+ }
32
+ if (cfg.globalDirectories !== undefined && (!Array.isArray(cfg.globalDirectories) || cfg.globalDirectories.some(rel => ![SOURCE, '.claude', '.codex', '.gemini'].includes(rel)))) refuse('invalid global directory inventory');
33
+ }
34
+
35
+ async function run({ args, commitPlan, probe, readConfig, ask }) {
36
+ const prior = renderer.DIE_THROWS;
37
+ renderer.DIE_THROWS = true;
38
+ try { return await execute({ args, commitPlan, probe, readConfig, ask }); }
39
+ finally { renderer.DIE_THROWS = prior; }
40
+ }
41
+ async function execute({ args, commitPlan, probe, readConfig, ask }) {
42
+ if ('--dir' in args) refuse('--global cannot be combined with --dir');
43
+ if ('--level' in args && args['--level'] !== '1') refuse('--global supports only --level 1');
44
+ const home = resolveHome();
45
+ const info = fs.lstatSync(home);
46
+ if (info.isSymbolicLink() || !info.isDirectory()) refuse('global home must be a real directory, never a symlink');
47
+ const root = fs.realpathSync(home);
48
+ const source = probe(root, SOURCE);
49
+ if (source.exists && !fs.lstatSync(source.full).isDirectory()) refuse(`${SOURCE} is not a directory`);
50
+ const profileRoot = path.join(root, SOURCE);
51
+ const stored = readConfig(profileRoot, 1);
52
+ if (stored.cfgExists) validateGlobal(stored.cfg);
53
+ if (args.command === 'learn') {
54
+ for (const opt of ['--ai', '--level', '--answers', '--defaults', '--quick', '--full', '--uninstall', '--dry']) if (opt in args) refuse(`${opt} is not a learn option`);
55
+ if (args['--forget'] && (args['--all-projects'] || args['--yes'])) refuse('--forget cannot be combined with --all-projects or --yes');
56
+ if (!stored.cfgExists) refuse(`missing config: expected ${path.join(root, CONFIG)}`);
57
+ const learning = require('./learn.cjs');
58
+ return args['--forget'] ? learning.forget(profileRoot) : learning.learn({ dir: profileRoot, yes: !!args['--yes'], allProjects: true });
59
+ }
60
+ if (args['--forget'] || args['--all-projects']) refuse('--forget and --all-projects need learn');
61
+ if (args['--uninstall']) {
62
+ for (const opt of ['--ai', '--level', '--answers', '--defaults', '--quick', '--full']) if (opt in args) refuse(`${opt} is an install option; --uninstall reads the stored config`);
63
+ if (!stored.cfgExists) refuse(`missing config: expected ${path.join(root, CONFIG)}`);
64
+ return uninstall({ root, cfg: stored.cfg, dry: !!args['--dry'], commitPlan, probe });
65
+ }
66
+ if (args['--dry']) refuse('--dry needs --uninstall');
67
+ const interactive = !!process.stdin.isTTY && !args['--yes'];
68
+ if (!stored.cfgExists && !interactive && (!args['--yes'] || !args['--ai'])) refuse('non-interactive --global needs --ai and --yes');
69
+ let ais = args['--ai'] || (stored.cfgExists ? stored.cfg.targets.filter(t => t !== 'onboarding').join(',') : 'claude,agents');
70
+ if (interactive && !stored.cfgExists) ais = await ask('Global AIs (claude,agents,gemini)', ais);
71
+ const targets = ais.split(',').map(s => s.trim()).filter(Boolean);
72
+ if (!targets.length || new Set(targets).size !== targets.length) refuse('choose each global AI once');
73
+ for (const key of targets) if (!Object.hasOwn(TARGETS, key)) refuse(`--global supports only claude, agents and gemini (unsupported target: ${key})`);
74
+ if (args['--answers'] && args['--defaults']) refuse('--answers and --defaults are exclusive');
75
+ let answers = stored.prevAnswers || onboarding.defaults();
76
+ if (args['--answers']) {
77
+ const file = args['--answers'];
78
+ try { answers = onboarding.validate(JSON.parse(fs.readFileSync(file === '-' ? 0 : path.resolve(file), 'utf8'))); }
79
+ catch (e) { refuse(`--answers: ${e.message}`); }
80
+ }
81
+ const old = stored.cfg;
82
+ const installed = { ...(old.installed || {}) };
83
+ const writes = [];
84
+ const read = rel => {
85
+ const found = probe(root, `${SOURCE}/${rel}`);
86
+ if (!found.exists) return null;
87
+ if (!fs.lstatSync(found.full).isFile()) refuse(`${SOURCE}/${rel} is not a regular file`);
88
+ return fs.readFileSync(found.full);
89
+ };
90
+ // Validate the complete previous inventory, including paths omitted by this run.
91
+ for (const rel of Object.keys(installed)) read(rel);
92
+ for (const rel of old.createdDirectories || []) {
93
+ const found = probe(root, `${SOURCE}/${rel}`);
94
+ if (found.exists && !fs.lstatSync(found.full).isDirectory()) refuse(`${rel} is not a directory`);
95
+ }
96
+ renderer.preflightSources(profileRoot);
97
+ const learnedBytes = read('LEARNED.md');
98
+ const plannedLearned = learnedBytes || fs.readFileSync(path.join(__dirname, '../templates/LEARNED.md'));
99
+ const learned = { ...onboarding.parseLearned(decode(plannedLearned, 'LEARNED.md'), 'LEARNED.md'), hash: sha256(plannedLearned) };
100
+ const profile = read('USER.md');
101
+ const user = !profile || (installed['USER.md'] && sha256(profile) === installed['USER.md'])
102
+ ? Buffer.from(onboarding.renderUser(answers, { notesScaffolded: false, entries: learned })) : profile;
103
+ function writeSource(rel, bytes, firstOnly = false) {
104
+ const existing = read(rel);
105
+ if (existing && (firstOnly || installed[rel] !== sha256(existing))) { console.log(`kept ${SOURCE}/${rel} (edited or pre-existing)`); return; }
106
+ installed[rel] = sha256(bytes);
107
+ writes.push({ rel: `${SOURCE}/${rel}`, bytes });
108
+ }
109
+ writeSource('USER.md', user);
110
+ if (!learnedBytes) writeSource('LEARNED.md', plannedLearned, true);
111
+ const cfg = { ...old, global: true, targets: [...targets, 'onboarding'], level: 1, ruleSet: 'core-5', onboarding: onboarding.sparse(answers), installed,
112
+ createdDirectories: old.createdDirectories || [], globalFiles: { ...(old.globalFiles || {}) }, toolingVersion: require('../package.json').version };
113
+ const renderCfg = { ...cfg, onboarding: answers };
114
+ const rendered = renderer.renderedContents(profileRoot, renderCfg, { profileSource: decode(user, 'USER.md'), learned });
115
+ const qualify = text => text
116
+ .replace(/`USER\.md` sits next to `(?:CLAUDE|AGENTS)\.md`\./g, 'Read `USER.md` from the global profile source.')
117
+ .replace(/"npx agent-personalizer --dir \.", or "node render\/render\.cjs --dir \." at level 3/g, '"npx agent-personalizer --global"')
118
+ .replace(/(^|[^A-Za-z0-9_./-])(USER\.md|LEARNED\.md|AGENT_ONBOARDING\.md|\.agent-personalizer\.json|\.agent-personalizer\/digest\.md)(?![A-Za-z0-9_/-])/g, (_, prefix, rel) => prefix + path.join(profileRoot, rel));
119
+ for (const entry of rendered) {
120
+ if (entry.key === 'onboarding') { writeSource(entry.rel, Buffer.from(renderer.splice(null, qualify(entry.block), entry.rel))); continue; }
121
+ const rel = TARGETS[entry.key];
122
+ const found = probe(root, rel);
123
+ if (found.exists && !fs.lstatSync(found.full).isFile()) refuse(`${rel} is not a regular file`);
124
+ const text = found.exists ? decode(fs.readFileSync(found.full), rel) : null;
125
+ const ms = text === null ? { kind: 'none' } : renderer.markerState(text, rel);
126
+ if (ms.kind === 'malformed') refuse(`${rel}: malformed marker block`);
127
+ if (ms.kind === 'one' && !Object.hasOwn(cfg.globalFiles, entry.key)) {
128
+ refuse(`${rel}: foreign agent-personalizer block; remove the block from <!-- agent-personalizer:begin --> through <!-- agent-personalizer:end -->, then re-run --global. Nothing was written`);
129
+ }
130
+ const block = `Profile source: \`${path.join(profileRoot, 'USER.md')}\`. Read \`${path.join(profileRoot, 'AGENT_ONBOARDING.md')}\` for working preferences.\n\n` + qualify(entry.block);
131
+ const output = renderer.splice(text, block, rel);
132
+ if (renderer.markerState(output, rel).kind !== 'one' || renderer.between(output, rel) !== block) refuse(`${rel}: generated block would not re-parse; nothing was written`);
133
+ const prior = ms.kind === 'one' ? cfg.globalFiles[entry.key] : null;
134
+ cfg.globalFiles[entry.key] = { created: !found.exists || !!cfg.globalFiles[entry.key]?.created, blockHash: blockHash(output, rel), fileHash: sha256(Buffer.from(output)),
135
+ appended: prior ? prior.appended : ms.kind === 'none', separator: prior ? prior.separator : (text === null ? '' : text.endsWith('\n') ? '\n' : '\n\n') };
136
+ writes.push({ rel, bytes: Buffer.from(output), report: `update ${rel} (global profile)` });
137
+ }
138
+ const learnRequested = interactive && !stored.cfgExists ? await require('./learn.cjs').requestConsent({ allProjects: true }) : false;
139
+ const outputPaths = new Set([CONFIG, ...writes.map(p => p.rel)]);
140
+ await commitPlan(root, { writes, outputPaths,
141
+ prepare(newDirectories) {
142
+ cfg.globalDirectories = [...new Set([...(old.globalDirectories || []), ...[...newDirectories].filter(rel => [SOURCE, '.claude', '.codex', '.gemini'].includes(rel))])].sort();
143
+ writes.push({ rel: CONFIG, bytes: Buffer.from(JSON.stringify(cfg, null, 2) + '\n') });
144
+ }
145
+ });
146
+ if (learnRequested) await require('./learn.cjs').learn({ dir: profileRoot, consented: true, allProjects: true });
147
+ console.log(`Global profile installed. Re-run with --global after editing ${profileRoot}.`);
148
+ }
149
+
150
+ async function uninstall({ root, cfg, dry, commitPlan, probe }) {
151
+ validateInventory(cfg);
152
+ const writes = [], removals = [], retained = [];
153
+ const read = rel => {
154
+ const found = probe(root, rel);
155
+ if (!found.exists) return null;
156
+ if (!fs.lstatSync(found.full).isFile()) refuse(`${rel} is not a regular file; nothing was removed`);
157
+ return fs.readFileSync(found.full);
158
+ };
159
+ for (const [key, owned] of Object.entries(cfg.globalFiles || {})) {
160
+ const rel = TARGETS[key], bytes = read(rel);
161
+ if (!bytes) continue;
162
+ const text = decode(bytes, rel), ms = renderer.markerState(text, rel);
163
+ const currentHash = blockHash(text, rel);
164
+ if (ms.kind === 'none') continue;
165
+ if (currentHash !== owned.blockHash) { retained.push(rel); continue; }
166
+ let before = text.slice(0, ms.bStart), after = text.slice(ms.eEnd);
167
+ if (after.startsWith('\r\n')) after = after.slice(2);
168
+ else if (after.startsWith('\n')) after = after.slice(1);
169
+ if (owned.appended) {
170
+ if (owned.separator && before.endsWith(owned.separator)) before = before.slice(0, -owned.separator.length);
171
+ }
172
+ const output = before + after;
173
+ if (owned.created && output === '') removals.push({ rel });
174
+ else writes.push({ rel, bytes: Buffer.from(output) });
175
+ }
176
+ for (const [rel, hash] of Object.entries(cfg.installed || {})) {
177
+ const fullRel = `${SOURCE}/${rel}`, bytes = read(fullRel);
178
+ if (!bytes) continue;
179
+ if (sha256(bytes) === hash) removals.push({ rel: fullRel });
180
+ else retained.push(fullRel);
181
+ }
182
+ const directories = [...(cfg.globalDirectories || []), ...(cfg.createdDirectories || []).map(rel => `${SOURCE}/${rel}`)];
183
+ for (const rel of directories) {
184
+ const found = probe(root, rel);
185
+ if (found.exists && !fs.lstatSync(found.full).isDirectory()) refuse(`${rel} is not a directory`);
186
+ }
187
+ if (!retained.length) removals.push({ rel: CONFIG });
188
+ for (const rel of retained) console.log(`kept ${rel} (edited)`);
189
+ if (dry) {
190
+ for (const p of [...writes, ...removals]) console.log(`would ${p.bytes ? 'update' : 'remove'} ${p.rel}`);
191
+ return;
192
+ }
193
+ const outputPaths = new Set([...writes, ...removals].map(p => p.rel));
194
+ await commitPlan(root, { writes, removals, outputPaths });
195
+ for (const rel of directories.sort((a, b) => b.split('/').length - a.split('/').length)) {
196
+ const found = probe(root, rel);
197
+ if (found.exists && fs.readdirSync(found.full).length === 0) fs.rmdirSync(found.full);
198
+ }
199
+ console.log(retained.length ? 'Global configuration kept for review of edited files.' : 'Global profile uninstalled.');
200
+ }
201
+ module.exports = { run };
package/bin/home.cjs ADDED
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+ const path = require('path');
3
+ const { Refusal } = require('../render/render.cjs');
4
+
5
+ function resolveHome(home = process.env.HOME) {
6
+ if (process.platform === 'win32' && (home === undefined || home === '')) home = process.env.USERPROFILE;
7
+ // On Windows a root-relative path such as \foo is "absolute" but lands on the current drive; require a drive or UNC root.
8
+ const rooted = path.sep !== '\\' || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/?.]+[\\/][^\\/]+)/.test(home || '');
9
+ if (typeof home !== 'string' || !home || !path.isAbsolute(home) || !rooted) {
10
+ throw new Refusal('HOME (or USERPROFILE on Windows) must be set to a non-empty absolute path; nothing was written');
11
+ }
12
+ return home;
13
+ }
14
+
15
+ module.exports = { resolveHome };
@@ -90,7 +90,7 @@ function migrateHome(current, previous, next, markerState) {
90
90
  return { text: lines.map(line => line.raw).join(''), edited, changed };
91
91
  }
92
92
 
93
- function installPlan({ answers, level, targets, notesScaffolded }) {
93
+ function installPlan({ answers, level, targets, notesScaffolded, legacyRules = false }) {
94
94
  const base = onboarding.baseFor(answers);
95
95
  const kind = onboarding.kindOf(answers);
96
96
  const plan = []; // { rel, src | text }
@@ -127,7 +127,12 @@ function installPlan({ answers, level, targets, notesScaffolded }) {
127
127
  let t = fs.readFileSync(path.join(PKG, 'templates', name), 'utf8');
128
128
  if (level < 3) {
129
129
  // no local rules/: the pointers point at the rendered block below, which carries the full text
130
- t = t.split('\n').filter(l => !/Rules, one file each, the owning copy/.test(l)).join('\n');
130
+ const core = require('../render/render.cjs').CORE_RULE_FILES;
131
+ t = t.split('\n').filter(l => {
132
+ if (/Rules, one file each, the owning copy/.test(l)) return false;
133
+ const rule = /\[owner: rules\/([^\]]+)\]/.exec(l);
134
+ return legacyRules || !rule || core.has(rule[1]);
135
+ }).join('\n');
131
136
  t = t.replace(/`\[owner: rules\/[^\]]+\]`/g, '`[owner: the rendered block below]`');
132
137
  }
133
138
  if (notesWhy) {
@@ -52,6 +52,9 @@
52
52
  },
53
53
  "v0.7.2": {
54
54
  "original": "ba6495eedfff5c5ea3658e4b7c4072f7505b0860414d67150e090366ca87e772"
55
+ },
56
+ "v0.8.4": {
57
+ "original": "ba6495eedfff5c5ea3658e4b7c4072f7505b0860414d67150e090366ca87e772"
55
58
  }
56
59
  },
57
60
  "check/gate.cjs": {
@@ -99,6 +102,9 @@
99
102
  },
100
103
  "v0.7.2": {
101
104
  "original": "52e959a266d68e1e9f0de1373786bdfb5a7792c093145813623714d7d4f83c86"
105
+ },
106
+ "v0.8.4": {
107
+ "original": "f9e1fb60929fd97cc52df93662b6faa39a022d95d83115c925b7c2047b12ab7c"
102
108
  }
103
109
  },
104
110
  "hooks/README.md": {
@@ -169,6 +175,10 @@
169
175
  "v0.7.2": {
170
176
  "original": "fb1daf41acd72d3bf01fb620b8f8f09f118154b983d634547352b944c07f72bc",
171
177
  "withoutSignature": "fb1daf41acd72d3bf01fb620b8f8f09f118154b983d634547352b944c07f72bc"
178
+ },
179
+ "v0.8.4": {
180
+ "original": "7dbb140c6b56a895500d43c71a95e36b2c8ab90b0a240e2f8a042368fed3ea67",
181
+ "withoutSignature": "7dbb140c6b56a895500d43c71a95e36b2c8ab90b0a240e2f8a042368fed3ea67"
172
182
  }
173
183
  },
174
184
  "hooks/claude-code/session-start.sh": {
@@ -222,6 +232,9 @@
222
232
  },
223
233
  "v0.7.2": {
224
234
  "original": "282024ff74e8a7168c49dcd75e45d61da6709c8901f5f91938fc02cdc7c5cfed"
235
+ },
236
+ "v0.8.4": {
237
+ "original": "282024ff74e8a7168c49dcd75e45d61da6709c8901f5f91938fc02cdc7c5cfed"
225
238
  }
226
239
  },
227
240
  "render/onboarding.cjs": {
@@ -269,6 +282,9 @@
269
282
  },
270
283
  "v0.7.2": {
271
284
  "original": "0a06b8fec458b98ed9a5219c02a592d3b3692187d279f2809db6058f7cb2d395"
285
+ },
286
+ "v0.8.4": {
287
+ "original": "eda6c3c068afed1ad195b6a5824e3feacdafb030c4678320634db1a29f74f090"
272
288
  }
273
289
  },
274
290
  "render/render.cjs": {
@@ -316,6 +332,9 @@
316
332
  },
317
333
  "v0.7.2": {
318
334
  "original": "a1ed005b082508c357569212d09f3e72b4b6cf3062c76d18796c6902a7195d1a"
335
+ },
336
+ "v0.8.4": {
337
+ "original": "b460b61a32f1fad0335cdd8cba6aaba25b8da52d0ddaebfd0ad8b06f9b8bedd6"
319
338
  }
320
339
  },
321
340
  "render/targets.json": {
@@ -369,6 +388,9 @@
369
388
  },
370
389
  "v0.7.2": {
371
390
  "original": "070209f11e929c89384d507975086955824014974886e2f84353d8b91d08fc83"
391
+ },
392
+ "v0.8.4": {
393
+ "original": "070209f11e929c89384d507975086955824014974886e2f84353d8b91d08fc83"
372
394
  }
373
395
  },
374
396
  "rules/00-read-the-profile-first.md": {
@@ -439,6 +461,10 @@
439
461
  "v0.7.2": {
440
462
  "original": "3806ff9a3f4bd539d1689c56bfa6397eb29938f9400117cecc1f487cdf6506a2",
441
463
  "withoutSignature": "3806ff9a3f4bd539d1689c56bfa6397eb29938f9400117cecc1f487cdf6506a2"
464
+ },
465
+ "v0.8.4": {
466
+ "original": "b937d12b1987a8b13e8d80ae143e1d7b74f84dda4541c361813367bd2f6002a9",
467
+ "withoutSignature": "b937d12b1987a8b13e8d80ae143e1d7b74f84dda4541c361813367bd2f6002a9"
442
468
  }
443
469
  },
444
470
  "rules/10-evidence-before-assertion.md": {
@@ -509,6 +535,10 @@
509
535
  "v0.7.2": {
510
536
  "original": "ce6f7862af2078617433899aec3419227c116dd2722d47e7234d5b7615e1559d",
511
537
  "withoutSignature": "ce6f7862af2078617433899aec3419227c116dd2722d47e7234d5b7615e1559d"
538
+ },
539
+ "v0.8.4": {
540
+ "original": "ce6f7862af2078617433899aec3419227c116dd2722d47e7234d5b7615e1559d",
541
+ "withoutSignature": "ce6f7862af2078617433899aec3419227c116dd2722d47e7234d5b7615e1559d"
512
542
  }
513
543
  },
514
544
  "rules/20-one-owner-per-rule.md": {
@@ -579,6 +609,10 @@
579
609
  "v0.7.2": {
580
610
  "original": "5268e490404da41e4474a368e9b4ff38ba6375bcbc5c643ee742ceacd9c8535c",
581
611
  "withoutSignature": "5268e490404da41e4474a368e9b4ff38ba6375bcbc5c643ee742ceacd9c8535c"
612
+ },
613
+ "v0.8.4": {
614
+ "original": "5268e490404da41e4474a368e9b4ff38ba6375bcbc5c643ee742ceacd9c8535c",
615
+ "withoutSignature": "5268e490404da41e4474a368e9b4ff38ba6375bcbc5c643ee742ceacd9c8535c"
582
616
  }
583
617
  },
584
618
  "rules/30-folder-index-is-part-of-the-change.md": {
@@ -649,6 +683,10 @@
649
683
  "v0.7.2": {
650
684
  "original": "50863f6b0ea933c6c7209bf4bbfbfc28c7481aabe9001cdd49b730f58dd3010f",
651
685
  "withoutSignature": "50863f6b0ea933c6c7209bf4bbfbfc28c7481aabe9001cdd49b730f58dd3010f"
686
+ },
687
+ "v0.8.4": {
688
+ "original": "50863f6b0ea933c6c7209bf4bbfbfc28c7481aabe9001cdd49b730f58dd3010f",
689
+ "withoutSignature": "50863f6b0ea933c6c7209bf4bbfbfc28c7481aabe9001cdd49b730f58dd3010f"
652
690
  }
653
691
  },
654
692
  "rules/40-sign-every-edit.md": {
@@ -719,6 +757,10 @@
719
757
  "v0.7.2": {
720
758
  "original": "ec73f0d745eb106a3632f22383ecf4ab5f7b0f89657a9dd5f1bf3657c7d96562",
721
759
  "withoutSignature": "ec73f0d745eb106a3632f22383ecf4ab5f7b0f89657a9dd5f1bf3657c7d96562"
760
+ },
761
+ "v0.8.4": {
762
+ "original": "ec73f0d745eb106a3632f22383ecf4ab5f7b0f89657a9dd5f1bf3657c7d96562",
763
+ "withoutSignature": "ec73f0d745eb106a3632f22383ecf4ab5f7b0f89657a9dd5f1bf3657c7d96562"
722
764
  }
723
765
  },
724
766
  "rules/50-output-style.md": {
@@ -789,6 +831,10 @@
789
831
  "v0.7.2": {
790
832
  "original": "56a8f916863e730185c092c5b78750c12fadf926d41e435f151f251d94d933c4",
791
833
  "withoutSignature": "56a8f916863e730185c092c5b78750c12fadf926d41e435f151f251d94d933c4"
834
+ },
835
+ "v0.8.4": {
836
+ "original": "56a8f916863e730185c092c5b78750c12fadf926d41e435f151f251d94d933c4",
837
+ "withoutSignature": "56a8f916863e730185c092c5b78750c12fadf926d41e435f151f251d94d933c4"
792
838
  }
793
839
  },
794
840
  "rules/60-act-or-ask.md": {
@@ -859,6 +905,10 @@
859
905
  "v0.7.2": {
860
906
  "original": "77e3fc8f0064c5f537f4ee6991aef77b865fee756e20c9cab8ccc1137f520b30",
861
907
  "withoutSignature": "77e3fc8f0064c5f537f4ee6991aef77b865fee756e20c9cab8ccc1137f520b30"
908
+ },
909
+ "v0.8.4": {
910
+ "original": "77e3fc8f0064c5f537f4ee6991aef77b865fee756e20c9cab8ccc1137f520b30",
911
+ "withoutSignature": "77e3fc8f0064c5f537f4ee6991aef77b865fee756e20c9cab8ccc1137f520b30"
862
912
  }
863
913
  },
864
914
  "rules/README.md": {
@@ -929,6 +979,34 @@
929
979
  "v0.7.2": {
930
980
  "original": "d5a069dca7b498041992df74bbffd9907b68157709b239cece3d47106862eb48",
931
981
  "withoutSignature": "e6bf5ac7404aaa264a0b7a1889389e891cb759667d99dd5bef803d96440b8607"
982
+ },
983
+ "v0.8.4": {
984
+ "original": "ef9e995f8a72fcaaac48eb1d2bde567a9f39559f64a6b921f924e7f460e76db8",
985
+ "withoutSignature": "534c18e439aced0f80ddaea04db31cf0df01f0cfcce17cfb84e88bffb740ff53"
986
+ }
987
+ },
988
+ "rules/65-ask-before-it-repeats.md": {
989
+ "v0.8.4": {
990
+ "original": "cbb8a463ab3ad3ac0d27a77fc99f98b773b355ce336f9c727ce8bb56c3a27dab",
991
+ "withoutSignature": "cbb8a463ab3ad3ac0d27a77fc99f98b773b355ce336f9c727ce8bb56c3a27dab"
992
+ }
993
+ },
994
+ "rules/70-their-words-point-at-the-thing.md": {
995
+ "v0.8.4": {
996
+ "original": "7d2765cc47762494634a5ec691f7f706ddc6e6f672a99ab8b60eb9d6bdcea505",
997
+ "withoutSignature": "7d2765cc47762494634a5ec691f7f706ddc6e6f672a99ab8b60eb9d6bdcea505"
998
+ }
999
+ },
1000
+ "rules/80-symptoms-are-not-causes.md": {
1001
+ "v0.8.4": {
1002
+ "original": "a6b67644715fa291acfa7db16d169b58599b1b70975a5488b901b332c609cc5d",
1003
+ "withoutSignature": "a6b67644715fa291acfa7db16d169b58599b1b70975a5488b901b332c609cc5d"
1004
+ }
1005
+ },
1006
+ "rules/90-surface-what-they-cant-see.md": {
1007
+ "v0.8.4": {
1008
+ "original": "27f16a59ab223195e8bdec69a92bf6edbd84423ecd85c797bb3288658b5982e1",
1009
+ "withoutSignature": "27f16a59ab223195e8bdec69a92bf6edbd84423ecd85c797bb3288658b5982e1"
932
1010
  }
933
1011
  }
934
1012
  }
package/bin/learn.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // Consent separates project inspection from access to the AI apps' private history.
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
- const os = require('os');
5
+ const { resolveHome } = require('./home.cjs');
6
6
  const crypto = require('crypto');
7
7
  const readline = require('readline');
8
8
  const renderer = require('../render/render.cjs');
@@ -155,7 +155,7 @@ async function learn({ dir = '.', yes = false, consented = false, allProjects =
155
155
  const terms = list.exists ? require('../check/gate.cjs').loadList(list.full, { allowEmpty: true }).terms : [];
156
156
  const entries = renderer.readLearned(root);
157
157
  const sources = [...new Set((cfg.targets || []).map(target => SOURCE[target]).filter(Boolean))];
158
- const home = os.homedir();
158
+ const home = resolveHome();
159
159
  const data = await require('./sessions.cjs').readSessions({ home, projectDir: root, allProjects, sources, limit: 20, privateTerms: terms });
160
160
  const now = new Date().toISOString();
161
161
  const text = digestText(data, entries, { sources, home, terms, now });
package/bin/sessions.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
- const os = require('node:os');
5
+ const { resolveHome } = require('./home.cjs');
6
6
  const crypto = require('node:crypto');
7
7
 
8
8
  const MAX_LINE = 8 * 1024 * 1024;
@@ -249,7 +249,21 @@ function parsedLine(line, state) {
249
249
  }
250
250
 
251
251
  function baseSession(file) {
252
- return { source: file.source, date: new Date(file.mtimeMs).toISOString(), project: file.project, sessionId: path.basename(file.file), file: file.file, mtimeMs: file.mtimeMs, messages: [] };
252
+ return { source: file.source, date: new Date(file.mtimeMs).toISOString(), project: file.project, sessionId: path.basename(file.file), file: file.file, mtimeMs: file.mtimeMs, timestampMs: null, messages: [] };
253
+ }
254
+
255
+ function messageTimestamp(session, timestamp) {
256
+ const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/;
257
+ let parsed = NaN;
258
+ if (typeof timestamp === 'string' && iso.test(timestamp)) {
259
+ const calendar = new Date(`${timestamp.slice(0, 10)}T00:00:00Z`);
260
+ if (Number.isFinite(calendar.getTime()) && calendar.toISOString().slice(0, 10) === timestamp.slice(0, 10)) parsed = Date.parse(timestamp);
261
+ } else if (typeof timestamp === 'number' && timestamp >= 1e11) parsed = new Date(timestamp).getTime();
262
+ const time = Math.min(parsed, session.mtimeMs);
263
+ if (Number.isFinite(time) && (session.timestampMs === null || time > session.timestampMs)) {
264
+ session.timestampMs = time;
265
+ session.date = new Date(time).toISOString();
266
+ }
253
267
  }
254
268
 
255
269
  async function readClaude(file, state) {
@@ -261,6 +275,7 @@ async function readClaude(file, state) {
261
275
  if (!record) return;
262
276
  if (typeof record.cwd === 'string') sessionCwd = record.cwd;
263
277
  if (typeof record.entrypoint === 'string' && record.entrypoint.startsWith('sdk')) automation = true;
278
+ if (record.type === 'user' || record.type === 'assistant') messageTimestamp(session, record.timestamp);
264
279
  if (record.type !== 'user') return;
265
280
  known = true;
266
281
  if (!state.allProjects && !belongsToProject(sessionCwd, state.projectDir)) {
@@ -299,7 +314,9 @@ async function readCodex(file, state) {
299
314
  if (typeof meta.cwd === 'string') session.project = path.basename(meta.cwd);
300
315
  return;
301
316
  }
302
- if (record.type !== 'response_item' || !record.payload || record.payload.type !== 'message' || record.payload.role !== 'user') return;
317
+ if (record.type !== 'response_item' || !record.payload || record.payload.type !== 'message') return;
318
+ messageTimestamp(session, record.timestamp);
319
+ if (record.payload.role !== 'user') return;
303
320
  known = true;
304
321
  if (!projectMatches) {
305
322
  if (!state.allProjects) bump(state, 'project_unknown');
@@ -330,7 +347,9 @@ async function readGemini(file, state) {
330
347
  });
331
348
  if (!ok) return [];
332
349
  for (const message of messages) {
333
- if (!message || message.type !== 'user') continue;
350
+ if (!message) continue;
351
+ messageTimestamp(session, message.timestamp);
352
+ if (message.type !== 'user') continue;
334
353
  const items = Array.isArray(message.content) ? message.content.filter(item => item && typeof item.text === 'string' && (!item.type || item.type === 'text')).map(item => item.text) : [];
335
354
  const text = typedText(items, state);
336
355
  if (text) session.messages.push(text);
@@ -346,16 +365,19 @@ async function readGeminiLogs(file, state) {
346
365
  function accept() {
347
366
  if (oversize) { bump(state, 'oversize_line'); return; }
348
367
  const record = parsedLine(entry, state);
349
- if (!record || record.type !== 'user') return;
350
- if (typeof record.sessionId !== 'string' || typeof record.message !== 'string') { bump(state, 'unknown_format'); return; }
351
- const text = typedText([record.message], state);
352
- if (!text) return;
368
+ if (!record || !['user', 'gemini', 'assistant'].includes(record.type)) return;
369
+ if (typeof record.sessionId !== 'string' || (record.type === 'user' && typeof record.message !== 'string')) { bump(state, 'unknown_format'); return; }
353
370
  if (!grouped.has(record.sessionId)) {
354
371
  const session = baseSession(file);
355
372
  session.sessionId = record.sessionId;
356
373
  grouped.set(record.sessionId, session);
357
374
  }
358
- grouped.get(record.sessionId).messages.push(text);
375
+ const session = grouped.get(record.sessionId);
376
+ messageTimestamp(session, record.timestamp);
377
+ if (record.type === 'user') {
378
+ const text = typedText([record.message], state);
379
+ if (text) session.messages.push(text);
380
+ }
359
381
  }
360
382
  const ok = await scanLines(file.file, state, line => {
361
383
  for (const character of `${line}\n`) {
@@ -393,7 +415,7 @@ async function readGeminiLogs(file, state) {
393
415
  if (!ok) return [];
394
416
  if (!started || invalid) { bump(state, 'unknown_format'); return []; }
395
417
  if (!finished || depth) bump(state, 'malformed_line');
396
- return [...grouped.values()];
418
+ return [...grouped.values()].filter(session => session.messages.length);
397
419
  }
398
420
 
399
421
  async function readMemory(file, state) {
@@ -405,12 +427,12 @@ async function readMemory(file, state) {
405
427
  return { file: file.file, text, date: new Date(file.mtimeMs).toISOString() };
406
428
  }
407
429
 
408
- async function readSessions({ home = os.homedir(), projectDir = process.cwd(), allProjects = false, sources = [], limit = 20, privateTerms = [] } = {}) {
430
+ async function readSessions({ home = resolveHome(), projectDir = process.cwd(), allProjects = false, sources = [], limit = 20, privateTerms = [] } = {}) {
409
431
  const selectedSources = new Set(Array.isArray(sources) ? sources.filter(source => SOURCES.has(source)) : []);
410
432
  const maximum = Number.isInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 20;
411
433
  projectDir = path.resolve(projectDir);
412
434
  const state = {
413
- home: path.resolve(home), projectDir, allProjects,
435
+ home: path.resolve(resolveHome(home)), projectDir, allProjects,
414
436
  geminiProjectHash: crypto.createHash('sha256').update(projectDir).digest('hex'),
415
437
  candidates: [], memoryFiles: [], filesRead: [], filesChecked: 0, skipped: {},
416
438
  privateTerms: Array.isArray(privateTerms) ? privateTerms.filter(term => typeof term === 'string' && fold(term).trim()).map(fold) : []
@@ -418,22 +440,33 @@ async function readSessions({ home = os.homedir(), projectDir = process.cwd(), a
418
440
  await discover(state.home, selectedSources, state);
419
441
  state.candidates.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file));
420
442
  const sessions = [], geminiSessions = new Map();
443
+ // Multiple Gemini files can contribute to the same session, including its fallback timestamp.
444
+ // Keep that full merge; independent sessions admit an mtime bound.
445
+ const bounded = state.candidates.filter(file => file.source === 'gemini-cli').length < 2;
446
+ const sortKey = session => session.timestampMs ?? session.mtimeMs;
447
+ const compare = (a, b) => sortKey(b) - sortKey(a) || a.file.localeCompare(b.file) || a.sessionId.localeCompare(b.sessionId);
421
448
  const readers = { claude: readClaude, codex: readCodex, gemini: readGemini, 'gemini-logs': readGeminiLogs };
422
449
  for (const file of state.candidates) {
423
- if (sessions.length >= maximum) break;
450
+ if (!maximum) break;
451
+ if (bounded && sessions.length === maximum && file.mtimeMs < sortKey(sessions[maximum - 1])) break;
424
452
  const found = await readers[file.format](file, state);
425
453
  for (const session of found) {
426
454
  if (session.source === 'gemini-cli' && geminiSessions.has(session.sessionId)) {
427
455
  const existing = geminiSessions.get(session.sessionId);
456
+ if (session.timestampMs !== null) messageTimestamp(existing, session.timestampMs);
428
457
  for (const text of session.messages) {
429
458
  if (existing.messages.includes(text)) bump(state, 'duplicate_message');
430
459
  else existing.messages.push(text);
431
460
  }
432
- } else if (sessions.length < maximum) {
461
+ } else {
433
462
  if (session.source === 'gemini-cli') geminiSessions.set(session.sessionId, session);
434
463
  sessions.push(session);
435
464
  }
436
465
  }
466
+ sessions.sort(compare);
467
+ if (bounded) for (const session of sessions.splice(maximum)) {
468
+ if (session.source === 'gemini-cli') geminiSessions.delete(session.sessionId);
469
+ }
437
470
  }
438
471
  const memories = [];
439
472
  state.memoryFiles.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file));
@@ -442,7 +475,7 @@ async function readSessions({ home = os.homedir(), projectDir = process.cwd(), a
442
475
  const memory = await readMemory(file, state);
443
476
  if (memory) memories.push(memory);
444
477
  }
445
- return { sessions, memories, filesRead: state.filesRead, filesChecked: state.filesChecked, skipped: state.skipped };
478
+ return { sessions: sessions.slice(0, maximum), memories, filesRead: state.filesRead, filesChecked: state.filesChecked, skipped: state.skipped };
446
479
  }
447
480
 
448
481
  module.exports = { readSessions };
package/bin/uninstall.cjs CHANGED
@@ -176,7 +176,8 @@ function run(dir, dry) {
176
176
  // later package release changing rules/ or USER.md cannot make an untouched block look
177
177
  // edited (or vice versa).
178
178
  const currentBlock = renderer.between(existing, rel);
179
- const blockUnedited = recorded ? (currentBlock !== null && sha256(Buffer.from(currentBlock)) === recorded) : matchesBlock;
179
+ // Explicit adoption of an older target can record the whole file; its outer text stays user-owned.
180
+ const blockUnedited = recorded ? (currentBlock !== null && (sha256(Buffer.from(currentBlock)) === recorded || sha256(bytes) === recorded)) : matchesBlock;
180
181
  if (blockUnedited) add(rel, 'strip', Buffer.from(stripBlock(existing, ms)), 'pre-existing file; removed only the marked block');
181
182
  else add(rel, 'keep', null, ms.kind === 'none' ? 'pre-existing file; block already absent' : 'edited');
182
183
  continue;
@@ -36,7 +36,7 @@ On a re-run, each home-file line that byte-matches the previous template is migr
36
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.
37
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.
38
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.
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
+ - **Entries and evidence:** uninstall keeps `LEARNED.md` once it holds anything you wrote (an untouched template is removed). It removes the digest and its `.gitignore` only when their bytes match recorded creation hashes, and removes the private folder only when recorded as installer-created and empty. Edited or unrecorded files 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.
40
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.
41
41
  - **Configuration last:** the configuration is removed after tracked files are gone. Retained tracked files are named and keep the configuration for review.
42
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.
@@ -69,7 +69,7 @@ Learning reads up to 20 recent usable sessions from the selected Claude Code, Co
69
69
 
70
70
  The digest stays in `.agent-personalizer/digest.md`, with its contents ignored by git. Filesystem access, backups and sync services still apply. The terminal prints file names and counts, never message text. The digest is data, and the AI is instructed never to follow instructions within it. When your AI reads it, the contents go to that AI's provider again, like anything you share with it.
71
71
 
72
- Reuse only sessions you are allowed to share. Past messages can contain other people's details; add private terms before accepting. Check employer or client agreements for work accounts. agent-personalizer is not affiliated with Anthropic, OpenAI or Google; their stored formats can change. `learn --forget` and uninstall remove the digest from this install, not copies a provider, backup or sync service already received.
72
+ Reuse only sessions you are allowed to share. Past messages can contain other people's details; add private terms before accepting. Check employer or client agreements for work accounts. agent-personalizer is not affiliated with Anthropic, OpenAI or Google; their stored formats can change. `learn --forget` removes the digest from this install; uninstall removes it only under the recorded-hash conditions above. Neither removes copies a provider, backup or sync service already received.
73
73
 
74
74
  ## Instructions and companions
75
75