agent-personalizer 0.5.2 → 0.6.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.
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+ // Shared, read-only install recipe. Uninstall compares against the same templates and copies.
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const PKG = path.resolve(__dirname, '..');
6
+ const onboarding = require('../render/onboarding.cjs');
7
+
8
+ function installPlan({ answers, level, targets, notesScaffolded }) {
9
+ const base = onboarding.baseFor(answers);
10
+ const kind = onboarding.kindOf(answers);
11
+ const plan = []; // { rel, src | text }
12
+ // signature=no: the signature rule file is not installed (a `requires:` rule that is absent cannot drift back in),
13
+ // and every copied markdown loses its `Last edited by:` template line and its pointer to the rule.
14
+ const noSig = answers.signature === 'no';
15
+ const stripSig = (t) => noSig ? t.split('\n').filter(l => !l.includes('40-sign-every-edit.md') && !/^`?Last edited by:/.test(l)).join('\n') : t;
16
+ const mdCopy = (rel, src) => plan.push({ rel, text: stripSig(fs.readFileSync(src, 'utf8')) });
17
+ // rules/ is copied at level 3, where it becomes yours to edit; levels 1 and 2 render from the package's rules
18
+ if (level >= 3) for (const f of fs.readdirSync(path.join(PKG, 'rules')).sort()) {
19
+ if (noSig && f === '40-sign-every-edit.md') continue;
20
+ mdCopy(`rules/${f}`, path.join(PKG, 'rules', f));
21
+ }
22
+ // The home templates carry four `notes/...` pointer lines. They collapse to ONE line whenever the
23
+ // folder they name will not be there to read: a cloud notes tool has no local folder at all, and no
24
+ // level below 2 creates one, so a level-1 install used to hand the first session four broken
25
+ // pointers. NOTES_ONE_LINE is also what the level-2 upgrade looks for, byte for byte.
26
+ const NOTES_ONE_LINE = (why) => `- Notes: see \`AGENT_ONBOARDING.md\` § Where you may write (${why})`;
27
+ const NOTES_LATER = `no local notes folder at level 1; level 2 creates \`${base}/\``;
28
+ // Is the folder every notes pointer names going to be there to read? The README is the file the AI
29
+ // is told to read before it writes, and the level-2 scaffold creates it with the folder. The LEVEL
30
+ // alone is a proxy that is wrong in both directions: a level-1 install can land beside a notes
31
+ // folder that already exists, and a re-run at a lower level does not delete what a higher one made
32
+ // (round 1, findings 4 and 5). One boolean drives the home-file collapse and both rendered files,
33
+ // so they can never disagree about the same folder.
34
+ const notesWhy = kind === 'cloud' ? 'reached through its connector, no local files'
35
+ : !notesScaffolded ? NOTES_LATER
36
+ : kind !== 'disk' ? 'local fallback folder `notes/`'
37
+ : null; // disk, scaffold present: the four paths, retargeted at notes_path
38
+ const home = (name) => {
39
+ let t = fs.readFileSync(path.join(PKG, 'templates', name), 'utf8');
40
+ if (level < 3) {
41
+ // no local rules/: the pointers point at the rendered block below, which carries the full text
42
+ t = t.split('\n').filter(l => !/Rules, one file each, the owning copy/.test(l)).join('\n');
43
+ t = t.replace(/`\[owner: rules\/[^\]]+\]`/g, '`[owner: the rendered block below]`');
44
+ }
45
+ if (notesWhy) {
46
+ let done = false;
47
+ t = t.split('\n').filter(l => { if (!/`notes\//.test(l)) return true; if (done) return false; done = true; return true; })
48
+ .map(l => /`notes\//.test(l) ? NOTES_ONE_LINE(notesWhy) : l).join('\n');
49
+ } else if (base !== 'notes') t = t.replace(/\bnotes\//g, `${base}/`);
50
+ return stripSig(t);
51
+ };
52
+ const POINTER = 'pointer file; the renderer fills its block below';
53
+ if (targets.includes('claude')) plan.push({ rel: 'CLAUDE.md', text: home('CLAUDE.md'), note: POINTER });
54
+ if (targets.includes('agents')) plan.push({ rel: 'AGENTS.md', text: home('AGENTS.md'), note: POINTER });
55
+ if (level >= 2 && kind !== 'cloud') { // a cloud tool's notes are not local files; no folder named after a workspace
56
+ mdCopy(`${base}/README.md`, path.join(PKG, 'templates', 'FOLDER_README.md'));
57
+ mdCopy(`${base}/sessions/TEMPLATE-week.md`, path.join(PKG, 'templates', 'session-log.md'));
58
+ mdCopy(`${base}/decisions.md`, path.join(PKG, 'templates', 'decisions-log.md'));
59
+ mdCopy(`${base}/inbox/README.md`, path.join(PKG, 'templates', 'INBOX_README.md'));
60
+ }
61
+ if (level >= 3) {
62
+ for (const rel of ['render/render.cjs', 'render/targets.json', 'render/onboarding.cjs', 'hooks/README.md', 'hooks/claude-code/session-start.sh', 'check/gate.cjs', 'check/forbidden.example.txt'])
63
+ plan.push({ rel, src: path.join(PKG, rel) });
64
+ }
65
+
66
+ return { plan, stripSig, notesWhy, NOTES_ONE_LINE, NOTES_LATER };
67
+ }
68
+
69
+ module.exports = { installPlan };
@@ -0,0 +1,248 @@
1
+ 'use strict';
2
+ // Plan every deletion from stored answers and current sources before changing anything.
3
+ // Installed JavaScript is compared as bytes, never loaded or executed.
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+ const renderer = require('../render/render.cjs');
8
+ const onboarding = require('../render/onboarding.cjs');
9
+ const TARGETS = require('../render/targets.json');
10
+ const { installPlan } = require('./install-plan.cjs');
11
+ const CONFIG = '.agent-personalizer.json';
12
+ const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
13
+ // The recorded hash for a path, or undefined for a config written before this field existed
14
+ // (0.5.x and earlier) or for a path install never recorded. undefined means: fall back to
15
+ // recomputing the expected bytes from the currently running package, exactly as before.
16
+ const recordedHash = (cfg, rel) => (cfg.installed && typeof cfg.installed === 'object' && !Array.isArray(cfg.installed)) ? cfg.installed[rel] : undefined;
17
+
18
+ function refuse(message) { throw new renderer.Refusal(message); }
19
+ function uninstall(dir, { dry = false } = {}) {
20
+ const previousThrows = renderer.DIE_THROWS;
21
+ renderer.DIE_THROWS = true;
22
+ try { return run(dir, dry); }
23
+ catch (e) {
24
+ console.error(`agent-personalizer: ${e.message}`);
25
+ process.exitCode = e instanceof renderer.Refusal ? 2 : 1;
26
+ } finally { renderer.DIE_THROWS = previousThrows; }
27
+ }
28
+
29
+ function run(dir, dry) {
30
+ const requested = path.resolve(dir);
31
+ let st;
32
+ try { st = fs.lstatSync(requested); }
33
+ catch (e) {
34
+ if (e.code === 'ENOENT') refuse(`missing config: expected ${path.join(requested, CONFIG)}`);
35
+ throw e;
36
+ }
37
+ if (st.isSymbolicLink()) refuse(`--dir ${requested} is a symlink; nothing was removed`);
38
+ if (!st.isDirectory()) refuse(`--dir ${requested} is not a directory`);
39
+ // Resolve the user-selected boundary once, as the installer does. All paths beneath it
40
+ // are walked with lstat, including missing and dangling entries, before any read or write.
41
+ const root = fs.realpathSync(requested);
42
+ const observations = new Map();
43
+ const dirs = new Set();
44
+ function probe(rel, kind = 'file') {
45
+ if (typeof rel !== 'string' || !rel || path.isAbsolute(rel) || rel.includes('\\') || rel.split('/').some(p => !p || p === '.' || p === '..'))
46
+ refuse(`refusing path ${JSON.stringify(rel)} outside the install folder`);
47
+ let cur = root;
48
+ const parts = rel.split('/');
49
+ for (let i = 0; i < parts.length; i++) {
50
+ cur = path.join(cur, parts[i]);
51
+ let info;
52
+ try { info = fs.lstatSync(cur); }
53
+ catch (e) { if (e.code === 'ENOENT') return null; throw e; }
54
+ const label = parts.slice(0, i + 1).join('/');
55
+ if (info.isSymbolicLink()) refuse(`${label} is a symlink; nothing was removed`);
56
+ const directory = i < parts.length - 1 || kind === 'dir';
57
+ if (directory ? !info.isDirectory() : !info.isFile()) refuse(`${label} is not a regular ${directory ? 'directory' : 'file'}; nothing was removed`);
58
+ if (!observations.has(label)) observations.set(label, { info, kind: directory ? 'dir' : 'file' });
59
+ }
60
+ return cur;
61
+ }
62
+ function read(rel) {
63
+ const full = probe(rel);
64
+ if (!full) return null;
65
+ const bytes = fs.readFileSync(full, { flag: fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) });
66
+ const entry = observations.get(rel);
67
+ if (!entry.bytes) entry.bytes = bytes;
68
+ return bytes;
69
+ }
70
+ function text(bytes, rel) {
71
+ try { return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); }
72
+ catch (_) { refuse(`${rel} is not valid UTF-8; nothing was removed`); }
73
+ }
74
+ function parentDirs(rel) {
75
+ let parent = path.posix.dirname(rel);
76
+ while (parent !== '.') { dirs.add(parent); parent = path.posix.dirname(parent); }
77
+ }
78
+
79
+ if (!read(CONFIG)) refuse(`missing config: expected ${path.join(root, CONFIG)}`);
80
+ let cfg;
81
+ try { cfg = renderer.readConfig(root); }
82
+ catch (e) { if (e instanceof renderer.Refusal) refuse(`${CONFIG}: ${e.message}`); throw e; }
83
+ if (!Array.isArray(cfg.targets) || !cfg.targets.length || !cfg.onboarding || !Number.isInteger(cfg.level))
84
+ refuse(`${CONFIG} needs stored targets, level and onboarding answers for --uninstall`);
85
+ const answers = cfg.onboarding;
86
+ const level = Math.min(cfg.level, 3);
87
+ const base = onboarding.baseFor(answers);
88
+ // The renderer consults this path even at level 1. Validate it before rendering.
89
+ const notesScaffolded = !!probe(`${base}/README.md`);
90
+ const recipe = installPlan({ answers, level, targets: cfg.targets, notesScaffolded }).plan;
91
+ const homeNames = new Set(['CLAUDE.md', 'AGENTS.md']);
92
+ const expected = new Map();
93
+ for (const p of recipe) {
94
+ if (homeNames.has(p.rel)) continue; // compare these after rendering their block
95
+ const bytes = p.src ? fs.readFileSync(p.src) : Buffer.from(p.text);
96
+ if (expected.has(p.rel) && !expected.get(p.rel).equals(bytes)) refuse(`${p.rel}: conflicting install paths; nothing was removed`);
97
+ expected.set(p.rel, bytes);
98
+ }
99
+ const tracked = new Set([CONFIG, 'USER.md', ...recipe.map(p => p.rel)]);
100
+ for (const key of cfg.targets) {
101
+ const target = TARGETS[key];
102
+ tracked.add(target.file);
103
+ for (const rel of Object.values(target.boxFiles || {})) tracked.add(rel);
104
+ }
105
+ // Check every tracked file first, including hook/runtime copies and raw paste files.
106
+ for (const rel of tracked) { read(rel); parentDirs(rel); }
107
+ // Custom local rules also influence the render. Validate and snapshot them, including
108
+ // README.md which the rule loader skips, so a symlink there cannot hide from preflight.
109
+ if (probe('rules', 'dir')) {
110
+ for (const name of fs.readdirSync(path.join(root, 'rules'))) {
111
+ if (name.endsWith('.md')) read(`rules/${name}`);
112
+ }
113
+ }
114
+ const rendered = renderer.renderedContents(root, cfg);
115
+ const plan = [];
116
+ const add = (rel, action, output, reason) => plan.push({ rel, action, output, reason });
117
+ for (const entry of rendered) {
118
+ const { rel, key, block, raw } = entry;
119
+ const bytes = read(rel);
120
+ if (!bytes) continue;
121
+ const recorded = recordedHash(cfg, rel);
122
+ if (raw) {
123
+ const unedited = recorded ? sha256(bytes) === recorded : bytes.equals(Buffer.from(block));
124
+ add(rel, unedited ? 'remove' : 'keep', null, 'edited');
125
+ continue;
126
+ }
127
+ const existing = text(bytes, rel);
128
+ const ms = renderer.markerState(existing, rel);
129
+ if (ms.kind === 'malformed') refuse(`${rel}: malformed marker block; nothing was removed`);
130
+ // Exact block bytes matter here. --check normalizes CRLF for drift reporting, but
131
+ // uninstall treats even a line-ending edit inside the owned block as an edit.
132
+ const generated = renderer.splice(null, block, rel);
133
+ const expectedBlock = generated.slice(0, -1);
134
+ const matchesBlock = ms.kind === 'one' && existing.slice(ms.bStart, ms.eEnd) === expectedBlock;
135
+ if (cfg.preservedTargets && cfg.preservedTargets.includes(key)) {
136
+ // Only the block is ours here; the rest of the file is the user's, whatever it says.
137
+ // Install records the hash of the exact inner block text it wrote (the same shape
138
+ // `renderer.between` extracts: markers and their surrounding blank line stripped), so a
139
+ // later package release changing rules/ or USER.md cannot make an untouched block look
140
+ // edited (or vice versa).
141
+ const currentBlock = renderer.between(existing, rel);
142
+ const blockUnedited = recorded ? (currentBlock !== null && sha256(Buffer.from(currentBlock)) === recorded) : matchesBlock;
143
+ if (blockUnedited) add(rel, 'strip', Buffer.from(existing.slice(0, ms.bStart) + existing.slice(ms.eEnd)), 'pre-existing file; removed only the marked block');
144
+ else add(rel, 'keep', null, ms.kind === 'none' ? 'pre-existing file; block already absent' : 'edited');
145
+ continue;
146
+ }
147
+ if (recorded) {
148
+ // Install recorded the exact whole-file bytes it wrote for this target; compare against
149
+ // that instead of re-rendering from whatever package version happens to be running now.
150
+ add(rel, sha256(bytes) === recorded ? 'remove' : 'keep', null, 'edited or pre-existing content');
151
+ continue;
152
+ }
153
+ const candidates = [Buffer.from(generated)];
154
+ if (homeNames.has(rel)) {
155
+ // Legacy fallback only (no recorded hash: a config from before this field existed).
156
+ // Earlier levels and notes-presence states can leave unchanged pointer templates
157
+ // behind on a later run. They are all produced by the same installer recipe.
158
+ for (let l = 1; l <= level; l++) for (const ns of [false, true]) {
159
+ const home = installPlan({ answers, level: l, targets: [key], notesScaffolded: ns }).plan.find(p => p.rel === rel);
160
+ candidates.push(Buffer.from(renderer.splice(home.text, block, rel)));
161
+ }
162
+ }
163
+ add(rel, candidates.some(candidate => candidate.equals(bytes)) ? 'remove' : 'keep', null, 'edited or pre-existing content');
164
+ }
165
+ const user = read('USER.md');
166
+ if (user) {
167
+ const recordedUser = recordedHash(cfg, 'USER.md');
168
+ const userUnedited = recordedUser ? sha256(user) === recordedUser : [false, true].some(ns => user.equals(Buffer.from(onboarding.renderUser(answers, { notesScaffolded: ns }))));
169
+ add('USER.md', userUnedited ? 'remove' : 'keep', null, 'edited');
170
+ }
171
+ for (const [rel, bytes] of expected) {
172
+ const existing = read(rel);
173
+ if (!existing) continue;
174
+ const recorded = recordedHash(cfg, rel);
175
+ // Install recorded the exact bytes it wrote for this tracked file; a later release of this
176
+ // very package (a newer rules/, render/ or template file) must never make an untouched file
177
+ // read as edited. Only a config with no record for this path (0.5.x or earlier) falls back
178
+ // to comparing against what the currently running package would write.
179
+ const unedited = recorded ? sha256(existing) === recorded : existing.equals(bytes);
180
+ add(rel, unedited ? 'remove' : 'keep', null, 'edited');
181
+ }
182
+ if (new Set(plan.map(p => p.rel)).size !== plan.length) refuse('conflicting tracked paths; nothing was removed');
183
+ const retained = plan.filter(p => p.action !== 'remove');
184
+ const removeConfig = retained.length === 0;
185
+ const gone = new Set(plan.filter(p => p.action === 'remove').map(p => p.rel));
186
+ const emptyDirs = [];
187
+ for (const rel of [...dirs].sort((a, b) => b.split('/').length - a.split('/').length || a.localeCompare(b))) {
188
+ if (!probe(rel, 'dir')) continue;
189
+ if (fs.readdirSync(path.join(root, rel)).every(name => gone.has(`${rel}/${name}`))) {
190
+ emptyDirs.push(rel); gone.add(rel);
191
+ }
192
+ }
193
+ // Recheck the whole snapshot and permissions before the first change. An invalid or
194
+ // concurrently changed path leaves every file alone. There is no recursive deletion.
195
+ for (const [rel, saved] of observations) {
196
+ const full = probe(rel, saved.kind);
197
+ if (!full) refuse(`${rel} changed during preflight; nothing was removed`);
198
+ const now = fs.lstatSync(full);
199
+ if (now.dev !== saved.info.dev || now.ino !== saved.info.ino || now.mode !== saved.info.mode || (saved.bytes && !fs.readFileSync(full).equals(saved.bytes)))
200
+ refuse(`${rel} changed during preflight; nothing was removed`);
201
+ }
202
+ for (const rel of [...plan.filter(p => p.action !== 'keep').map(p => p.rel), ...emptyDirs, ...(removeConfig ? [CONFIG] : [])]) {
203
+ try { fs.accessSync(path.dirname(path.join(root, rel)), fs.constants.W_OK); }
204
+ catch (_) { refuse(`${rel}: parent directory is not writable; nothing was removed`); }
205
+ }
206
+ const label = dry ? 'would ' : '';
207
+ if (dry) console.log('Dry run: preview only; no files changed.');
208
+ for (const p of plan) {
209
+ if (p.action === 'keep') { console.log(`kept ${p.rel} (${p.reason})`); continue; }
210
+ if (!dry) {
211
+ const full = probe(p.rel);
212
+ if (!full || !fs.readFileSync(full).equals(observations.get(p.rel).bytes)) refuse(`${p.rel} changed before removal; config kept, rerun after reviewing the folder`);
213
+ if (p.action === 'remove') fs.unlinkSync(full);
214
+ else {
215
+ // Replace rather than truncate, preserving permissions without writing through a hard link.
216
+ const tmp = path.join(path.dirname(full), `.${path.basename(full)}.${crypto.randomBytes(8).toString('hex')}.agent-personalizer.tmp`);
217
+ try {
218
+ fs.writeFileSync(tmp, p.output, { flag: 'wx', mode: observations.get(p.rel).info.mode & 0o777 });
219
+ fs.chmodSync(tmp, observations.get(p.rel).info.mode & 0o777);
220
+ probe(p.rel);
221
+ fs.renameSync(tmp, full);
222
+ } finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); }
223
+ }
224
+ }
225
+ console.log(`${label}${p.action === 'strip' ? 'update' : 'remove'} ${p.rel}${p.action === 'strip' ? ` (${p.reason})` : ''}`);
226
+ }
227
+ for (const rel of emptyDirs) {
228
+ if (!dry) {
229
+ const full = probe(rel, 'dir');
230
+ if (full && fs.readdirSync(full).length === 0) fs.rmdirSync(full);
231
+ else continue;
232
+ }
233
+ console.log(`${label}remove ${rel}/ (empty)`);
234
+ }
235
+ // Config is always the final removal. A kept tracked path keeps the record for review.
236
+ if (removeConfig) {
237
+ if (!dry) {
238
+ for (const p of plan) if (probe(p.rel)) refuse(`${p.rel} still exists; ${CONFIG} kept`);
239
+ const full = probe(CONFIG);
240
+ if (!full || !fs.readFileSync(full).equals(observations.get(CONFIG).bytes)) refuse(`${CONFIG} changed; config kept`);
241
+ fs.unlinkSync(full);
242
+ }
243
+ console.log(`${label}remove ${CONFIG}`);
244
+ } else console.log(`kept ${CONFIG} (tracked files remain; review the kept paths above)`);
245
+ 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.');
246
+ }
247
+
248
+ module.exports = { uninstall };
package/docs/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # Documentation
2
+
3
+ agent-personalizer turns an interview into a profile and the instruction files each AI reads. Start with installation, then choose the guides for your setup.
4
+
5
+ | Guide | What it gives you |
6
+ |---|---|
7
+ | [Install and use](install.md) | Interactive setup, scripted answers, flags, updates and uninstall. |
8
+ | [Instruction tiers](tiers.md) | Where style, home files, session contracts, rule owners and memory belong. |
9
+ | [Paste guide](paste-guide.md) | Which file each AI reads and how to refresh pasted instructions. |
10
+ | [Companion tools](companions.md) | Notes connectors, access controls and approval mechanisms. |
11
+ | [Guarantees](guarantees.md) | Rendering, drift detection, preflight, local operation and the forbidden-string gate. |
12
+
13
+ For contributors, read [CONTRIBUTING.md](../CONTRIBUTING.md), [the rule format](../rules/README.md) and [AGENTS.md](../AGENTS.md). Agents can use [llms.txt](../llms.txt) as the entry point.
@@ -0,0 +1,61 @@
1
+ # What the code enforces
2
+
3
+ agent-personalizer is an installer and renderer. Its checks enforce file consistency and safe handling of paths. The generated profile, onboarding manual and session-start contract give the AI your working instructions. The AI applies those instructions when it works; its behaviour depends on the host and model.
4
+
5
+ ## Rendering and drift checks
6
+
7
+ Each render comes from `USER.md`, the selected rule source and the onboarding answers in `.agent-personalizer.json`. At level 3, `rules/` is your local editable source; lower levels use the package's rules.
8
+
9
+ - **One source:** edit the profile, rule files or onboarding answers, then regenerate the selected AI files together.
10
+ - **Byte fidelity:** the renderer preserves bytes outside generated markers, including line endings.
11
+ - **Drift detection:** `node render/render.cjs --dir . --check` compares the current generated blocks with what the sources would render now. It exits `1` when they differ.
12
+ - **Paste updates:** re-paste regenerated files into chat-app instruction fields. The check compares files on disk.
13
+ - **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.
14
+
15
+ The check measures rendered-file consistency. The [instruction tiers](tiers.md) explain how those files and hooks place instructions in front of the AI.
16
+
17
+ ## Preflight and writes
18
+
19
+ 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.
20
+
21
+ - **Paths:** paths beneath the installation root must be real files and directories. Symlinks and paths outside the root are refused.
22
+ - **Markers:** each target may have one correctly ordered generated block or be ready for its first block. Malformed blocks are refused.
23
+ - **Encoding:** sources and targets must contain valid UTF-8; invalid bytes are refused instead of re-encoded.
24
+ - **Existing work:** the installer keeps existing notes and rules. It regenerates `USER.md` only while the profile matches the previous answers byte for byte.
25
+ - **Renderer recovery:** target writes are staged, existing files are backed up, and a write failure triggers rollback. An incomplete restore keeps and names its backup with exit `2`.
26
+ - **Local operation:** the tool makes no network calls, sends no telemetry and reads no environment variables. `npx` fetches the package before execution.
27
+
28
+ The installer's upgrades can replace its own unchanged pointer lines as you add notes or local rules. The renderer's byte-fidelity promise applies to everything outside its marked block.
29
+
30
+ ## Forbidden-string gate
31
+
32
+ At level 3, configure a private list in your installed project:
33
+
34
+ ```bash
35
+ cp check/forbidden.example.txt check/forbidden.local.txt
36
+ ```
37
+
38
+ Fill it with the identifiers you want to catch and add `check/forbidden.local.txt` to that project's `.gitignore`. Never commit the private list. Then run:
39
+
40
+ ```bash
41
+ node check/gate.cjs --dir .
42
+ ```
43
+
44
+ The gate checks listed strings against file text and relative paths. In a git work tree it scans staged blobs, changed working copies and untracked files that git would include. `--all` scans the folder directly. It never follows symlinks.
45
+
46
+ - **Exit `0`:** the scan completed with no listed strings found.
47
+ - **Exit `1`:** one or more listed strings were found.
48
+ - **Exit `2`:** setup was refused, including a missing, empty or tracked private list.
49
+
50
+ Keep the list current. Review binaries, git history and personal terms outside that list separately; the gate checks the listed strings in the files it scans. Use `node check/gate.cjs --self-test` to verify detection with a seeded fixture.
51
+
52
+ ## Instructions and companions
53
+
54
+ The onboarding manual tells the AI where it may write, what is off limits and when to ask. The session-start hook prints those restrictions and the selected rules into context. Notes templates instruct the AI to maintain an index, session notes, decisions and inbox entries.
55
+
56
+ To make those answers govern tool access, configure a [companion](companions.md):
57
+
58
+ - **obsidian-tc:** folder access controls and human approval for destructive Obsidian operations.
59
+ - **The Context Layer:** purpose-bound context, approval decisions and receipts for actions and disclosures.
60
+
61
+ These controls live in the companion's configuration. The interview records the policy and renders the instructions that refer to it.
@@ -0,0 +1,140 @@
1
+ # Install and use agent-personalizer
2
+
3
+ The installer writes a profile, an onboarding manual and the instruction files for the AIs you choose. It stores your answers in `.agent-personalizer.json` so later runs can update the files together.
4
+
5
+ ## Requirements
6
+
7
+ Use Node 18 or later. The installer, renderer and gate run on macOS, Linux and Windows. The shell harness and session-start hook need a POSIX shell; use WSL or Git Bash on Windows.
8
+
9
+ ## Interactive setup
10
+
11
+ ```bash
12
+ npx agent-personalizer
13
+ ```
14
+
15
+ Choose the destination folder, AI targets and install level. The default interview asks seven questions that change behaviour, plus any question that applies to your notes tool. Enter accepts the displayed default.
16
+
17
+ For the full interview:
18
+
19
+ ```bash
20
+ npx agent-personalizer --full
21
+ ```
22
+
23
+ This asks up to 23 questions; questions that do not apply to your notes tool are skipped. `--quick` explicitly selects the short interview, which is already the default. Both interview flags require a terminal and the interactive answer source.
24
+
25
+ To pin a GitHub tag:
26
+
27
+ ```bash
28
+ npx github:aunysillyme/agent-personalizer#v0.6.0
29
+ ```
30
+
31
+ ## Answer sources and headless runs
32
+
33
+ | Option | What it does |
34
+ |---|---|
35
+ | `--defaults` | Accepts every default answer. It works with interactive folder selection or with `--yes`. |
36
+ | `--answers my-answers.json` | Loads your answers from a JSON file. |
37
+ | `--answers -` | Reads the answer JSON from stdin. |
38
+ | `--yes` | Selects non-interactive mode. Supply `--dir`, `--ai` and `--level`. It uses defaults when an answer source is omitted. |
39
+
40
+ Default answers:
41
+
42
+ ```bash
43
+ npx agent-personalizer --dir . --ai claude,agents --level 1 --yes --defaults
44
+ ```
45
+
46
+ Your answers:
47
+
48
+ ```bash
49
+ npx agent-personalizer --dir . --ai claude,agents --level 2 --yes --answers my-answers.json
50
+ ```
51
+
52
+ Answers from stdin:
53
+
54
+ ```bash
55
+ npx agent-personalizer --dir . --ai claude,agents --level 2 --yes --answers - < my-answers.json
56
+ ```
57
+
58
+ Use [`test/fixtures/answers.json`](../test/fixtures/answers.json) as a complete example. Partial answer objects take defaults for the remaining fields. Unknown keys, invalid types and unknown choices are refused before writing files. Choose either `--answers` or `--defaults` for a run. A rerun using defaults preserves previously stored onboarding answers.
59
+
60
+ ## Installer flags
61
+
62
+ | Flag | Purpose |
63
+ |---|---|
64
+ | `--dir <folder>` | Destination folder; prompted in interactive mode. |
65
+ | `--ai claude,agents,gemini,chatgpt,prompt` | Comma-separated targets. Choose the ones you use. |
66
+ | `--level 1`, `--level 2`, `--level 3` | Profile and home files; add local notes; add editable rules and mechanisms. |
67
+ | `--answers <file.json>` or `--answers -` | Script the interview. |
68
+ | `--defaults` | Accept default answers. |
69
+ | `--yes` | Run without interactive prompts. |
70
+ | `--full` | Run the full applicable interview in a terminal. |
71
+ | `--quick` | Run the short interview in a terminal. |
72
+ | `--uninstall` | Remove unchanged installed files using the stored configuration. |
73
+ | `--dry` | Preview `--uninstall` without writing. |
74
+ | `--help`, `-h` | Print usage. |
75
+ | `--version`, `-v` | Print the package version. |
76
+
77
+ For compatibility with older scripts, `--level 4` remains an alias of `--level 3` and installs exactly the same files. For routing between agents, use [model-orchestrator](https://github.com/aunysillyme/model-orchestrator).
78
+
79
+ Installer exit codes: `0` completed, `1` unexpected error, `2` refused or invalid input.
80
+
81
+ ## What each level adds
82
+
83
+ - **Level 1:** `USER.md`, `AGENT_ONBOARDING.md`, the files for your AI targets, and `.agent-personalizer.json`. Rules render from the package. The default target selection is `claude,agents`, so it produces both `CLAUDE.md` and `AGENTS.md`.
84
+ - **Level 2:** a local notes scaffold with `README.md`, `sessions/TEMPLATE-week.md`, `decisions.md` and `inbox/README.md`. Disk tools use your `notes_path`; read-only and other tools use the local `notes/` fallback. Cloud tools get connector pointers and keep their notes in their service.
85
+ - **Level 3:** your editable `rules/` copy, `render/` tools, the Claude Code session-start hook and the forbidden-string gate. [Register the hook](../hooks/README.md) in your AI settings and [configure the gate](guarantees.md#forbidden-string-gate).
86
+
87
+ An existing local notes scaffold is detected at any level. Existing notes and rule files stay yours. A `signature: no` answer omits the signature rule and its template lines; answering yes includes the signature line.
88
+
89
+ ## Updating an install
90
+
91
+ Re-run the installer with your destination, AI selection and level. An interview or `--answers` file supplies new onboarding answers. Existing targets remain in the stored selection, so the renderer updates them together.
92
+
93
+ `AGENT_ONBOARDING.md` and rendered blocks regenerate from the answers. `USER.md` regenerates only when its bytes still match the previous answers. An edited profile stays; the installer names changed answers so you can update the profile by hand. Home-file text outside the markers is preserved, with installer-owned pointer lines updated when you add notes or local rules.
94
+
95
+ At level 3, render your edited profile and rules:
96
+
97
+ ```bash
98
+ node render/render.cjs --dir .
99
+ node render/render.cjs --dir . --check
100
+ ```
101
+
102
+ The check returns `0` for current files, `1` for drift, and `2` for invalid inputs. `--targets claude,agents` selects specific renders; `--rules <folder>` selects a rule source. `--strict` returns `1` and writes nothing when a ChatGPT box is over the configured budget. Run `node render/render.cjs --help` for contract and target options.
103
+
104
+ Re-paste changed text into chat apps. See the [paste guide](paste-guide.md) for the files each app needs.
105
+
106
+ ## npm cache permissions
107
+
108
+ If `npx` reports `EPERM` and root-owned files in `~/.npm`, give this run a writable cache in the current folder:
109
+
110
+ ```bash
111
+ npm_config_cache=./.npm-cache npx agent-personalizer
112
+ ```
113
+
114
+ ## Manual copying
115
+
116
+ For a setup without Node, download this repository and copy [`templates/USER.md`](../templates/USER.md) plus [`templates/CLAUDE.md`](../templates/CLAUDE.md) or [`templates/AGENTS.md`](../templates/AGENTS.md) into your project. Fill in the profile and adapt the home template's pointers to the files you keep. For a chat app, paste the profile body into its instruction field.
117
+
118
+ The interview, automatic rendering and drift check are available when you use the Node installer. [The paste guide](paste-guide.md) covers manual app setup.
119
+
120
+ ## Uninstall
121
+
122
+ Run from anywhere and name the installed folder:
123
+
124
+ ```bash
125
+ npx agent-personalizer --uninstall --dir /path/to/project --dry
126
+ npx agent-personalizer --uninstall --dir /path/to/project
127
+ ```
128
+
129
+ The uninstaller reads `/path/to/project/.agent-personalizer.json` and compares tracked files with what the stored answers and current sources would produce. Install records the exact bytes it wrote for each tracked file, so uninstall recognizes them correctly even after the package itself has moved on to a newer release.
130
+
131
+ - **Generated files:** removed when unchanged. Edited files are kept and named in the output.
132
+ - **Existing home files:** user text stays; only an unchanged generated block is removed.
133
+ - **`USER.md`:** removed only when it still matches the render of the stored answers.
134
+ - **Notes scaffold:** unchanged template files are removed. Your notes stay, and folders are removed only when empty.
135
+ - **Rules and tools:** unchanged installed copies are removed file by file, including the session-start hook. Edited copies stay.
136
+ - **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.
137
+ - **Paths:** the uninstaller never follows symlinks or removes a path outside the named folder. A refused path leaves the removal plan unapplied.
138
+ - **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.
139
+
140
+ `--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.
@@ -59,8 +59,8 @@ Use `system-prompt.md`. It carries only the universal blocks: no profile, no per
59
59
  2. Files that are read automatically (`CLAUDE.md`, `AGENTS.md`, `GEMINI.md`) are done.
60
60
  3. Files that were pasted (claude.ai, ChatGPT, any system prompt) must be pasted again. Nothing can detect a stale paste for you; put "re-paste after re-render" in your own checklist.
61
61
 
62
- ## What not to do
62
+ ## Keep it working
63
63
 
64
- - Do not edit inside the marker block of a rendered file; edit `USER.md`, `rules/`, or your answers, and re-render. The next render overwrites the block.
65
- - Do not paste `AGENT_ONBOARDING.md` into a shared bot. It names your off-limits topics and your working habits. `system-prompt.md` is the shareable one.
66
- - Do not keep a hand-edited copy of a rule in two places. One owner, everything else points to it. [tiers.md](tiers.md), tier 4.
64
+ - **Edit the source:** change `USER.md`, `rules/`, or your answers, then re-render. The next render replaces the generated block.
65
+ - **Share the universal rules:** use `system-prompt.md` for a shared bot. Keep `AGENT_ONBOARDING.md` in your own setup because it names your off-limits topics and working habits.
66
+ - **Keep one rule owner:** link other files to the owning rule, or generate and check their copies. See [tiers.md](tiers.md), tier 4.
package/docs/tiers.md CHANGED
@@ -2,7 +2,16 @@
2
2
 
3
3
  Instructions to an AI live in five places. Each has one job and prevents one failure. Put a rule in the wrong tier and it either decays, drifts, or gets ignored. Put it in the right one and it holds.
4
4
 
5
- Read bottom-up. Tier 1 is the most present, tier 5 the most durable.
5
+ Read bottom-up. Tier 1 is the most present, tier 5 the most durable. Install levels select the files you receive; these tiers explain where the resulting instructions belong.
6
+
7
+ | Tier | What | Prevents |
8
+ |---|---|---|
9
+ | 1 | Style in the system prompt | rules decaying over a long chat |
10
+ | 2 | One always-loaded home file | the AI not knowing where anything is |
11
+ | 3 | Session-start injection | a tool's own instructions beating yours at the moment of decision |
12
+ | 4 | One owning document per rule | the same rule drifting in five copies |
13
+ | 5 | Memory with a status on every fact | the AI treating its own guess as your ruling |
14
+
6
15
 
7
16
  A word on the stories below: each is one setup's experience of what held and what did not. They explain why the tiers are shaped this way. They are not measurements, and placing a rule in a tier puts it in front of the model; it does not make the model obey. Instruction precedence differs by host and model.
8
17
 
@@ -37,7 +37,7 @@ _Generated by agent-personalizer from Mara's own answers (stored in `.agent-pers
37
37
 
38
38
  ### Where you may write
39
39
 
40
- - **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.5.2/docs/companions.md.
40
+ - **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.6.0/docs/companions.md.
41
41
  - You may create and edit files anywhere under `notes/`, under that folder's rules. Nowhere else without being asked.
42
42
  - **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.
43
43
  - **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.5.2/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.6.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.
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 ADDED
@@ -0,0 +1,26 @@
1
+ # agent-personalizer
2
+
3
+ > One interview writes a profile and rule files for Claude Code, Codex, Cursor, Gemini and ChatGPT, kept in sync from one source.
4
+
5
+ Install with Node 18 or later: `npx agent-personalizer`. Headless setup: `npx agent-personalizer --dir . --ai claude,agents --level 1 --yes --defaults`.
6
+
7
+ The installer writes USER.md, AGENT_ONBOARDING.md and each selected AI's instruction files. 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. Preview removal with `npx agent-personalizer --uninstall --dir . --dry`.
8
+
9
+ ## Docs
10
+
11
+ - [Documentation index](https://github.com/aunysillyme/agent-personalizer/blob/main/docs/README.md): Start here.
12
+ - [Install and use](https://github.com/aunysillyme/agent-personalizer/blob/main/docs/install.md): Flags, scripted answers, updates and uninstall.
13
+ - [Instruction tiers](https://github.com/aunysillyme/agent-personalizer/blob/main/docs/tiers.md): Where each instruction belongs.
14
+ - [Paste guide](https://github.com/aunysillyme/agent-personalizer/blob/main/docs/paste-guide.md): The file each AI reads and how to load it.
15
+ - [Companion tools](https://github.com/aunysillyme/agent-personalizer/blob/main/docs/companions.md): Notes connectors and enforcement tools.
16
+ - [Guarantees](https://github.com/aunysillyme/agent-personalizer/blob/main/docs/guarantees.md): What the code enforces and how instructions reach the AI.
17
+
18
+ ## Optional
19
+
20
+ - [Agent contributor instructions](https://github.com/aunysillyme/agent-personalizer/blob/main/AGENTS.md): Repository rules and verification.
21
+ - [Contributing](https://github.com/aunysillyme/agent-personalizer/blob/main/CONTRIBUTING.md): Add targets, notes tools, examples and regression fixes.
22
+ - [Rule format](https://github.com/aunysillyme/agent-personalizer/blob/main/rules/README.md): Universal, personal, binding and origin sections.
23
+ - [Worked example](https://github.com/aunysillyme/agent-personalizer/tree/main/examples/freelance-illustrator): An invented illustrator's profile and rendered files.
24
+ - [Changelog](https://github.com/aunysillyme/agent-personalizer/blob/main/CHANGELOG.md): Release history.
25
+ - [model-orchestrator](https://github.com/aunysillyme/model-orchestrator): Route tasks to the model suited to the work.
26
+ - [website-build-skill](https://github.com/aunysillyme/website-build-skill): A skill pack that teaches your AI current website-building expertise: research, design, code, accessibility, performance, search and security.