agent-personalizer 0.4.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.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +155 -0
  3. package/bin/agent-personalizer.js +388 -0
  4. package/check/forbidden.example.txt +31 -0
  5. package/check/gate.cjs +349 -0
  6. package/docs/companions.md +62 -0
  7. package/docs/paste-guide.md +66 -0
  8. package/docs/tiers.md +89 -0
  9. package/examples/freelance-illustrator/.agent-personalizer.json +52 -0
  10. package/examples/freelance-illustrator/AGENTS.md +180 -0
  11. package/examples/freelance-illustrator/AGENT_ONBOARDING.md +70 -0
  12. package/examples/freelance-illustrator/CLAUDE.md +184 -0
  13. package/examples/freelance-illustrator/USER.md +49 -0
  14. package/examples/freelance-illustrator/notes/README.md +39 -0
  15. package/examples/freelance-illustrator/notes/decisions.md +18 -0
  16. package/examples/freelance-illustrator/notes/inbox/2026-09-03-shot-list-for-six-prints.md +14 -0
  17. package/examples/freelance-illustrator/notes/inbox/README.md +19 -0
  18. package/examples/freelance-illustrator/notes/sessions/2026-W36.md +41 -0
  19. package/examples/freelance-illustrator/rules/00-read-the-profile-first.md +24 -0
  20. package/examples/freelance-illustrator/rules/10-evidence-before-assertion.md +24 -0
  21. package/examples/freelance-illustrator/rules/20-one-owner-per-rule.md +24 -0
  22. package/examples/freelance-illustrator/rules/30-folder-index-is-part-of-the-change.md +26 -0
  23. package/examples/freelance-illustrator/rules/40-sign-every-edit.md +25 -0
  24. package/examples/freelance-illustrator/rules/50-output-style.md +21 -0
  25. package/examples/freelance-illustrator/rules/60-act-or-ask.md +30 -0
  26. package/hooks/README.md +39 -0
  27. package/hooks/claude-code/session-start.sh +14 -0
  28. package/package.json +49 -0
  29. package/render/onboarding.cjs +360 -0
  30. package/render/render.cjs +559 -0
  31. package/render/targets.json +57 -0
  32. package/rules/00-read-the-profile-first.md +24 -0
  33. package/rules/10-evidence-before-assertion.md +24 -0
  34. package/rules/20-one-owner-per-rule.md +24 -0
  35. package/rules/30-folder-index-is-part-of-the-change.md +26 -0
  36. package/rules/40-sign-every-edit.md +25 -0
  37. package/rules/50-output-style.md +21 -0
  38. package/rules/60-act-or-ask.md +30 -0
  39. package/rules/README.md +55 -0
  40. package/templates/AGENTS.md +30 -0
  41. package/templates/CLAUDE.md +30 -0
  42. package/templates/FOLDER_README.md +35 -0
  43. package/templates/INBOX_README.md +19 -0
  44. package/templates/USER.md +52 -0
  45. package/templates/decisions-log.md +16 -0
  46. package/templates/session-log.md +22 -0
@@ -0,0 +1,559 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /*
4
+ render.cjs: USER.md + rules/*.md -> per-AI instruction files.
5
+
6
+ usage:
7
+ node render/render.cjs [--dir <project>] [--targets claude,agents,gemini,chatgpt,prompt] [--check] [--strict] [--rules <dir>]
8
+ node render/render.cjs [--dir <project>] --contract [--contract-target claude] [--no-personal]
9
+ node render/render.cjs --help
10
+
11
+ --rules where the rule files live. Default: <dir>/rules when it exists (a level-3 install,
12
+ or this repo), else the rules/ folder beside this renderer's own package (a level-1
13
+ or level-2 install renders from the package's rules and copies none). Refused if
14
+ neither exists.
15
+ --strict with the ChatGPT target: exit 1 and write nothing when a box is over its budget.
16
+
17
+ --dir project folder holding USER.md and rules/ (default: cwd). The folder you
18
+ name is followed once (realpath); nothing beneath it may be a symlink.
19
+ --targets which renders to write; default: <dir>/.agent-personalizer.json, else "claude,agents".
20
+ The "onboarding" target renders AGENT_ONBOARDING.md from the interview answers
21
+ stored in .agent-personalizer.json (render/onboarding.cjs).
22
+ --check render to memory, compare with disk; exit 1 on drift, 0 clean
23
+ --contract print the inject:true rules for one target to stdout (session-start hooks):
24
+ the onboarding block (how to work with this person) when answers exist and
25
+ personal content is allowed, then each rule: universal, personal (same
26
+ condition), then the target's binding block.
27
+ --contract-target which target's surface filter, personal policy and binding to use (default claude)
28
+
29
+ Rules render from the interview answers as well as the profile: a rule whose frontmatter says
30
+ `requires: <answer>=<value>` is left out of every render and every contract when the stored
31
+ answer differs (no stored answers = the defaults). The ChatGPT target, when answers exist,
32
+ renders a compact profile and the contract block plus the inject:true rules, sized for its
33
+ two boxes; without answers it falls back to the full profile and every rule for that surface.
34
+
35
+ Rendered text lives between two marker lines inside each target file. Bytes outside the
36
+ markers are preserved exactly (line endings included); a target that is not valid UTF-8 is
37
+ refused rather than re-encoded (sources too). Outputs are staged beside their targets under
38
+ per-run random names with the target's own mode (0644 for new files), existing targets are
39
+ backed up, and a failure at any point restores every target and removes every staged file.
40
+ If a restore itself fails, the backup is kept and named, and the exit is 2 with ROLLBACK
41
+ INCOMPLETE on stderr; a backup is never deleted unless its target was restored or committed.
42
+ A cleanup that fails (a staged file or a backup that cannot be removed) is named on stderr
43
+ with exit 2, never silently ignored. Backups carry the target's mode regardless of umask. The renderer refuses to write when
44
+ the marker state is anything other than "no block yet" or "exactly one BEGIN followed by
45
+ exactly one END", and it validates every target before writing any.
46
+
47
+ Safety: sources (USER.md, rules/, each rule file) and targets must be regular files or
48
+ directories inside the real project folder, never symlinks. Marker tokens are rejected
49
+ inside sources; markers inside a fenced code block in a TARGET are ignored. rules/ must exist.
50
+ Frontmatter keys are whitelisted; unknown, duplicate, malformed or CRLF
51
+ frontmatter is an error, never a silent default. Unexpected .md files in rules/ are an
52
+ error. No network. No environment variables read. No secrets written.
53
+
54
+ exit codes: 0 ok · 1 drift (--check) · 2 refused or invalid input
55
+ */
56
+ const fs = require('fs');
57
+ const path = require('path');
58
+ const crypto = require('crypto');
59
+ const onboarding = require('./onboarding.cjs');
60
+
61
+ class Refusal extends Error {}
62
+ /* die(): exit 2 with the reason. When a caller (the installer's preflight) sets module.exports.DIE_THROWS,
63
+ the same refusal is thrown as a Refusal instead, so the caller can add its own context and exit. */
64
+ function die(msg) { if (module.exports && module.exports.DIE_THROWS) throw new Refusal(msg); console.error(`render: ${msg}`); process.exit(2); }
65
+
66
+
67
+ const BEGIN = '<!-- agent-personalizer:begin -->';
68
+ const END = '<!-- agent-personalizer:end -->';
69
+ function readJson(file, what) {
70
+ let text;
71
+ try { text = fs.readFileSync(file, 'utf8'); } catch (e) { die(`${what}: cannot read ${file} (${e.code || e.message})`); }
72
+ try { return JSON.parse(text); } catch (e) { die(`${what}: ${file} is not valid JSON (${e.message})`); }
73
+ }
74
+ const TARGETS = readJson(path.join(__dirname, 'targets.json'), 'targets');
75
+ if (!TARGETS || typeof TARGETS !== 'object' || Array.isArray(TARGETS) || !Object.keys(TARGETS).length) die('targets: targets.json must be a non-empty object');
76
+ for (const [k, t] of Object.entries(TARGETS)) if (!t || typeof t !== 'object' || typeof t.file !== 'string') die(`targets: target "${k}" needs a string "file"`);
77
+ const KNOWN = Object.keys(TARGETS);
78
+ const BINDINGS = new Set(Object.values(TARGETS).map(t => t.binding).filter(Boolean));
79
+ const SECTION_RE = /^(universal|personal|origin|binding:[a-z]+)$/;
80
+ const META_KEYS = new Set(['id', 'title', 'inject', 'surfaces', 'requires']);
81
+ const RULE_FILE_RE = /^\d{2}-[A-Za-z0-9._-]+\.md$/;
82
+
83
+
84
+ const VALUE_OPTS = ['--dir', '--targets', '--contract-target', '--rules'];
85
+ const FLAG_OPTS = ['--check', '--contract', '--no-personal', '--strict', '--help'];
86
+ /* Parse argv once, strictly: value options at most once each, flags at most once, nothing unknown. */
87
+ function parseArgs() {
88
+ const out = {};
89
+ const argv = process.argv.slice(2);
90
+ for (let i = 0; i < argv.length; i++) {
91
+ const a = argv[i];
92
+ if (VALUE_OPTS.includes(a)) {
93
+ if (a in out) die(`${a} given more than once`);
94
+ const v = argv[i + 1];
95
+ if (v === undefined || v === '' || v.startsWith('--')) die(`${a} needs a non-empty value`);
96
+ out[a] = v; i++;
97
+ } else if (FLAG_OPTS.includes(a)) {
98
+ if (a in out) die(`${a} given more than once`);
99
+ out[a] = true;
100
+ } else die(`unknown option "${a}" (known: ${[...VALUE_OPTS, ...FLAG_OPTS].join(', ')})`);
101
+ }
102
+ return out;
103
+ }
104
+ let ARGS = null;
105
+ function arg(name, dflt) { if (!ARGS) ARGS = parseArgs(); return name in ARGS ? ARGS[name] : dflt; }
106
+
107
+ /* lstat helper: the entry must exist as a regular file or directory, not a symlink. */
108
+ function mustBe(p, kind, where) {
109
+ let st;
110
+ try { st = fs.lstatSync(p); } catch (_) { return null; }
111
+ if (st.isSymbolicLink()) die(`${where} is a symlink; refusing to follow it`);
112
+ if (kind === 'file' && !st.isFile()) die(`${where} is not a regular file`);
113
+ if (kind === 'dir' && !st.isDirectory()) die(`${where} is not a directory`);
114
+ return st;
115
+ }
116
+
117
+ function parseFrontmatter(text, where) {
118
+ if (!text.startsWith('---\n')) return { meta: {}, body: text };
119
+ const close = text.indexOf('\n---\n', 4);
120
+ if (close === -1) die(`${where}: frontmatter opened with --- but never closed`);
121
+ const meta = {};
122
+ for (const line of text.slice(4, close).split('\n')) {
123
+ if (!line.trim()) continue;
124
+ const kv = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
125
+ if (!kv) die(`${where}: unreadable frontmatter line "${line}"`);
126
+ const key = kv[1];
127
+ if (!META_KEYS.has(key)) die(`${where}: unknown frontmatter key "${key}" (allowed: ${[...META_KEYS].join(', ')})`);
128
+ if (key in meta) die(`${where}: duplicate frontmatter key "${key}"`);
129
+ let v = kv[2].trim();
130
+ if (v.startsWith('[')) {
131
+ if (!v.endsWith(']')) die(`${where}: frontmatter list "${key}" is not closed`);
132
+ v = v.slice(1, -1).split(',').map(s => s.trim()).filter(Boolean);
133
+ } else if (v === 'true') v = true;
134
+ else if (v === 'false') v = false;
135
+ meta[key] = v;
136
+ }
137
+ if ('surfaces' in meta) {
138
+ if (!Array.isArray(meta.surfaces) || !meta.surfaces.length) die(`${where}: "surfaces" must be a non-empty list`);
139
+ const bad = meta.surfaces.filter(s => !KNOWN.includes(s));
140
+ if (bad.length) die(`${where}: unknown surface(s) ${bad.join(', ')} (known: ${KNOWN.join(', ')})`);
141
+ }
142
+ if ('inject' in meta && typeof meta.inject !== 'boolean') die(`${where}: "inject" must be true or false`);
143
+ if ('requires' in meta) {
144
+ const m = typeof meta.requires === 'string' && meta.requires.match(/^([a-z_]+)=([A-Za-z0-9_-]+)$/);
145
+ if (!m) die(`${where}: "requires" must read <answer>=<value>, e.g. signature=yes`);
146
+ const q = onboarding.QUESTIONS.find(x => x.id === m[1]);
147
+ if (!q) die(`${where}: "requires" names an unknown answer "${m[1]}"`);
148
+ if (q.type !== 'choice' || !q.options.some(o => o[0] === m[2])) die(`${where}: "requires" value "${m[2]}" is not a choice for "${m[1]}" (${q.type === 'choice' ? q.options.map(o => o[0]).join(', ') : 'not a choice question'})`);
149
+ meta.requires = { answer: m[1], value: m[2] };
150
+ }
151
+ for (const k of ['id', 'title']) if (k in meta && (typeof meta[k] !== 'string' || !meta[k].trim())) die(`${where}: "${k}" must be non-empty text`);
152
+ return { meta, body: text.slice(close + 5) };
153
+ }
154
+
155
+ function parseSections(body, where) {
156
+ const sections = {};
157
+ let current = null;
158
+ const lines = body.split('\n');
159
+ const fenced = fenceMap(lines, where);
160
+ for (let i = 0; i < lines.length; i++) {
161
+ const line = lines[i];
162
+ const h = fenced[i] ? null : line.match(/^##\s+(.+?)\s*$/);
163
+ if (h) {
164
+ const name = h[1].trim();
165
+ if (!SECTION_RE.test(name)) die(`${where}: unknown section "## ${name}" (allowed: universal, personal, origin, binding:<ai>)`);
166
+ if (name.startsWith('binding:') && !BINDINGS.has(name.slice(8))) die(`${where}: unknown binding "${name}" (known: ${[...BINDINGS].map(b => 'binding:' + b).join(', ')})`);
167
+ if (name in sections) die(`${where}: duplicate section "## ${name}"`);
168
+ current = name; sections[current] = [];
169
+ continue;
170
+ }
171
+ if (current) sections[current].push(line);
172
+ else if (line.trim()) die(`${where}: text before the first "## " section heading would be dropped ("${line.trim().slice(0, 40)}"); move it into a section`);
173
+ }
174
+ for (const k of Object.keys(sections)) sections[k] = sections[k].join('\n').trim();
175
+ return sections;
176
+ }
177
+
178
+ /* CommonMark-style fence tracking over LF-split lines: an opening fence is 3+ backticks or
179
+ tildes after at most 3 spaces; it closes only on the same character, at least the opening
180
+ length, with nothing but whitespace after. Returns one boolean per line: inside a fence?
181
+ An unterminated fence is an error, never a guess. */
182
+ function fenceMap(lines, where) {
183
+ const inside = new Array(lines.length).fill(false);
184
+ let open = null; // { ch, len, line }
185
+ lines.forEach((raw, i) => {
186
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
187
+ const m = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
188
+ if (open) {
189
+ inside[i] = true;
190
+ if (m && m[1][0] === open.ch && m[1].length >= open.len && m[2].trim() === '') open = null;
191
+ } else if (m && !(m[1][0] === '`' && m[2].includes('`'))) {
192
+ open = { ch: m[1][0], len: m[1].length, line: i + 1 };
193
+ inside[i] = true;
194
+ }
195
+ });
196
+ if (open) die(`${where}: code fence opened on line ${open.line} is never closed; fix it by hand`);
197
+ return inside;
198
+ }
199
+
200
+ function rejectMarkers(text, where) {
201
+ if (text.includes(BEGIN) || text.includes(END)) die(`${where}: contains a render marker token; those are reserved for rendered files`);
202
+ }
203
+
204
+ function decodeUtf8(bytes, where) {
205
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
206
+ catch (_) { die(`${where}: not valid UTF-8. Nothing was written`); }
207
+ }
208
+
209
+ /* .agent-personalizer.json, fully validated on EVERY load (render, --check and --contract alike):
210
+ targets a unique list of known targets, level an integer 1-4, onboarding a valid answer set. */
211
+ function readConfig(root) {
212
+ const cfgPath = path.join(root, '.agent-personalizer.json');
213
+ if (!mustBe(cfgPath, 'file', '.agent-personalizer.json')) return null;
214
+ const cfg = readJson(cfgPath, 'config');
215
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) die('config: .agent-personalizer.json must be an object');
216
+ if ('targets' in cfg) {
217
+ if (!Array.isArray(cfg.targets)) die('config: .agent-personalizer.json "targets" must be a list');
218
+ const bad = cfg.targets.filter(t => !KNOWN.includes(t));
219
+ if (bad.length) die(`config: .agent-personalizer.json lists unknown target(s): ${bad.join(', ')} (known: ${KNOWN.join(', ')})`);
220
+ if (new Set(cfg.targets).size !== cfg.targets.length) die('config: .agent-personalizer.json lists a target twice');
221
+ }
222
+ if ('level' in cfg && !(Number.isInteger(cfg.level) && cfg.level >= 1 && cfg.level <= 4)) die(`config: .agent-personalizer.json "level" must be an integer 1-4 (found ${JSON.stringify(cfg.level)})`);
223
+ if ('onboarding' in cfg) {
224
+ try { cfg.onboarding = onboarding.validate(cfg.onboarding); } catch (e) { die(`config: onboarding answers: ${e.message}`); }
225
+ }
226
+ return cfg;
227
+ }
228
+
229
+ function readSource(p, where) {
230
+ mustBe(p, 'file', where);
231
+ const text = decodeUtf8(fs.readFileSync(p), where).replace(/\r\n/g, '\n');
232
+ rejectMarkers(text, where);
233
+ return text;
234
+ }
235
+
236
+ /* Where the rules come from: --rules, else <root>/rules when present, else the rules/ folder of the
237
+ package this renderer belongs to (so a level-1 install, which copies no rules, still renders them). */
238
+ function rulesDir(root, explicit) {
239
+ if (explicit) { const d = path.resolve(explicit); if (!mustBe(d, 'dir', `--rules ${explicit}`)) die(`--rules ${explicit} does not exist`); return fs.realpathSync(d); }
240
+ const local = path.join(root, 'rules');
241
+ if (mustBe(local, 'dir', 'rules/')) return local;
242
+ const pkg = path.resolve(__dirname, '..', 'rules');
243
+ if (pkg !== local && mustBe(pkg, 'dir', 'package rules/')) return pkg;
244
+ die('rules/ is missing here and beside this renderer; an intentionally empty rule set is an empty rules/ directory, not a missing one');
245
+ }
246
+ function loadRules(root, explicit) {
247
+ const rdir = rulesDir(root, explicit || null);
248
+ const out = [];
249
+ for (const f of fs.readdirSync(rdir).sort()) {
250
+ if (f === 'README.md') continue;
251
+ if (!f.endsWith('.md')) continue;
252
+ if (!RULE_FILE_RE.test(f)) die(`rules/${f}: unexpected file name; rule files are NN-name.md (README.md is the one exception)`);
253
+ const where = `${path.relative(root, rdir) || 'rules'}/${f}`;
254
+ const text = readSource(path.join(rdir, f), where);
255
+ const { meta, body } = parseFrontmatter(text, where);
256
+ const sections = parseSections(body, where);
257
+ if (!sections.universal) die(`${where}: missing "## universal" block`);
258
+ out.push({ file: f, meta, sections });
259
+ }
260
+ return out;
261
+ }
262
+
263
+ function loadProfile(root) {
264
+ const p = path.join(root, 'USER.md');
265
+ if (!fs.existsSync(p) && !(() => { try { fs.lstatSync(p); return true; } catch (_) { return false; } })()) return null;
266
+ const text = readSource(p, 'USER.md');
267
+ fenceMap(text.split('\n'), 'USER.md'); // an unterminated fence in the profile is an error, not a surprise later
268
+ return text.replace(/^#\s+USER\.md\s*\n/, '').replace(/\n---\n\*Template from agent-personalizer[^\n]*\n?$/, '').trim();
269
+ }
270
+
271
+ /* Resolve a target's relative filename to a path provably inside the real project root,
272
+ with no symlink anywhere on the way. */
273
+ function safeTargetPath(root, rel, key) {
274
+ if (typeof rel !== 'string' || !rel || path.isAbsolute(rel) || /[\\]/.test(rel) || rel.split('/').some(p => p === '..' || p === '' || p === '.'))
275
+ die(`target "${key}": file name "${rel}" is not a plain relative path`);
276
+ const parts = rel.split('/');
277
+ let cur = root;
278
+ for (let i = 0; i < parts.length; i++) {
279
+ cur = path.join(cur, parts[i]);
280
+ const where = `target "${key}": ${path.relative(root, cur)}`;
281
+ const st = mustBe(cur, i < parts.length - 1 ? 'dir' : 'file', where);
282
+ if (i < parts.length - 1 && !st) die(`${where}: directory does not exist; create it first`);
283
+ }
284
+ if (!(cur + path.sep).startsWith(root + path.sep) || cur === root) die(`target "${key}": resolves outside the project folder`);
285
+ return cur;
286
+ }
287
+
288
+ function renderRule(rule, target) {
289
+ const s = rule.sections;
290
+ const out = [`### ${rule.meta.title || rule.meta.id || rule.file}`, '', s.universal];
291
+ if (target.personal && s.personal) out.push('', s.personal);
292
+ if (target.binding && s[`binding:${target.binding}`]) out.push('', s[`binding:${target.binding}`]);
293
+ if (target.origin && s.origin) out.push('', s.origin.split('\n').map(l => `> ${l}`).join('\n'));
294
+ return out.join('\n');
295
+ }
296
+
297
+ /* the rules that reach one surface: the surfaces filter, then the requires filter against the
298
+ stored answers (defaults when none are stored, so a rule set without an interview still renders) */
299
+ function rulesFor(rules, key, answers) {
300
+ const a = answers || onboarding.defaults();
301
+ return rules.filter(r => (!Array.isArray(r.meta.surfaces) || r.meta.surfaces.includes(key))
302
+ && (!r.meta.requires || a[r.meta.requires.answer] === r.meta.requires.value));
303
+ }
304
+ const answersOf = (cfg) => (cfg && cfg.onboarding) ? cfg.onboarding : null;
305
+
306
+ function renderTarget(key, target, profile, rules, cfg) {
307
+ if (target.source === 'onboarding') {
308
+ if (!cfg || !cfg.onboarding) die(`target "${key}": no onboarding answers in .agent-personalizer.json. Run the installer (it asks), or pass --answers <file>`);
309
+ return onboarding.renderOnboarding(cfg.onboarding);
310
+ }
311
+ const answers = answersOf(cfg);
312
+ const lines = [`## ${target.header}`, '', '_Generated by agent-personalizer from `USER.md`, `rules/` and your onboarding answers. Edit those, then re-render. Do not edit between the markers._', ''];
313
+ if (target.boxes) {
314
+ // With answers: a compact profile and the contract block plus the inject:true rules, in
315
+ // consequence order, so the two boxes fit their budget and no restriction depends on trimming.
316
+ // Without answers: the full profile and every rule for this surface (the pre-interview shape).
317
+ const picked = rulesFor(rules, key, answers).filter(r => !answers || r.meta.inject === true);
318
+ const ruleText = picked.map(r => {
319
+ const s = r.sections, parts = [s.universal];
320
+ if (target.personal && s.personal && !answers) parts.push(s.personal);
321
+ if (target.binding && s[`binding:${target.binding}`]) parts.push(s[`binding:${target.binding}`]);
322
+ return parts.join('\n\n');
323
+ }).join('\n\n');
324
+ const box1 = answers ? onboarding.compactProfile(answers) : (profile || '(no USER.md found)');
325
+ const box2 = answers ? [onboarding.contractBlock(answers, { files: false }).split('\n').slice(2).join('\n'), ruleText].filter(Boolean).join('\n\n') : ruleText;
326
+ const over = [];
327
+ const warn = (label, text) => {
328
+ if (text.length > target.limit) { over.push(label); return `\n> **${label} is OVER BUDGET: ${text.length} characters, the box allows about ${target.limit}.** Nothing was cut for you. Trim from the bottom up: the box is ordered by consequence (restrictions first, style last), so the last lines are the cheapest to lose.`; }
329
+ return `\n> ${label}: ${text.length} of about ${target.limit} characters.`;
330
+ };
331
+ // a wrapping fence longer than any backtick or tilde run inside the content, so content fences can never close it
332
+ const fenceFor = (text) => { let n = 3; for (const m of text.matchAll(/(`{3,}|~{3,})/g)) n = Math.max(n, m[1].length + 1); return '`'.repeat(n); };
333
+ const f1 = fenceFor(box1), f2 = fenceFor(box2);
334
+ renderTarget.boxes = { box1: box1 + '\n', box2: box2 + '\n' }; // plain paste files, written beside the markdown
335
+ lines.push('### Box 1: "What would you like ChatGPT to know about you?"', '', '_Copy only the text inside the fence below (or paste the whole of `chatgpt-box1.txt`, the same text as a plain file)._', '', f1, box1, f1, warn('Box 1', box1), '');
336
+ lines.push('### Box 2: "How would you like ChatGPT to respond?"', '', '_Copy only the text inside the fence below (or paste the whole of `chatgpt-box2.txt`)._', '', f2, box2, f2, warn('Box 2', box2));
337
+ if (!answers) lines.push('', '> No onboarding answers in `.agent-personalizer.json`, so this is the full profile and every rule. Run the installer (it asks) for the compact, budgeted form.');
338
+ else lines.push('', `> ChatGPT has no file access, so only the rules marked \`inject: true\` are here (${picked.length}). The rest live in \`rules/\`; for a ChatGPT Project, upload \`AGENT_ONBOARDING.md\` and \`rules/\` as project files instead of pasting.`);
339
+ renderTarget.overBudget = (renderTarget.overBudget || []).concat(over.map(l => `${target.file}: ${l}`));
340
+ return lines.join('\n');
341
+ }
342
+ if (target.profile && profile) lines.push('## Profile', '', profile, '');
343
+ lines.push('## Rules', '');
344
+ for (const r of rulesFor(rules, key, answers)) lines.push(renderRule(r, target), '');
345
+ return lines.join('\n').trimEnd();
346
+ }
347
+
348
+ /* Marker positions as byte ranges of whole lines. Markers count only as standalone lines
349
+ OUTSIDE fenced code blocks, so a quoted example in the target is never mistaken for the
350
+ owned block. */
351
+ function markerState(text, where) {
352
+ const lines = text.split('\n');
353
+ const fenced = fenceMap(lines, where);
354
+ const b = [], e = [];
355
+ let pos = 0;
356
+ lines.forEach((raw, i) => {
357
+ if (!fenced[i]) {
358
+ const t = (raw.endsWith('\r') ? raw.slice(0, -1) : raw).trim();
359
+ if (t === BEGIN) b.push([pos, pos + raw.length]);
360
+ else if (t === END) e.push([pos, pos + raw.length]);
361
+ }
362
+ pos += raw.length + 1;
363
+ });
364
+ if (!b.length && !e.length) return { kind: 'none' };
365
+ if (b.length === 1 && e.length === 1 && b[0][0] < e[0][0])
366
+ return { kind: 'one', bStart: b[0][0], bEnd: b[0][1], eStart: e[0][0], eEnd: e[0][1] };
367
+ return { kind: 'malformed', begins: b.length, ends: e.length };
368
+ }
369
+
370
+ function splice(existing, block, file) {
371
+ const body = `${BEGIN}\n${block}\n${END}`;
372
+ if (existing == null) return body + '\n';
373
+ const st = markerState(existing, file);
374
+ if (st.kind === 'malformed') die(`${file}: malformed marker block (${st.begins} begin, ${st.ends} end). Fix it by hand; nothing was written`);
375
+ if (st.kind === 'none') return existing + (existing.endsWith('\n') ? '' : '\n') + '\n' + body + '\n';
376
+ return existing.slice(0, st.bStart) + body + existing.slice(st.eEnd);
377
+ }
378
+
379
+ function between(existing, file) {
380
+ const st = markerState(existing, file);
381
+ if (st.kind === 'malformed') die(`${file}: malformed marker block (${st.begins} begin, ${st.ends} end)`);
382
+ if (st.kind === 'none') return null;
383
+ return existing.slice(st.bEnd, st.eStart).replace(/\r\n/g, '\n').replace(/^\n/, '').replace(/\n$/, '');
384
+ }
385
+
386
+ function main() {
387
+ ARGS = parseArgs();
388
+ if (arg('--help', false)) { const src = fs.readFileSync(__filename, 'utf8'); process.stdout.write(src.slice(src.indexOf('/*') + 2, src.indexOf('*/')).trim() + `\n\nagent-personalizer renderer ${onboarding.VERSION}\n`); return; }
389
+ const requested = path.resolve(arg('--dir', process.cwd()));
390
+ let root;
391
+ try { root = fs.realpathSync(requested); } catch (_) { die(`--dir ${requested} does not exist`); }
392
+ if (!fs.statSync(root).isDirectory()) die(`--dir ${requested} is not a directory`);
393
+ const check = !!arg('--check', false);
394
+ const contract = !!arg('--contract', false);
395
+ const rules = loadRules(root, arg('--rules', null));
396
+ const profile = loadProfile(root);
397
+
398
+ if (contract) {
399
+ const key = arg('--contract-target', 'claude');
400
+ if (!KNOWN.includes(key)) die(`unknown contract target "${key}"`);
401
+ const target = TARGETS[key];
402
+ const withPersonal = target.personal && !arg('--no-personal', false);
403
+ const cfgC = readConfig(root);
404
+ const inject = rulesFor(rules, key, answersOf(cfgC)).filter(r => r.meta.inject === true);
405
+ const out = [`[agent-personalizer] Session-start contract for ${key}. Injected in full at the start of every session so these rules are in context at the moment of decision.`, ''];
406
+ if (cfgC && cfgC.onboarding && withPersonal) out.push(onboarding.contractBlock(cfgC.onboarding), '');
407
+ for (const r of inject) {
408
+ out.push(`## ${r.meta.title || r.meta.id || r.file}`, '', r.sections.universal);
409
+ if (withPersonal && r.sections.personal) out.push('', r.sections.personal);
410
+ if (target.binding && r.sections[`binding:${target.binding}`]) out.push('', r.sections[`binding:${target.binding}`]);
411
+ out.push('');
412
+ }
413
+ process.stdout.write(out.join('\n'));
414
+ return;
415
+ }
416
+
417
+ let targets;
418
+ const cfg = readConfig(root);
419
+ const explicit = arg('--targets', null);
420
+ if (explicit) targets = explicit.split(',').map(s => s.trim()).filter(Boolean);
421
+ else if (cfg) {
422
+ if (Array.isArray(cfg.targets)) targets = cfg.targets;
423
+ else if (cfg.targets === undefined) targets = ['claude', 'agents'];
424
+ else die('config: .agent-personalizer.json "targets" must be a list');
425
+ }
426
+ else targets = ['claude', 'agents'];
427
+ if (!targets.length) die('no targets');
428
+ if (new Set(targets).size !== targets.length) die(`a target is listed twice (${targets.join(',')})`);
429
+
430
+ // Preflight everything: paths, existing content, marker state, final bytes. Then write.
431
+ const plan = targets.map(key => {
432
+ const target = TARGETS[key];
433
+ if (!target) die(`unknown target "${key}" (known: ${KNOWN.join(', ')})`);
434
+ const file = safeTargetPath(root, target.file, key);
435
+ const block = renderTarget(key, target, profile, rules, cfg);
436
+ let existing = null;
437
+ if (fs.existsSync(file)) {
438
+ existing = decodeUtf8(fs.readFileSync(file), target.file);
439
+ }
440
+ if (!check) {
441
+ try { fs.accessSync(existing == null ? path.dirname(file) : file, fs.constants.W_OK); }
442
+ catch (_) { die(`${target.file}: not writable. Nothing was written`); }
443
+ }
444
+ const current = existing == null ? null : between(existing, target.file);
445
+ const output = check ? null : splice(existing, block, target.file);
446
+ // the generated file must itself re-parse to exactly one block, or the next render would refuse it
447
+ if (output != null) { const st = markerState(output, `${target.file} (generated)`); if (st.kind !== 'one' || between(output, `${target.file} (generated)`) !== block) die(`${target.file}: generated content would not re-parse cleanly; a fence in USER.md or a rule is unbalanced. Nothing was written`); }
448
+ const mode = existing == null ? 0o644 : (fs.statSync(file).mode & 0o777);
449
+ const entry = { key, target, file, block, current, output, mode };
450
+ if (!target.boxes) return entry;
451
+ // the two plain paste files: whole-file outputs, no markers, compared whole in --check
452
+ const raws = Object.entries(target.boxFiles || {}).map(([which, rel]) => {
453
+ const rfile = safeTargetPath(root, rel, `${key}:${which}`);
454
+ const text = renderTarget.boxes[which];
455
+ let rexisting = null;
456
+ if (fs.existsSync(rfile)) rexisting = decodeUtf8(fs.readFileSync(rfile), rel);
457
+ if (!check) { try { fs.accessSync(rexisting == null ? path.dirname(rfile) : rfile, fs.constants.W_OK); } catch (_) { die(`${rel}: not writable. Nothing was written`); } }
458
+ const rmode = rexisting == null ? 0o644 : (fs.statSync(rfile).mode & 0o777);
459
+ return { key: `${key}:${which}`, target: { file: rel }, file: rfile, block: text, current: rexisting, output: check ? null : text, mode: rmode, raw: true };
460
+ });
461
+ return [entry, ...raws];
462
+ }).flat();
463
+ if (arg('--strict', false) && (renderTarget.overBudget || []).length) {
464
+ for (const o of renderTarget.overBudget) console.error(`render: OVER BUDGET ${o}`);
465
+ console.error('render: --strict: a box is over its budget. Nothing was written');
466
+ process.exit(1);
467
+ }
468
+
469
+ // Every final path must be distinct, and no final path may look like a staging file.
470
+ // Checked in every mode, before any output.
471
+ const finals = plan.map(p => p.file);
472
+ if (new Set(finals).size !== finals.length) die('two targets resolve to the same file. Nothing was written');
473
+ if (finals.some(f => /\.agent-personalizer\.(tmp|bak)$/.test(f))) die('a target file name uses the staging suffix. Nothing was written');
474
+
475
+ if (check) {
476
+ let drift = 0;
477
+ for (const p of plan) {
478
+ if (p.current === null) { console.log(`DRIFT ${p.target.file}: ${p.raw ? 'missing' : 'missing or no marker block'}`); drift++; }
479
+ else if (p.current !== p.block) { console.log(`DRIFT ${p.target.file}: rendered block differs from source`); drift++; }
480
+ else console.log(`ok ${p.target.file}`);
481
+ }
482
+ console.log(drift ? `\n${drift} file(s) drifted. Re-render with: node render/render.cjs --dir ${root}` : '\nclean: every rendered file matches its source');
483
+ process.exit(drift ? 1 : 0);
484
+ }
485
+ // Commit: stage every output beside its target under a per-run random name, back up every
486
+ // existing target, rename staged -> final one by one, and on any failure put every backup
487
+ // back and remove every staged file. A stale .tmp/.bak from an earlier crash never blocks a
488
+ // run (names are unique) and is never deleted automatically (it may be the only copy).
489
+ const run = `${process.pid}-${crypto.randomBytes(6).toString('hex')}`;
490
+ const staged = [], committed = [];
491
+ const tryUnlink = (p, kept, what) => { try { fs.unlinkSync(p); } catch (e) { if (e.code !== 'ENOENT') kept.push(`${what}: ${path.basename(p)} (${e.message})`); } };
492
+ const undo = (why) => {
493
+ const kept = [];
494
+ for (const c of committed) {
495
+ if (c.bak && c.done) {
496
+ try { fs.renameSync(c.bak, c.file); } // target was replaced: original back in place, mode carried by the backup
497
+ catch (e) { kept.push(`${c.label}: original kept at ${path.basename(c.bak)} (${e.message})`); }
498
+ } else if (c.bak) {
499
+ tryUnlink(c.bak, kept, `${c.label}: stale backup not removed`); // target was never replaced: the original is still in place, drop the copy
500
+ } else if (c.done) {
501
+ try { fs.unlinkSync(c.file); } // target did not exist before and was created by this run
502
+ catch (e) { kept.push(`${c.label}: created target not removed (${e.message})`); }
503
+ }
504
+ // else: target did not exist before and the rename never happened; nothing to restore
505
+ }
506
+ for (const s of staged) tryUnlink(s.tmp, kept, 'staged output not removed');
507
+ if (kept.length) {
508
+ console.error(`render: ${why}.`);
509
+ console.error('render: ROLLBACK INCOMPLETE. Handle these by hand; nothing else was deleted:');
510
+ for (const k of kept) console.error(` ${k}`);
511
+ process.exit(2);
512
+ }
513
+ die(`${why}. Every target was restored; nothing changed`);
514
+ };
515
+ try {
516
+ for (const p of plan) {
517
+ const tmp = path.join(path.dirname(p.file), `.${path.basename(p.file)}.${run}.agent-personalizer.tmp`);
518
+ staged.push({ tmp, file: p.file, label: p.target.file, mode: p.mode }); // recorded BEFORE the file can exist; cleanup tolerates ENOENT
519
+ fs.writeFileSync(tmp, p.output, { flag: 'wx', mode: p.mode });
520
+ fs.chmodSync(tmp, p.mode);
521
+ }
522
+ } catch (e) { undo(`could not stage output (${e.message})`); }
523
+ try {
524
+ for (const s of staged) {
525
+ let bak = null;
526
+ const rec = { file: s.file, bak: null, label: s.label, done: false };
527
+ committed.push(rec); // recorded before the first artifact exists
528
+ if (fs.existsSync(s.file)) {
529
+ bak = path.join(path.dirname(s.file), `.${path.basename(s.file)}.${run}.agent-personalizer.bak`);
530
+ rec.bak = bak; // recorded BEFORE the copy can exist
531
+ fs.copyFileSync(s.file, bak, fs.constants.COPYFILE_EXCL);
532
+ fs.chmodSync(bak, s.mode); // carries the target's mode into a restore, whatever the umask
533
+ }
534
+ fs.renameSync(s.tmp, s.file);
535
+ rec.done = true;
536
+ }
537
+ } catch (e) { undo(`could not commit output (${e.message})`); }
538
+ const leftovers = [];
539
+ for (const c of committed) if (c.bak) tryUnlink(c.bak, leftovers, 'backup not removed');
540
+ for (const s of staged) console.log(`wrote ${s.label}`);
541
+ for (const o of (renderTarget.overBudget || [])) console.log(`OVER BUDGET ${o} (written in full; trim by hand, bottom up)`);
542
+ if (leftovers.length) {
543
+ console.error('render: every target was written, but CLEANUP INCOMPLETE. Remove these by hand (they hold copies of the previous targets):');
544
+ for (const l of leftovers) console.error(` ${l}`);
545
+ process.exit(2);
546
+ }
547
+
548
+ }
549
+
550
+ /* Everything the renderer would refuse about the SOURCES already present in a folder, checked without
551
+ writing: an existing rules/ (each file parsed as loadRules does) and an existing USER.md (as
552
+ loadProfile does). A missing rules/ or USER.md is fine here: the installer is about to create them. */
553
+ function preflightSources(root) {
554
+ if (mustBe(path.join(root, 'rules'), 'dir', 'rules/')) loadRules(root, null); // library call: never read argv; a kept local rules/ must parse; package rules are the package's problem
555
+ loadProfile(root);
556
+ }
557
+
558
+ module.exports = { main, fenceMap, markerState, splice, between, preflightSources, Refusal, DIE_THROWS: false };
559
+ if (require.main === module) main();
@@ -0,0 +1,57 @@
1
+ {
2
+ "claude": {
3
+ "file": "CLAUDE.md",
4
+ "binding": "claude",
5
+ "personal": true,
6
+ "origin": true,
7
+ "profile": true,
8
+ "header": "Rendered instructions for Claude"
9
+ },
10
+ "agents": {
11
+ "file": "AGENTS.md",
12
+ "binding": "agents",
13
+ "personal": true,
14
+ "origin": true,
15
+ "profile": true,
16
+ "header": "Rendered instructions for coding agents (Codex, Cursor, others that read AGENTS.md)"
17
+ },
18
+ "gemini": {
19
+ "file": "GEMINI.md",
20
+ "binding": "gemini",
21
+ "personal": true,
22
+ "origin": true,
23
+ "profile": true,
24
+ "header": "Rendered instructions for Gemini"
25
+ },
26
+ "chatgpt": {
27
+ "file": "chatgpt-custom-instructions.md",
28
+ "binding": "chatgpt",
29
+ "personal": true,
30
+ "origin": false,
31
+ "profile": true,
32
+ "boxes": true,
33
+ "limit": 1500,
34
+ "header": "ChatGPT custom instructions (two boxes)",
35
+ "boxFiles": {
36
+ "box1": "chatgpt-box1.txt",
37
+ "box2": "chatgpt-box2.txt"
38
+ }
39
+ },
40
+ "prompt": {
41
+ "file": "system-prompt.md",
42
+ "binding": null,
43
+ "personal": false,
44
+ "origin": false,
45
+ "profile": false,
46
+ "header": "Shareable system prompt (universal rules only, no profile)"
47
+ },
48
+ "onboarding": {
49
+ "file": "AGENT_ONBOARDING.md",
50
+ "source": "onboarding",
51
+ "binding": null,
52
+ "personal": true,
53
+ "origin": false,
54
+ "profile": false,
55
+ "header": "Agent onboarding: how to work with this person"
56
+ }
57
+ }
@@ -0,0 +1,24 @@
1
+ ---
2
+ id: 00-read-the-profile-first
3
+ title: Read the profile first
4
+ inject: true
5
+ surfaces: [claude, agents, gemini]
6
+ ---
7
+
8
+ ## universal
9
+ Before the first substantive reply of a session, read the user's profile (`USER.md`) and then their agent onboarding file (`AGENT_ONBOARDING.md`). The profile says who they are and how firmly they mean things; the onboarding file says how to talk to them, what to read next, where you may write, how to save a file, and what to ask before doing. Everything below assumes both have been read.
10
+
11
+ In practice: two files, read before you answer anything, every time you start.
12
+
13
+ ## personal
14
+ If the profile and a rendered instruction file disagree, the profile wins: the rendered file is generated from it and is the one that drifted.
15
+
16
+ ## binding:claude
17
+ `USER.md` sits next to `CLAUDE.md`. In Claude Code, `CLAUDE.md` loads automatically; `USER.md` does not, so the first action of a session is to read it.
18
+
19
+ ## binding:agents
20
+ `USER.md` sits next to `AGENTS.md`. Read it before the first tool call.
21
+
22
+ ## origin
23
+ Written after: an AI produced a week of correctly formatted, well-reasoned work in the wrong voice, for the wrong audience, because the profile lived in a file nothing told it to open. A second week went to an AI that knew the person well and still wrote into the wrong folder, because nothing told it where writes were allowed.
24
+ Prevents: fluent output aimed at nobody in particular.