agent-personalizer 0.7.2 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/README.md +23 -14
  3. package/SECURITY.md +3 -1
  4. package/bin/agent-personalizer.js +90 -106
  5. package/bin/git-exclude.cjs +108 -0
  6. package/bin/install-plan.cjs +3 -0
  7. package/bin/known-hashes.json +54 -0
  8. package/bin/learn.cjs +210 -0
  9. package/bin/sessions.cjs +448 -0
  10. package/bin/uninstall.cjs +51 -7
  11. package/check/gate.cjs +4 -3
  12. package/docs/README.md +2 -1
  13. package/docs/companions.md +2 -2
  14. package/docs/guarantees.md +17 -6
  15. package/docs/install.md +31 -20
  16. package/docs/learning.md +103 -0
  17. package/docs/paste-guide.md +4 -4
  18. package/docs/tiers.md +4 -4
  19. package/examples/freelance-illustrator/.agent-personalizer.json +3 -3
  20. package/examples/freelance-illustrator/AGENTS.md +67 -3
  21. package/examples/freelance-illustrator/AGENT_ONBOARDING.md +4 -7
  22. package/examples/freelance-illustrator/CLAUDE.md +67 -3
  23. package/examples/freelance-illustrator/LEARNED.md +14 -0
  24. package/examples/freelance-illustrator/USER.md +6 -1
  25. package/examples/freelance-illustrator/rules/00-read-the-profile-first.md +1 -1
  26. package/examples/freelance-illustrator/rules/65-ask-before-it-repeats.md +18 -0
  27. package/examples/freelance-illustrator/rules/70-their-words-point-at-the-thing.md +15 -0
  28. package/examples/freelance-illustrator/rules/80-symptoms-are-not-causes.md +15 -0
  29. package/examples/freelance-illustrator/rules/90-surface-what-they-cant-see.md +15 -0
  30. package/examples/freelance-illustrator/rules/README.md +59 -0
  31. package/examples/lab-technician/.agent-personalizer.json +38 -0
  32. package/examples/lab-technician/AGENTS.md +243 -0
  33. package/examples/lab-technician/AGENT_ONBOARDING.md +64 -0
  34. package/examples/lab-technician/CLAUDE.md +247 -0
  35. package/examples/lab-technician/LEARNED.md +14 -0
  36. package/examples/lab-technician/USER.md +53 -0
  37. package/examples/lab-technician/notes/README.md +26 -0
  38. package/examples/lab-technician/notes/decisions.md +4 -0
  39. package/examples/lab-technician/notes/inbox/2026-10-06-observation-table.md +3 -0
  40. package/examples/lab-technician/notes/inbox/README.md +7 -0
  41. package/examples/lab-technician/notes/sessions/2026-W41.md +7 -0
  42. package/examples/lab-technician/rules/00-read-the-profile-first.md +24 -0
  43. package/examples/lab-technician/rules/10-evidence-before-assertion.md +24 -0
  44. package/examples/lab-technician/rules/20-one-owner-per-rule.md +24 -0
  45. package/examples/lab-technician/rules/30-folder-index-is-part-of-the-change.md +26 -0
  46. package/examples/lab-technician/rules/40-sign-every-edit.md +25 -0
  47. package/examples/lab-technician/rules/50-output-style.md +21 -0
  48. package/examples/lab-technician/rules/60-act-or-ask.md +30 -0
  49. package/examples/lab-technician/rules/65-ask-before-it-repeats.md +18 -0
  50. package/examples/lab-technician/rules/70-their-words-point-at-the-thing.md +15 -0
  51. package/examples/lab-technician/rules/80-symptoms-are-not-causes.md +15 -0
  52. package/examples/lab-technician/rules/90-surface-what-they-cant-see.md +15 -0
  53. package/examples/lab-technician/rules/README.md +59 -0
  54. package/examples/product-designer/.agent-personalizer.json +38 -0
  55. package/examples/product-designer/AGENTS.md +243 -0
  56. package/examples/product-designer/AGENT_ONBOARDING.md +63 -0
  57. package/examples/product-designer/CLAUDE.md +247 -0
  58. package/examples/product-designer/LEARNED.md +14 -0
  59. package/examples/product-designer/USER.md +53 -0
  60. package/examples/product-designer/notes/README.md +26 -0
  61. package/examples/product-designer/notes/decisions.md +4 -0
  62. package/examples/product-designer/notes/inbox/2026-10-06-cancellation-wording.md +8 -0
  63. package/examples/product-designer/notes/inbox/README.md +7 -0
  64. package/examples/product-designer/notes/sessions/2026-W41.md +7 -0
  65. package/examples/product-designer/rules/00-read-the-profile-first.md +24 -0
  66. package/examples/product-designer/rules/10-evidence-before-assertion.md +24 -0
  67. package/examples/product-designer/rules/20-one-owner-per-rule.md +24 -0
  68. package/examples/product-designer/rules/30-folder-index-is-part-of-the-change.md +26 -0
  69. package/examples/product-designer/rules/40-sign-every-edit.md +25 -0
  70. package/examples/product-designer/rules/50-output-style.md +21 -0
  71. package/examples/product-designer/rules/60-act-or-ask.md +30 -0
  72. package/examples/product-designer/rules/65-ask-before-it-repeats.md +18 -0
  73. package/examples/product-designer/rules/70-their-words-point-at-the-thing.md +15 -0
  74. package/examples/product-designer/rules/80-symptoms-are-not-causes.md +15 -0
  75. package/examples/product-designer/rules/90-surface-what-they-cant-see.md +15 -0
  76. package/examples/product-designer/rules/README.md +59 -0
  77. package/hooks/README.md +1 -1
  78. package/llms.txt +6 -2
  79. package/package.json +2 -2
  80. package/render/onboarding.cjs +115 -45
  81. package/render/render.cjs +98 -39
  82. package/rules/00-read-the-profile-first.md +1 -1
  83. package/rules/65-ask-before-it-repeats.md +18 -0
  84. package/rules/70-their-words-point-at-the-thing.md +15 -0
  85. package/rules/80-symptoms-are-not-causes.md +15 -0
  86. package/rules/90-surface-what-they-cant-see.md +15 -0
  87. package/rules/README.md +4 -0
  88. package/templates/LEARNED.md +11 -0
@@ -0,0 +1,448 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+ const crypto = require('node:crypto');
7
+
8
+ const MAX_LINE = 8 * 1024 * 1024;
9
+ const MAX_FILE = 64 * 1024 * 1024;
10
+ const MAX_MEMORIES = 20;
11
+ const SOURCES = new Set(['claude-code', 'codex', 'gemini-cli']);
12
+ const CONTEXT_HEADERS = ['# AGENTS.md instructions', '# Files mentioned by the user', '# Response annotations', '# Browser comments'];
13
+
14
+ function bump(state, reason, count = 1) {
15
+ state.skipped[reason] = (state.skipped[reason] || 0) + count;
16
+ }
17
+
18
+ function claudeProjectNames(projectDir) {
19
+ const absolute = path.resolve(projectDir);
20
+ return [...new Set([absolute.replace(/[\\/]/g, '-'), absolute.replace(/[:\\/]/g, '-')])];
21
+ }
22
+
23
+ function belongsToProject(cwd, projectDir) {
24
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return false;
25
+ const relative = path.relative(projectDir, path.resolve(cwd));
26
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
27
+ }
28
+
29
+ /* Both sides are compared in NFC and lower case: macOS often stores accents decomposed (NFD),
30
+ which would otherwise let a listed name through. Audit 0.8.0 F2. */
31
+ const CTRL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
32
+ const fold = (text) => String(text).replace(CTRL, '').normalize('NFC').toLowerCase();
33
+ const compact = (text) => fold(text).replace(/\s+/g, '');
34
+ function privateMatch(text, terms) {
35
+ const lower = fold(text);
36
+ const collapsed = compact(text);
37
+ return terms.some(raw => {
38
+ const term = fold(raw).trim();
39
+ const tight = compact(raw);
40
+ return (term && lower.includes(term)) || (tight && collapsed.includes(tight));
41
+ });
42
+ }
43
+
44
+ function cutContextBlocks(text) {
45
+ const tags = /<(\/?)(system-reminder|pasted_content)\b[^>]*>/gi;
46
+ const stack = [];
47
+ let output = '', position = 0, match;
48
+ while ((match = tags.exec(text))) {
49
+ if (!stack.length) output += text.slice(position, match.index);
50
+ const name = match[2].toLowerCase();
51
+ if (match[1]) {
52
+ if (stack[stack.length - 1] === name) stack.pop();
53
+ } else if (!/\/\s*>$/.test(match[0])) stack.push(name);
54
+ position = tags.lastIndex;
55
+ }
56
+ // An unfinished block stays excluded rather than exposing a partial paste.
57
+ if (!stack.length) output += text.slice(position);
58
+ return output;
59
+ }
60
+
61
+ function typedText(items, state) {
62
+ if (!items.length) { bump(state, 'non_typed'); return null; }
63
+ // A private match drops the whole message, including its other text items.
64
+ if (privateMatch(items.join('\n'), state.privateTerms) || privateMatch(items.join(''), state.privateTerms)) { bump(state, 'private_match'); return null; }
65
+ const kept = [];
66
+ for (const item of items) {
67
+ let text = String(item).replace(CTRL, '').trim();
68
+ if (/^<[A-Za-z][A-Za-z0-9_:-]*/.test(text) || CONTEXT_HEADERS.some(prefix => text.startsWith(prefix))) {
69
+ bump(state, 'automation_text');
70
+ continue;
71
+ }
72
+ text = cutContextBlocks(text).replace(CTRL, '').trim();
73
+ if (text) kept.push(text);
74
+ }
75
+ const text = kept.join('\n');
76
+ if (privateMatch(text, state.privateTerms) || privateMatch(kept.join(''), state.privateTerms)) { bump(state, 'private_match'); return null; }
77
+ if (!text) { bump(state, 'empty_message'); return null; }
78
+ if (text.length > 2000) { bump(state, 'long_message'); return null; }
79
+ return text;
80
+ }
81
+
82
+ function textItems(content, type) {
83
+ if (typeof content === 'string') return [content];
84
+ if (!Array.isArray(content)) return [];
85
+ return content.filter(item => item && typeof item === 'object' && item.type === type && typeof item.text === 'string').map(item => item.text);
86
+ }
87
+
88
+ async function statPath(file, kind, state, count = false) {
89
+ if (count) state.filesChecked += 1;
90
+ try {
91
+ const stat = await fs.promises.lstat(file);
92
+ if (stat.isSymbolicLink()) { bump(state, 'symlink'); return null; }
93
+ if ((kind === 'directory' && !stat.isDirectory()) || (kind === 'file' && !stat.isFile())) {
94
+ bump(state, 'non_regular');
95
+ return null;
96
+ }
97
+ return stat;
98
+ } catch (error) {
99
+ if (error.code !== 'ENOENT') bump(state, 'unreadable');
100
+ return null;
101
+ }
102
+ }
103
+
104
+ async function children(dir, state) {
105
+ if (!await statPath(dir, 'directory', state)) return [];
106
+ try { return (await fs.promises.readdir(dir)).sort(); }
107
+ catch { bump(state, 'unreadable'); return []; }
108
+ }
109
+
110
+ async function candidate(file, source, project, format, state) {
111
+ const stat = await statPath(file, 'file', state, true);
112
+ if (stat) state.candidates.push({ file, source, project, format, mtimeMs: stat.mtimeMs });
113
+ }
114
+
115
+ async function discover(home, sources, state) {
116
+ if (!await statPath(home, 'directory', state)) return;
117
+ if (sources.has('claude-code')) {
118
+ const app = path.join(home, '.claude');
119
+ if (await statPath(app, 'directory', state)) {
120
+ const projects = path.join(app, 'projects');
121
+ if (await statPath(projects, 'directory', state)) {
122
+ const projectNames = state.allProjects ? await children(projects, state) : claudeProjectNames(state.projectDir);
123
+ for (const project of projectNames) {
124
+ const dir = path.join(projects, project);
125
+ if (!await statPath(dir, 'directory', state)) continue;
126
+ for (const name of await children(dir, state)) {
127
+ if (name.endsWith('.jsonl')) await candidate(path.join(dir, name), 'claude-code', project, 'claude', state);
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ if (sources.has('codex')) {
134
+ const app = path.join(home, '.codex');
135
+ if (await statPath(app, 'directory', state)) {
136
+ async function walk(dir) {
137
+ for (const name of await children(dir, state)) {
138
+ const file = path.join(dir, name);
139
+ const stat = await statPath(file, null, state);
140
+ if (!stat) continue;
141
+ if (stat.isDirectory()) await walk(file);
142
+ else if (name.startsWith('rollout-') && name.endsWith('.jsonl')) await candidate(file, 'codex', path.basename(dir), 'codex', state);
143
+ else if (!stat.isFile()) bump(state, 'non_regular');
144
+ }
145
+ }
146
+ await walk(path.join(app, 'sessions'));
147
+ const memories = path.join(app, 'memories');
148
+ for (const name of await children(memories, state)) {
149
+ if (!name.endsWith('.md')) continue;
150
+ const file = path.join(memories, name);
151
+ const stat = await statPath(file, 'file', state, true);
152
+ if (stat) state.memoryFiles.push({ file, mtimeMs: stat.mtimeMs });
153
+ }
154
+ }
155
+ }
156
+ if (sources.has('gemini-cli')) {
157
+ const app = path.join(home, '.gemini');
158
+ if (await statPath(app, 'directory', state)) {
159
+ const tmp = path.join(app, 'tmp');
160
+ if (await statPath(tmp, 'directory', state)) {
161
+ const projects = state.allProjects ? await children(tmp, state) : [state.geminiProjectHash];
162
+ for (const project of projects) {
163
+ const dir = path.join(tmp, project);
164
+ if (!await statPath(dir, 'directory', state)) continue;
165
+ for (const name of await children(path.join(dir, 'chats'), state)) {
166
+ if (name.startsWith('session-') && name.endsWith('.jsonl')) await candidate(path.join(dir, 'chats', name), 'gemini-cli', project, 'gemini', state);
167
+ }
168
+ const logs = path.join(dir, 'logs.json');
169
+ try {
170
+ await fs.promises.lstat(logs);
171
+ await candidate(logs, 'gemini-cli', project, 'gemini-logs', state);
172
+ } catch (error) { if (error.code !== 'ENOENT') bump(state, 'unreadable'); }
173
+ }
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ async function safeOpen(file, state) {
180
+ // Recheck each path within HOME immediately before opening to catch replaced links.
181
+ const relative = path.relative(state.home, file);
182
+ if (relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) return null;
183
+ let current = state.home;
184
+ if (!await statPath(current, 'directory', state)) return null;
185
+ const parts = relative.split(path.sep);
186
+ for (const name of parts.slice(0, -1)) {
187
+ current = path.join(current, name);
188
+ if (!await statPath(current, 'directory', state)) return null;
189
+ }
190
+ const before = await statPath(file, 'file', state);
191
+ if (!before) return null;
192
+ try {
193
+ const handle = await fs.promises.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
194
+ const after = await handle.stat();
195
+ if (!after.isFile() || before.ino !== after.ino || before.dev !== after.dev) {
196
+ await handle.close();
197
+ bump(state, 'non_regular');
198
+ return null;
199
+ }
200
+ state.filesRead.push(file);
201
+ if (after.size > MAX_FILE) bump(state, 'file_limit');
202
+ return handle;
203
+ } catch { bump(state, 'unreadable'); return null; }
204
+ }
205
+
206
+ async function scanLines(file, state, onLine) {
207
+ const handle = await safeOpen(file, state);
208
+ if (!handle) return false;
209
+ let fragments = [], length = 0, oversize = false, stopped = false;
210
+ function line() {
211
+ if (!oversize && length && onLine(Buffer.concat(fragments, length).toString('utf8')) === false) stopped = true;
212
+ fragments = []; length = 0; oversize = false;
213
+ }
214
+ try {
215
+ const stream = handle.createReadStream({ autoClose: false, highWaterMark: 64 * 1024, start: 0, end: MAX_FILE - 1 });
216
+ for await (const chunk of stream) {
217
+ if (stopped) break;
218
+ let start = 0;
219
+ for (let end = chunk.indexOf(10); ; end = chunk.indexOf(10, start)) {
220
+ const stop = end === -1 ? chunk.length : end;
221
+ if (!oversize && stop > start) {
222
+ length += stop - start;
223
+ if (length > MAX_LINE) { oversize = true; fragments = []; bump(state, 'oversize_line'); }
224
+ else fragments.push(chunk.subarray(start, stop));
225
+ }
226
+ if (end === -1) break;
227
+ line();
228
+ if (stopped) break;
229
+ start = end + 1;
230
+ }
231
+ if (stopped) break;
232
+ }
233
+ // A capped file's partial final record is not a complete JSON line.
234
+ if (!stopped) {
235
+ const stat = await handle.stat();
236
+ if (stat.size <= MAX_FILE) line();
237
+ }
238
+ return true;
239
+ } catch { bump(state, 'unreadable'); return false; }
240
+ finally { await handle.close(); }
241
+ }
242
+
243
+ function parsedLine(line, state) {
244
+ try {
245
+ const record = JSON.parse(line);
246
+ if (!record || Array.isArray(record) || typeof record !== 'object') { bump(state, 'unknown_format'); return null; }
247
+ return record;
248
+ } catch { bump(state, 'malformed_line'); return null; }
249
+ }
250
+
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: [] };
253
+ }
254
+
255
+ async function readClaude(file, state) {
256
+ const session = baseSession(file);
257
+ if (!state.allProjects) session.project = path.basename(state.projectDir);
258
+ let known = false, automation = false, sessionCwd = null;
259
+ const ok = await scanLines(file.file, state, line => {
260
+ const record = parsedLine(line, state);
261
+ if (!record) return;
262
+ if (typeof record.cwd === 'string') sessionCwd = record.cwd;
263
+ if (typeof record.entrypoint === 'string' && record.entrypoint.startsWith('sdk')) automation = true;
264
+ if (record.type !== 'user') return;
265
+ known = true;
266
+ if (!state.allProjects && !belongsToProject(sessionCwd, state.projectDir)) {
267
+ bump(state, typeof sessionCwd === 'string' ? 'other_project' : 'project_unknown');
268
+ return;
269
+ }
270
+ if (record.isMeta || record.isSidechain || record.isCompactSummary || record.isVisibleInTranscriptOnly) { bump(state, 'non_typed'); return; }
271
+ if (typeof record.sessionId === 'string') session.sessionId = record.sessionId;
272
+ const text = typedText(textItems(record.message && record.message.content, 'text'), state);
273
+ if (text) session.messages.push(text);
274
+ });
275
+ if (!ok) return [];
276
+ if (automation) { bump(state, 'automation_session'); return []; }
277
+ if (!known) bump(state, 'unknown_format');
278
+ return session.messages.length ? [session] : [];
279
+ }
280
+
281
+ async function readCodex(file, state) {
282
+ const session = baseSession(file);
283
+ let known = false, automation = false, projectMatches = state.allProjects;
284
+ const ok = await scanLines(file.file, state, line => {
285
+ const record = parsedLine(line, state);
286
+ if (!record) return;
287
+ if (record.type === 'session_meta' && record.payload && typeof record.payload === 'object') {
288
+ known = true;
289
+ const meta = record.payload;
290
+ if (meta.source === 'exec' || (meta.source && typeof meta.source === 'object' && Object.prototype.hasOwnProperty.call(meta.source, 'subagent'))) automation = true;
291
+ if (typeof meta.id === 'string') session.sessionId = meta.id;
292
+ if (!state.allProjects) {
293
+ projectMatches = belongsToProject(meta.cwd, state.projectDir);
294
+ if (!projectMatches) {
295
+ bump(state, typeof meta.cwd === 'string' ? 'other_project' : 'project_unknown');
296
+ return false;
297
+ }
298
+ }
299
+ if (typeof meta.cwd === 'string') session.project = path.basename(meta.cwd);
300
+ return;
301
+ }
302
+ if (record.type !== 'response_item' || !record.payload || record.payload.type !== 'message' || record.payload.role !== 'user') return;
303
+ known = true;
304
+ if (!projectMatches) {
305
+ if (!state.allProjects) bump(state, 'project_unknown');
306
+ if (!state.allProjects) return false;
307
+ return;
308
+ }
309
+ const text = typedText(textItems(record.payload.content, 'input_text'), state);
310
+ if (text) session.messages.push(text);
311
+ });
312
+ if (!ok) return [];
313
+ if (automation) { bump(state, 'automation_session'); return []; }
314
+ if (!known) bump(state, 'unknown_format');
315
+ if (!projectMatches) return [];
316
+ return session.messages.length ? [session] : [];
317
+ }
318
+
319
+ async function readGemini(file, state) {
320
+ const session = baseSession(file);
321
+ let known = false, messages = [];
322
+ const ok = await scanLines(file.file, state, line => {
323
+ const record = parsedLine(line, state);
324
+ if (!record) return;
325
+ if (typeof record.sessionId === 'string') { session.sessionId = record.sessionId; known = true; }
326
+ if (record.$set && Object.prototype.hasOwnProperty.call(record.$set, 'messages')) {
327
+ if (Array.isArray(record.$set.messages)) { messages = record.$set.messages; known = true; }
328
+ else bump(state, 'unknown_format');
329
+ }
330
+ });
331
+ if (!ok) return [];
332
+ for (const message of messages) {
333
+ if (!message || message.type !== 'user') continue;
334
+ 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
+ const text = typedText(items, state);
336
+ if (text) session.messages.push(text);
337
+ }
338
+ if (!known) bump(state, 'unknown_format');
339
+ return session.messages.length ? [session] : [];
340
+ }
341
+
342
+ async function readGeminiLogs(file, state) {
343
+ const grouped = new Map();
344
+ // Old logs are JSON arrays. Frame one entry at a time instead of buffering the array.
345
+ let entry = '', entryBytes = 0, depth = 0, quoted = false, escaped = false, oversize = false, started = false, finished = false, invalid = false;
346
+ function accept() {
347
+ if (oversize) { bump(state, 'oversize_line'); return; }
348
+ 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;
353
+ if (!grouped.has(record.sessionId)) {
354
+ const session = baseSession(file);
355
+ session.sessionId = record.sessionId;
356
+ grouped.set(record.sessionId, session);
357
+ }
358
+ grouped.get(record.sessionId).messages.push(text);
359
+ }
360
+ const ok = await scanLines(file.file, state, line => {
361
+ for (const character of `${line}\n`) {
362
+ if (!started) {
363
+ if (/\s/.test(character)) continue;
364
+ if (character !== '[') { invalid = true; return; }
365
+ started = true;
366
+ continue;
367
+ }
368
+ if (invalid) return;
369
+ if (!depth) {
370
+ if (/\s/.test(character) || character === ',') continue;
371
+ if (character === ']') { finished = true; continue; }
372
+ if (finished || character !== '{') { invalid = true; return; }
373
+ depth = 1; entry = '{'; entryBytes = 1; quoted = false; escaped = false; oversize = false;
374
+ continue;
375
+ }
376
+ if (!oversize) {
377
+ entryBytes += Buffer.byteLength(character, 'utf8');
378
+ entry += character;
379
+ if (entryBytes > MAX_LINE) { oversize = true; entry = ''; }
380
+ }
381
+ if (quoted) {
382
+ if (escaped) escaped = false;
383
+ else if (character === '\\') escaped = true;
384
+ else if (character === '"') quoted = false;
385
+ } else if (character === '"') quoted = true;
386
+ else if (character === '{' || character === '[') depth += 1;
387
+ else if (character === '}' || character === ']') {
388
+ depth -= 1;
389
+ if (!depth) accept();
390
+ }
391
+ }
392
+ });
393
+ if (!ok) return [];
394
+ if (!started || invalid) { bump(state, 'unknown_format'); return []; }
395
+ if (!finished || depth) bump(state, 'malformed_line');
396
+ return [...grouped.values()];
397
+ }
398
+
399
+ async function readMemory(file, state) {
400
+ const lines = [];
401
+ if (!await scanLines(file.file, state, line => lines.push(line))) return null;
402
+ const text = lines.join('\n').replace(CTRL, '').trim();
403
+ if (!text) return null;
404
+ if (privateMatch(text, state.privateTerms)) { bump(state, 'private_match'); return null; }
405
+ return { file: file.file, text, date: new Date(file.mtimeMs).toISOString() };
406
+ }
407
+
408
+ async function readSessions({ home = os.homedir(), projectDir = process.cwd(), allProjects = false, sources = [], limit = 20, privateTerms = [] } = {}) {
409
+ const selectedSources = new Set(Array.isArray(sources) ? sources.filter(source => SOURCES.has(source)) : []);
410
+ const maximum = Number.isInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 20;
411
+ projectDir = path.resolve(projectDir);
412
+ const state = {
413
+ home: path.resolve(home), projectDir, allProjects,
414
+ geminiProjectHash: crypto.createHash('sha256').update(projectDir).digest('hex'),
415
+ candidates: [], memoryFiles: [], filesRead: [], filesChecked: 0, skipped: {},
416
+ privateTerms: Array.isArray(privateTerms) ? privateTerms.filter(term => typeof term === 'string' && fold(term).trim()).map(fold) : []
417
+ };
418
+ await discover(state.home, selectedSources, state);
419
+ state.candidates.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file));
420
+ const sessions = [], geminiSessions = new Map();
421
+ const readers = { claude: readClaude, codex: readCodex, gemini: readGemini, 'gemini-logs': readGeminiLogs };
422
+ for (const file of state.candidates) {
423
+ if (sessions.length >= maximum) break;
424
+ const found = await readers[file.format](file, state);
425
+ for (const session of found) {
426
+ if (session.source === 'gemini-cli' && geminiSessions.has(session.sessionId)) {
427
+ const existing = geminiSessions.get(session.sessionId);
428
+ for (const text of session.messages) {
429
+ if (existing.messages.includes(text)) bump(state, 'duplicate_message');
430
+ else existing.messages.push(text);
431
+ }
432
+ } else if (sessions.length < maximum) {
433
+ if (session.source === 'gemini-cli') geminiSessions.set(session.sessionId, session);
434
+ sessions.push(session);
435
+ }
436
+ }
437
+ }
438
+ const memories = [];
439
+ state.memoryFiles.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file));
440
+ for (const file of state.memoryFiles.slice(MAX_MEMORIES)) bump(state, 'memory_limit');
441
+ for (const file of state.memoryFiles.slice(0, MAX_MEMORIES)) {
442
+ const memory = await readMemory(file, state);
443
+ if (memory) memories.push(memory);
444
+ }
445
+ return { sessions, memories, filesRead: state.filesRead, filesChecked: state.filesChecked, skipped: state.skipped };
446
+ }
447
+
448
+ module.exports = { readSessions };
package/bin/uninstall.cjs CHANGED
@@ -12,6 +12,16 @@ const CONFIG = '.agent-personalizer.json';
12
12
  const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
13
13
 
14
14
  function refuse(message) { throw new renderer.Refusal(message); }
15
+ // Install appends "\n" + block + "\n" to a pre-existing file that ends in a newline
16
+ // (render.cjs splice). Take back exactly that: the newline ending the end marker and one
17
+ // separator newline before the begin marker, so an untouched file returns byte for byte.
18
+ function stripBlock(existing, ms) {
19
+ let before = existing.slice(0, ms.bStart), after = existing.slice(ms.eEnd);
20
+ if (after.startsWith('\r\n')) after = after.slice(2);
21
+ else if (after.startsWith('\n')) after = after.slice(1);
22
+ if (before.endsWith('\n\n')) before = before.slice(0, -1);
23
+ return before + after;
24
+ }
15
25
  function uninstall(dir, { dry = false } = {}) {
16
26
  const previousThrows = renderer.DIE_THROWS;
17
27
  renderer.DIE_THROWS = true;
@@ -84,12 +94,33 @@ function run(dir, dry) {
84
94
  const homeNames = new Set(['CLAUDE.md', 'AGENTS.md']);
85
95
  const expected = new Map();
86
96
  for (const p of recipe) {
87
- if (homeNames.has(p.rel)) continue; // compare these after rendering their block
97
+ if (homeNames.has(p.rel) || p.rel === 'LEARNED.md') continue; // entries always belong to the user
88
98
  const bytes = p.src ? fs.readFileSync(p.src) : Buffer.from(p.text);
89
99
  if (expected.has(p.rel) && !expected.get(p.rel).equals(bytes)) refuse(`${p.rel}: conflicting install paths; nothing was removed`);
90
100
  expected.set(p.rel, bytes);
91
101
  }
92
102
  const tracked = new Set(modern ? [CONFIG, ...Object.keys(cfg.installed)] : [CONFIG, 'USER.md', ...recipe.map(p => p.rel)]);
103
+ tracked.delete('LEARNED.md');
104
+ // Digest files use the same ownership proof as every other installed file.
105
+ const digestFolder = '.agent-personalizer';
106
+ const digestFiles = [];
107
+ function collectDigest(rel) {
108
+ const full = probe(rel, 'dir');
109
+ if (!full) return;
110
+ const names = fs.readdirSync(full).sort();
111
+ observations.get(rel).children = names;
112
+ if ((cfg.createdDirectories || []).includes(rel)) dirs.add(rel);
113
+ for (const name of names) {
114
+ const child = `${rel}/${name}`;
115
+ const info = fs.lstatSync(path.join(root, child));
116
+ if (info.isDirectory() && !info.isSymbolicLink()) collectDigest(child);
117
+ else { read(child); digestFiles.push(child); }
118
+ }
119
+ }
120
+ // Validate even unexpected descendants, then keep anything without a matching creation hash.
121
+ collectDigest(digestFolder);
122
+ for (const rel of digestFiles) tracked.add(rel);
123
+ const learned = read('LEARNED.md');
93
124
  if (!modern) for (const key of cfg.targets) {
94
125
  const target = TARGETS[key];
95
126
  tracked.add(target.file);
@@ -115,6 +146,10 @@ function run(dir, dry) {
115
146
  : renderer.renderedContents(root, cfg);
116
147
  const plan = [];
117
148
  const add = (rel, action, output, reason) => plan.push({ rel, action, output, reason });
149
+ for (const rel of digestFiles) {
150
+ const bytes = read(rel), recorded = recordedHash(cfg, rel);
151
+ if (bytes) add(rel, recorded && sha256(bytes) === recorded ? 'remove' : 'keep', null, 'unrecorded or edited digest-folder file');
152
+ }
118
153
  for (const entry of rendered) {
119
154
  const { rel, key, block, raw } = entry;
120
155
  if (!tracked.has(rel)) continue;
@@ -142,7 +177,7 @@ function run(dir, dry) {
142
177
  // edited (or vice versa).
143
178
  const currentBlock = renderer.between(existing, rel);
144
179
  const blockUnedited = recorded ? (currentBlock !== null && sha256(Buffer.from(currentBlock)) === recorded) : matchesBlock;
145
- if (blockUnedited) add(rel, 'strip', Buffer.from(existing.slice(0, ms.bStart) + existing.slice(ms.eEnd)), 'pre-existing file; removed only the marked block');
180
+ if (blockUnedited) add(rel, 'strip', Buffer.from(stripBlock(existing, ms)), 'pre-existing file; removed only the marked block');
146
181
  else add(rel, 'keep', null, ms.kind === 'none' ? 'pre-existing file; block already absent' : 'edited');
147
182
  continue;
148
183
  }
@@ -171,7 +206,7 @@ function run(dir, dry) {
171
206
  add('USER.md', userUnedited ? 'remove' : 'keep', null, 'edited');
172
207
  }
173
208
  for (const [rel, bytes] of expected) {
174
- if (!tracked.has(rel)) continue;
209
+ if (!tracked.has(rel) || digestFiles.includes(rel)) continue;
175
210
  const existing = read(rel);
176
211
  if (!existing) continue;
177
212
  const recorded = recordedHash(cfg, rel);
@@ -182,16 +217,22 @@ function run(dir, dry) {
182
217
  const unedited = recorded ? sha256(existing) === recorded : existing.equals(bytes);
183
218
  add(rel, unedited ? 'remove' : 'keep', null, 'edited');
184
219
  }
220
+ // LEARNED.md belongs to the user once it holds anything they wrote. Only the exact template
221
+ // bytes this package recorded writing are removed; a pre-existing or edited file stays.
222
+ const recordedLearned = recordedHash(cfg, 'LEARNED.md');
223
+ const learnedUntouched = !!learned && !!recordedLearned && sha256(learned) === recordedLearned;
224
+ if (learnedUntouched) add('LEARNED.md', 'remove', null, 'untouched template');
185
225
  // Earlier notes folders, retired rules and all other recorded paths are inventory too.
186
226
  // Current answers cannot erase history, and an unrecorded file is never adopted here.
187
227
  const planned = new Set(plan.map(p => p.rel));
188
228
  if (modern) for (const rel of Object.keys(cfg.installed)) {
189
- if (planned.has(rel)) continue;
229
+ if (planned.has(rel) || rel === 'LEARNED.md') continue;
190
230
  const bytes = read(rel);
191
231
  if (bytes) add(rel, sha256(bytes) === recordedHash(cfg, rel) ? 'remove' : 'keep', null, 'edited');
192
232
  }
193
233
  if (new Set(plan.map(p => p.rel)).size !== plan.length) refuse('conflicting tracked paths; nothing was removed');
194
- const retained = plan.filter(p => p.action !== 'remove');
234
+ // A pre-existing home file with only its block removed holds nothing of ours to review.
235
+ const retained = plan.filter(p => p.action === 'keep');
195
236
  const removeConfig = retained.length === 0;
196
237
  const gone = new Set(plan.filter(p => p.action === 'remove').map(p => p.rel));
197
238
  const emptyDirs = [];
@@ -207,7 +248,8 @@ function run(dir, dry) {
207
248
  const full = probe(rel, saved.kind);
208
249
  if (!full) refuse(`${rel} changed during preflight; nothing was removed`);
209
250
  const now = fs.lstatSync(full);
210
- if (now.dev !== saved.info.dev || now.ino !== saved.info.ino || now.mode !== saved.info.mode || (saved.bytes && !fs.readFileSync(full).equals(saved.bytes)))
251
+ if (now.dev !== saved.info.dev || now.ino !== saved.info.ino || now.mode !== saved.info.mode || (saved.bytes && !fs.readFileSync(full).equals(saved.bytes))
252
+ || (saved.children && JSON.stringify(fs.readdirSync(full).sort()) !== JSON.stringify(saved.children)))
211
253
  refuse(`${rel} changed during preflight; nothing was removed`);
212
254
  }
213
255
  for (const rel of [...plan.filter(p => p.action !== 'keep').map(p => p.rel), ...emptyDirs, ...(removeConfig ? [CONFIG] : [])]) {
@@ -216,6 +258,7 @@ function run(dir, dry) {
216
258
  }
217
259
  const label = dry ? 'would ' : '';
218
260
  if (dry) console.log('Dry run: preview only; no files changed.');
261
+ if (learned && !learnedUntouched) console.log('kept LEARNED.md (your entries)');
219
262
  for (const p of plan) {
220
263
  if (p.action === 'keep') { console.log(`kept ${p.rel} (${p.reason})`); continue; }
221
264
  if (!dry) {
@@ -246,12 +289,13 @@ function run(dir, dry) {
246
289
  // Config is always the final removal. A kept tracked path keeps the record for review.
247
290
  if (removeConfig) {
248
291
  if (!dry) {
249
- for (const p of plan) if (probe(p.rel)) refuse(`${p.rel} still exists; ${CONFIG} kept`);
292
+ for (const p of plan) if (p.action === 'remove' && probe(p.rel)) refuse(`${p.rel} still exists; ${CONFIG} kept`);
250
293
  const full = probe(CONFIG);
251
294
  if (!full || !fs.readFileSync(full).equals(observations.get(CONFIG).bytes)) refuse(`${CONFIG} changed; config kept`);
252
295
  fs.unlinkSync(full);
253
296
  }
254
297
  console.log(`${label}remove ${CONFIG}`);
298
+ require('./git-exclude.cjs').unprotect(root, { dry });
255
299
  } else console.log(`kept ${CONFIG} (tracked files remain; review the kept paths above)`);
256
300
  if (level >= 3) console.log('Manual step: remove any SessionStart entry for hooks/claude-code/session-start.sh from .claude/settings.json or ~/.claude/settings.json if you registered it. Settings are kept.');
257
301
  }
package/check/gate.cjs CHANGED
@@ -97,7 +97,7 @@ function refuseTrackedList(file) {
97
97
  }
98
98
  }
99
99
 
100
- function loadList(file) {
100
+ function loadList(file, { allowEmpty = false } = {}) {
101
101
  let st = null;
102
102
  try { st = fs.lstatSync(file); } catch (_) { st = null; }
103
103
  if (!st) die(`${file} not found.\nCopy check/forbidden.example.txt to that path and fill it in. The gate does not pass without it.`);
@@ -117,7 +117,7 @@ function loadList(file) {
117
117
  allow.push(a);
118
118
  } else terms.push(line);
119
119
  });
120
- if (!terms.length) die('forbidden list has no terms.');
120
+ if (!terms.length && !allowEmpty) die('forbidden list has no terms.');
121
121
  return { terms, allow, real };
122
122
  }
123
123
 
@@ -354,4 +354,5 @@ function main() {
354
354
  console.log(`gate clean: 0 hits across ${files} files, text and paths (${scan.mode === 'git' ? 'files git would ship, index blobs included' : 'every file under --dir'}; ${skipped.length} skipped)`);
355
355
  }
356
356
 
357
- main();
357
+ module.exports = { loadList };
358
+ if (require.main === module) main();
package/docs/README.md CHANGED
@@ -1,10 +1,11 @@
1
1
  # Documentation
2
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.
3
+ agent-personalizer writes shared AI instructions and, with your consent, helps your AI learn from your recent sessions. Start with installation, then choose the guides for your setup.
4
4
 
5
5
  | Guide | What it gives you |
6
6
  |---|---|
7
7
  | [Install and use](install.md) | Interactive setup, scripted answers, flags, updates and uninstall. |
8
+ | [Learning and privacy](learning.md) | Consent, session sources, evidence-backed questions, shared entries and forgetting the digest. |
8
9
  | [Instruction tiers](tiers.md) | Where style, home files, session contracts, rule owners and memory belong. |
9
10
  | [Paste guide](paste-guide.md) | Which file each AI reads and how to refresh pasted instructions. |
10
11
  | [Companion tools](companions.md) | Notes connectors, access controls and approval mechanisms. |
@@ -2,7 +2,7 @@
2
2
 
3
3
  This repo tells an AI *how to behave with you*. Two companions govern *what it can touch* and *what it is allowed to carry*. Neither is required; both make the onboarding answers enforceable instead of advisory.
4
4
 
5
- | Your answer in the interview | What enforces it without a companion | With a companion |
5
+ | Your saved setting | What enforces it without a companion | With a companion |
6
6
  |---|---|---|
7
7
  | **Always ask before** delete / publish / send / spend | the AI remembering | obsidian-tc: destructive tools fail closed until a human confirms |
8
8
  | **Off limits** folders | the AI remembering | obsidian-tc: folder ACL deny, per caller |
@@ -39,7 +39,7 @@ Lexical search and every note tool work immediately; semantic and graph retrieva
39
39
 
40
40
  **Read in this order**: the [essay](https://sierracatalina.com/signal/the-context-layer) (the argument in plain language) → [architecture](https://sierracatalina.com/context-layer/architecture) → [specification](https://sierracatalina.com/context-layer/specification) → [implementation](https://sierracatalina.com/context-layer/implementation) → [code](https://sierracatalina.com/context-layer/code) (v0.2 contracts, encrypted local vault, four-state policy, scoped bundles, anchored receipts, a files adapter, a local-agent consumer) → [demo](https://sierracatalina.com/context-layer/demo). Its stated boundary: it does not claim production key custody or a portable signing suite.
41
41
 
42
- **How it pairs with this repo.** Three of the interview's answers are Context Layer decisions in miniature:
42
+ **How it pairs with this repo.** Three saved settings are Context Layer decisions in miniature:
43
43
  - **Write policy** "logs and inbox only" or "ask before every write" is the Layer's rule that memory writes remain proposals until approved.
44
44
  - **Off limits** is the Layer's vault stage: originals that never enter a bundle.
45
45
  - **Always ask before** is the Layer's decide stage: allow, reduce, approve or deny by action and recipient.