agent-personalizer 0.10.0 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -1
- package/CONTRIBUTING.md +1 -1
- package/README.md +19 -18
- package/SECURITY.md +1 -1
- package/bin/agent-personalizer.js +130 -26
- package/bin/global.cjs +155 -29
- package/bin/home.cjs +69 -4
- package/bin/install-plan.cjs +10 -6
- package/bin/learn.cjs +5 -4
- package/bin/sessions.cjs +57 -14
- package/check/gate.cjs +76 -30
- package/docs/companions.md +11 -11
- package/docs/guarantees.md +4 -4
- package/docs/install.md +1 -1
- package/docs/learning.md +5 -5
- package/docs/paste-guide.md +13 -11
- package/examples/answers.json +1 -1
- package/hooks/README.md +1 -1
- package/hooks/gemini-cli/session-start.sh +19 -7
- package/llms.txt +2 -1
- package/package.json +22 -9
- package/render/onboarding.cjs +8 -8
- package/render/render.cjs +1 -1
- package/skills/agent-personalizer/SKILL.md +1 -1
package/bin/global.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
// Global targets have fixed home-relative names; profile ownership stays inside its own folder.
|
|
2
|
+
// Global targets have fixed home-relative names (except CODEX_HOME when set); profile ownership stays inside its own folder.
|
|
3
3
|
const fs = require('fs');
|
|
4
|
-
const { resolveHome } = require('./home.cjs');
|
|
4
|
+
const { rootedAbsolute, resolveHome, resolveCodexHome, walkRealChain, hasNonEmptyOverride } = require('./home.cjs');
|
|
5
5
|
const path = require('path');
|
|
6
6
|
const renderer = require('../render/render.cjs');
|
|
7
7
|
const onboarding = require('../render/onboarding.cjs');
|
|
@@ -21,6 +21,15 @@ function blockHash(text, rel) {
|
|
|
21
21
|
if (ms.kind === 'malformed') refuse(`${rel}: malformed marker block; nothing was changed`);
|
|
22
22
|
return ms.kind === 'one' ? sha256(Buffer.from(text.slice(ms.bStart, ms.eEnd))) : null;
|
|
23
23
|
}
|
|
24
|
+
function stripOwnedBlock(text, ms, owned) {
|
|
25
|
+
let before = text.slice(0, ms.bStart), after = text.slice(ms.eEnd);
|
|
26
|
+
if (after.startsWith('\r\n')) after = after.slice(2);
|
|
27
|
+
else if (after.startsWith('\n')) after = after.slice(1);
|
|
28
|
+
if (owned.appended && owned.separator && before.endsWith(owned.separator)) {
|
|
29
|
+
before = before.slice(0, -owned.separator.length);
|
|
30
|
+
}
|
|
31
|
+
return before + after;
|
|
32
|
+
}
|
|
24
33
|
function validateGlobal(cfg) {
|
|
25
34
|
if (!cfg.global || cfg.level !== 1) refuse('global profile config must identify a level-1 global install');
|
|
26
35
|
for (const target of cfg.targets || []) if (!Object.hasOwn(TARGETS, target) && target !== 'onboarding') refuse(`unsupported global target: ${target}`);
|
|
@@ -28,10 +37,45 @@ function validateGlobal(cfg) {
|
|
|
28
37
|
for (const [key, info] of Object.entries(cfg.globalFiles || {})) {
|
|
29
38
|
if (!Object.hasOwn(TARGETS, key) || !info || typeof info.created !== 'boolean' || !HASH.test(info.blockHash) || !HASH.test(info.fileHash)
|
|
30
39
|
|| !['', '\n', '\n\n'].includes(info.separator) || typeof info.appended !== 'boolean') refuse('invalid global target ownership');
|
|
40
|
+
if (info.path !== undefined && (key !== 'agents' || !rootedAbsolute(info.path))) refuse('invalid global target path');
|
|
41
|
+
if (info.createdDirs !== undefined && (key !== 'agents' || !Array.isArray(info.createdDirs) || info.createdDirs.some(d => !rootedAbsolute(d)))) {
|
|
42
|
+
refuse('invalid global target directory ownership');
|
|
43
|
+
}
|
|
31
44
|
}
|
|
32
45
|
if (cfg.globalDirectories !== undefined && (!Array.isArray(cfg.globalDirectories) || cfg.globalDirectories.some(rel => ![SOURCE, '.claude', '.codex', '.gemini', '.hermes'].includes(rel)))) refuse('invalid global directory inventory');
|
|
33
46
|
}
|
|
34
47
|
|
|
48
|
+
function resolveCodexTarget(root, profileRoot) {
|
|
49
|
+
const raw = resolveCodexHome(root);
|
|
50
|
+
const { base, missingDirs, dir } = walkRealChain(raw, { allowDarwinRootLink: true, action: 'nothing was written' });
|
|
51
|
+
if (dir === profileRoot || (dir + path.sep).startsWith(profileRoot + path.sep)) {
|
|
52
|
+
refuse('CODEX_HOME cannot point inside ~/.agent-personalizer; nothing was written');
|
|
53
|
+
}
|
|
54
|
+
const defaultDir = path.join(root, '.codex');
|
|
55
|
+
if (dir === defaultDir) return { external: false, dir, rel: TARGETS.agents, full: path.join(dir, 'AGENTS.md') };
|
|
56
|
+
const full = path.join(dir, 'AGENTS.md');
|
|
57
|
+
if (!missingDirs.length) {
|
|
58
|
+
let fileSt = null;
|
|
59
|
+
try { fileSt = fs.lstatSync(full); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
60
|
+
if (fileSt) {
|
|
61
|
+
if (fileSt.isSymbolicLink()) refuse(`${full} is a symlink; refusing to write through it`);
|
|
62
|
+
if (!fileSt.isFile()) refuse(`${full} is not a regular file; nothing was written`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { external: true, base, missingDirs, dir, file: 'AGENTS.md', full };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function readExternalFile(full, label, action = 'nothing was changed') {
|
|
69
|
+
const dir = path.dirname(full);
|
|
70
|
+
const chain = walkRealChain(dir, { allowDarwinRootLink: false, action });
|
|
71
|
+
if (chain.missingDirs.length) return null;
|
|
72
|
+
let st = null;
|
|
73
|
+
try { st = fs.lstatSync(full); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
|
|
74
|
+
if (st.isSymbolicLink()) refuse(`${label} is a symlink; ${action}`);
|
|
75
|
+
if (!st.isFile()) refuse(`${label} is not a regular file; ${action}`);
|
|
76
|
+
return fs.readFileSync(full);
|
|
77
|
+
}
|
|
78
|
+
|
|
35
79
|
async function run({ args, commitPlan, probe, readConfig, ask }) {
|
|
36
80
|
const prior = renderer.DIE_THROWS;
|
|
37
81
|
renderer.DIE_THROWS = true;
|
|
@@ -78,9 +122,10 @@ async function execute({ args, commitPlan, probe, readConfig, ask }) {
|
|
|
78
122
|
try { answers = onboarding.validate(JSON.parse(fs.readFileSync(file === '-' ? 0 : path.resolve(file), 'utf8'))); }
|
|
79
123
|
catch (e) { refuse(`--answers: ${e.message}`); }
|
|
80
124
|
}
|
|
125
|
+
const codexTarget = targets.includes('agents') ? resolveCodexTarget(root, profileRoot) : null;
|
|
81
126
|
const old = stored.cfg;
|
|
82
127
|
const installed = { ...(old.installed || {}) };
|
|
83
|
-
const writes = [];
|
|
128
|
+
const writes = [], removals = [], external = [], pruneExternalDirs = [];
|
|
84
129
|
const read = rel => {
|
|
85
130
|
const found = probe(root, `${SOURCE}/${rel}`);
|
|
86
131
|
if (!found.exists) return null;
|
|
@@ -116,35 +161,101 @@ async function execute({ args, commitPlan, probe, readConfig, ask }) {
|
|
|
116
161
|
.replace(/`USER\.md` sits next to `(?:CLAUDE|AGENTS|GEMINI)\.md`\.(?: In (?:Claude Code|Gemini CLI and Google Antigravity), `(?:CLAUDE|GEMINI)\.md` loads automatically;)?/g, 'Read `USER.md` from the global profile source.')
|
|
117
162
|
.replace(/"npx agent-personalizer --dir \.", or "node render\/render\.cjs --dir \." at level 3/g, '"npx agent-personalizer --global"')
|
|
118
163
|
.replace(/(^|[^A-Za-z0-9_./-])(USER\.md|LEARNED\.md|AGENT_ONBOARDING\.md|\.agent-personalizer\.json|\.agent-personalizer\/digest\.md)(?![A-Za-z0-9_/-])/g, (_, prefix, rel) => prefix + path.join(profileRoot, rel));
|
|
164
|
+
|
|
165
|
+
// If agents moved between ~/.codex and a custom CODEX_HOME, retire the unedited block at the old location.
|
|
166
|
+
const oldAgents = old.globalFiles?.agents;
|
|
167
|
+
if (codexTarget && oldAgents) {
|
|
168
|
+
const oldFull = oldAgents.path || path.join(root, TARGETS.agents);
|
|
169
|
+
if (oldFull !== codexTarget.full) {
|
|
170
|
+
if (!oldAgents.path) {
|
|
171
|
+
const prevFound = probe(root, TARGETS.agents);
|
|
172
|
+
if (prevFound.exists) {
|
|
173
|
+
if (!fs.lstatSync(prevFound.full).isFile()) refuse(`${TARGETS.agents} is not a regular file`);
|
|
174
|
+
const prevText = decode(fs.readFileSync(prevFound.full), TARGETS.agents);
|
|
175
|
+
const prevMs = renderer.markerState(prevText, TARGETS.agents);
|
|
176
|
+
const prevHash = blockHash(prevText, TARGETS.agents);
|
|
177
|
+
if (prevMs.kind === 'one' && prevHash === oldAgents.blockHash) {
|
|
178
|
+
const stripped = stripOwnedBlock(prevText, prevMs, oldAgents);
|
|
179
|
+
if (oldAgents.created && stripped === '') removals.push({ rel: TARGETS.agents });
|
|
180
|
+
else writes.push({ rel: TARGETS.agents, bytes: Buffer.from(stripped) });
|
|
181
|
+
} else if (prevMs.kind === 'one') console.log(`kept ${TARGETS.agents} (edited)`);
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
const prevBytes = readExternalFile(oldAgents.path, oldAgents.path);
|
|
185
|
+
if (prevBytes) {
|
|
186
|
+
const prevText = decode(prevBytes, oldAgents.path);
|
|
187
|
+
const prevMs = renderer.markerState(prevText, oldAgents.path);
|
|
188
|
+
const prevHash = blockHash(prevText, oldAgents.path);
|
|
189
|
+
if (prevMs.kind === 'one' && prevHash === oldAgents.blockHash) {
|
|
190
|
+
const stripped = stripOwnedBlock(prevText, prevMs, oldAgents);
|
|
191
|
+
if (oldAgents.created && stripped === '') external.push({ base: path.dirname(oldAgents.path), missingDirs: [], file: path.basename(oldAgents.path), remove: true });
|
|
192
|
+
else external.push({ base: path.dirname(oldAgents.path), missingDirs: [], file: path.basename(oldAgents.path), bytes: Buffer.from(stripped) });
|
|
193
|
+
for (const d of oldAgents.createdDirs || []) pruneExternalDirs.push(d);
|
|
194
|
+
} else if (prevMs.kind === 'one') console.log(`kept ${oldAgents.path} (edited)`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
119
200
|
const rendered = renderer.renderedContents(profileRoot, renderCfg, { profileSource: decode(user, 'USER.md'), learned, boilerplate: qualify });
|
|
120
201
|
for (const entry of rendered) {
|
|
121
202
|
if (entry.key === 'onboarding') { writeSource(entry.rel, Buffer.from(renderer.splice(null, entry.block, entry.rel))); continue; }
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
203
|
+
const isExternalAgents = entry.key === 'agents' && codexTarget && codexTarget.external;
|
|
204
|
+
const label = isExternalAgents ? codexTarget.full : TARGETS[entry.key];
|
|
205
|
+
let text = null, exists = false;
|
|
206
|
+
if (isExternalAgents) {
|
|
207
|
+
const existingBytes = fs.existsSync(codexTarget.full) ? fs.readFileSync(codexTarget.full) : null;
|
|
208
|
+
exists = !!existingBytes;
|
|
209
|
+
if (existingBytes) text = decode(existingBytes, label);
|
|
210
|
+
} else {
|
|
211
|
+
const found = probe(root, label);
|
|
212
|
+
exists = found.exists;
|
|
213
|
+
if (found.exists && !fs.lstatSync(found.full).isFile()) refuse(`${label} is not a regular file`);
|
|
214
|
+
if (found.exists) text = decode(fs.readFileSync(found.full), label);
|
|
215
|
+
}
|
|
216
|
+
const ms = text === null ? { kind: 'none' } : renderer.markerState(text, label);
|
|
217
|
+
if (ms.kind === 'malformed') refuse(`${label}: malformed marker block`);
|
|
218
|
+
const samePriorPath = Object.hasOwn(cfg.globalFiles, entry.key)
|
|
219
|
+
&& ((entry.key !== 'agents') || (cfg.globalFiles.agents?.path || path.join(root, TARGETS.agents)) === (isExternalAgents ? codexTarget.full : path.join(root, TARGETS.agents)));
|
|
220
|
+
if (ms.kind === 'one' && !samePriorPath) {
|
|
221
|
+
refuse(`${label}: foreign agent-personalizer block; remove the block from <!-- agent-personalizer:begin --> through <!-- agent-personalizer:end -->, then re-run --global. Nothing was written`);
|
|
130
222
|
}
|
|
131
223
|
const block = `Profile source: \`${path.join(profileRoot, 'USER.md')}\`. Read \`${path.join(profileRoot, 'AGENT_ONBOARDING.md')}\` for working preferences.\n\n` + entry.block;
|
|
132
|
-
const output = renderer.splice(text, block,
|
|
133
|
-
if (output.length > renderer.FILE_BUDGET) console.log(`OVER BUDGET ${
|
|
134
|
-
if (renderer.markerState(output,
|
|
135
|
-
const prior = ms.kind === 'one' ? cfg.globalFiles[entry.key] : null;
|
|
136
|
-
|
|
224
|
+
const output = renderer.splice(text, block, label);
|
|
225
|
+
if (output.length > renderer.FILE_BUDGET) console.log(`OVER BUDGET ${label} (${output.length} characters, budget ${renderer.FILE_BUDGET}; --compact shortens rules)`);
|
|
226
|
+
if (renderer.markerState(output, label).kind !== 'one' || renderer.between(output, label) !== block) refuse(`${label}: generated block would not re-parse; nothing was written`);
|
|
227
|
+
const prior = ms.kind === 'one' && samePriorPath ? cfg.globalFiles[entry.key] : null;
|
|
228
|
+
const meta = { created: !exists || !!prior?.created, blockHash: blockHash(output, label), fileHash: sha256(Buffer.from(output)),
|
|
137
229
|
appended: prior ? prior.appended : ms.kind === 'none', separator: prior ? prior.separator : (text === null ? '' : text.endsWith('\n') ? '\n' : '\n\n') };
|
|
138
|
-
|
|
230
|
+
if (isExternalAgents) {
|
|
231
|
+
meta.path = codexTarget.full;
|
|
232
|
+
if (prior?.createdDirs?.length) meta.createdDirs = [...prior.createdDirs];
|
|
233
|
+
external.push({ base: codexTarget.base, missingDirs: codexTarget.missingDirs, file: codexTarget.file, bytes: Buffer.from(output), report: `update ${label} (global profile)` });
|
|
234
|
+
} else {
|
|
235
|
+
writes.push({ rel: label, bytes: Buffer.from(output), report: `update ${label} (global profile)` });
|
|
236
|
+
}
|
|
237
|
+
cfg.globalFiles[entry.key] = meta;
|
|
139
238
|
}
|
|
140
239
|
const learnRequested = interactive && !stored.cfgExists ? await require('./learn.cjs').requestConsent({ allProjects: true }) : false;
|
|
141
|
-
const outputPaths = new Set([CONFIG, ...writes.map(p => p.rel)]);
|
|
142
|
-
await commitPlan(root, { writes, outputPaths,
|
|
143
|
-
prepare(newDirectories) {
|
|
240
|
+
const outputPaths = new Set([CONFIG, ...writes.map(p => p.rel), ...removals.map(p => p.rel)]);
|
|
241
|
+
await commitPlan(root, { writes, removals, external, outputPaths,
|
|
242
|
+
prepare(newDirectories, externalNewDirs = []) {
|
|
243
|
+
if (codexTarget?.external && cfg.globalFiles.agents && externalNewDirs.length) {
|
|
244
|
+
cfg.globalFiles.agents.createdDirs = [...new Set([...(cfg.globalFiles.agents.createdDirs || []), ...externalNewDirs])];
|
|
245
|
+
}
|
|
144
246
|
cfg.globalDirectories = [...new Set([...(old.globalDirectories || []), ...[...newDirectories].filter(rel => [SOURCE, '.claude', '.codex', '.gemini', '.hermes'].includes(rel))])].sort();
|
|
145
247
|
writes.push({ rel: CONFIG, bytes: Buffer.from(JSON.stringify(cfg, null, 2) + '\n') });
|
|
146
248
|
}
|
|
147
249
|
});
|
|
250
|
+
for (const dir of pruneExternalDirs.sort((a, b) => b.length - a.length)) {
|
|
251
|
+
try {
|
|
252
|
+
const chain = walkRealChain(dir, { allowDarwinRootLink: false, action: 'nothing was removed' });
|
|
253
|
+
if (!chain.missingDirs.length && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
|
|
254
|
+
} catch (_) {}
|
|
255
|
+
}
|
|
256
|
+
if (codexTarget && hasNonEmptyOverride(codexTarget.dir)) {
|
|
257
|
+
console.warn(`Warning: ${path.join(codexTarget.dir, 'AGENTS.override.md')} is non-empty and overrides ${codexTarget.full} in Codex; Codex ignores AGENTS.md in that directory while AGENTS.override.md has content.`);
|
|
258
|
+
}
|
|
148
259
|
if (targets.includes('hermes') && process.env.HERMES_HOME) {
|
|
149
260
|
let hermesHome = path.resolve(process.env.HERMES_HOME);
|
|
150
261
|
try { hermesHome = fs.realpathSync(hermesHome); } catch (_) {}
|
|
@@ -156,7 +267,7 @@ async function execute({ args, commitPlan, probe, readConfig, ask }) {
|
|
|
156
267
|
|
|
157
268
|
async function uninstall({ root, cfg, dry, commitPlan, probe }) {
|
|
158
269
|
validateInventory(cfg);
|
|
159
|
-
const writes = [], removals = [], retained = [];
|
|
270
|
+
const writes = [], removals = [], external = [], retained = [], externalDirs = [];
|
|
160
271
|
const read = rel => {
|
|
161
272
|
const found = probe(root, rel);
|
|
162
273
|
if (!found.exists) return null;
|
|
@@ -164,19 +275,26 @@ async function uninstall({ root, cfg, dry, commitPlan, probe }) {
|
|
|
164
275
|
return fs.readFileSync(found.full);
|
|
165
276
|
};
|
|
166
277
|
for (const [key, owned] of Object.entries(cfg.globalFiles || {})) {
|
|
278
|
+
if (owned.path) {
|
|
279
|
+
const bytes = readExternalFile(owned.path, owned.path, 'nothing was removed');
|
|
280
|
+
for (const d of owned.createdDirs || []) externalDirs.push(d);
|
|
281
|
+
if (!bytes) continue;
|
|
282
|
+
const text = decode(bytes, owned.path), ms = renderer.markerState(text, owned.path);
|
|
283
|
+
const currentHash = blockHash(text, owned.path);
|
|
284
|
+
if (ms.kind === 'none') continue;
|
|
285
|
+
if (currentHash !== owned.blockHash) { retained.push(owned.path); continue; }
|
|
286
|
+
const output = stripOwnedBlock(text, ms, owned);
|
|
287
|
+
if (owned.created && output === '') external.push({ base: path.dirname(owned.path), missingDirs: [], file: path.basename(owned.path), remove: true, display: owned.path });
|
|
288
|
+
else external.push({ base: path.dirname(owned.path), missingDirs: [], file: path.basename(owned.path), bytes: Buffer.from(output), display: owned.path });
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
167
291
|
const rel = TARGETS[key], bytes = read(rel);
|
|
168
292
|
if (!bytes) continue;
|
|
169
293
|
const text = decode(bytes, rel), ms = renderer.markerState(text, rel);
|
|
170
294
|
const currentHash = blockHash(text, rel);
|
|
171
295
|
if (ms.kind === 'none') continue;
|
|
172
296
|
if (currentHash !== owned.blockHash) { retained.push(rel); continue; }
|
|
173
|
-
|
|
174
|
-
if (after.startsWith('\r\n')) after = after.slice(2);
|
|
175
|
-
else if (after.startsWith('\n')) after = after.slice(1);
|
|
176
|
-
if (owned.appended) {
|
|
177
|
-
if (owned.separator && before.endsWith(owned.separator)) before = before.slice(0, -owned.separator.length);
|
|
178
|
-
}
|
|
179
|
-
const output = before + after;
|
|
297
|
+
const output = stripOwnedBlock(text, ms, owned);
|
|
180
298
|
if (owned.created && output === '') removals.push({ rel });
|
|
181
299
|
else writes.push({ rel, bytes: Buffer.from(output) });
|
|
182
300
|
}
|
|
@@ -191,14 +309,22 @@ async function uninstall({ root, cfg, dry, commitPlan, probe }) {
|
|
|
191
309
|
const found = probe(root, rel);
|
|
192
310
|
if (found.exists && !fs.lstatSync(found.full).isDirectory()) refuse(`${rel} is not a directory`);
|
|
193
311
|
}
|
|
312
|
+
for (const dir of externalDirs) {
|
|
313
|
+
walkRealChain(dir, { allowDarwinRootLink: false, action: 'nothing was removed' });
|
|
314
|
+
}
|
|
194
315
|
if (!retained.length) removals.push({ rel: CONFIG });
|
|
195
316
|
for (const rel of retained) console.log(`kept ${rel} (edited)`);
|
|
196
317
|
if (dry) {
|
|
197
318
|
for (const p of [...writes, ...removals]) console.log(`would ${p.bytes ? 'update' : 'remove'} ${p.rel}`);
|
|
319
|
+
for (const ext of external) console.log(`would ${ext.remove ? 'remove' : 'update'} ${ext.display}`);
|
|
198
320
|
return;
|
|
199
321
|
}
|
|
200
322
|
const outputPaths = new Set([...writes, ...removals].map(p => p.rel));
|
|
201
|
-
await commitPlan(root, { writes, removals, outputPaths });
|
|
323
|
+
await commitPlan(root, { writes, removals, external, outputPaths });
|
|
324
|
+
for (const dir of externalDirs.sort((a, b) => b.length - a.length)) {
|
|
325
|
+
const chain = walkRealChain(dir, { allowDarwinRootLink: false, action: 'nothing was removed' });
|
|
326
|
+
if (!chain.missingDirs.length && fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
|
|
327
|
+
}
|
|
202
328
|
for (const rel of directories.sort((a, b) => b.split('/').length - a.split('/').length)) {
|
|
203
329
|
const found = probe(root, rel);
|
|
204
330
|
if (found.exists && fs.readdirSync(found.full).length === 0) fs.rmdirSync(found.full);
|
package/bin/home.cjs
CHANGED
|
@@ -1,15 +1,80 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
2
3
|
const path = require('path');
|
|
3
4
|
const { Refusal } = require('../render/render.cjs');
|
|
4
5
|
|
|
6
|
+
function rootedAbsolute(dir) {
|
|
7
|
+
// On Windows a root-relative path such as \foo is "absolute" but lands on the current drive; require a drive or UNC root.
|
|
8
|
+
const rooted = path.sep !== '\\' || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/?.]+[\\/][^\\/]+)/.test(dir || '');
|
|
9
|
+
return typeof dir === 'string' && dir.length > 0 && path.isAbsolute(dir) && rooted;
|
|
10
|
+
}
|
|
11
|
+
|
|
5
12
|
function resolveHome(home = process.env.HOME) {
|
|
6
13
|
if (process.platform === 'win32' && (home === undefined || home === '')) home = process.env.USERPROFILE;
|
|
7
|
-
|
|
8
|
-
const rooted = path.sep !== '\\' || /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/?.]+[\\/][^\\/]+)/.test(home || '');
|
|
9
|
-
if (typeof home !== 'string' || !home || !path.isAbsolute(home) || !rooted) {
|
|
14
|
+
if (!rootedAbsolute(home)) {
|
|
10
15
|
throw new Refusal('HOME (or USERPROFILE on Windows) must be set to a non-empty absolute path; nothing was written');
|
|
11
16
|
}
|
|
12
17
|
return home;
|
|
13
18
|
}
|
|
14
19
|
|
|
15
|
-
|
|
20
|
+
function resolveCodexHome(home = resolveHome(), codexHome = process.env.CODEX_HOME) {
|
|
21
|
+
const resolvedHome = resolveHome(home);
|
|
22
|
+
if (codexHome === undefined || codexHome === '') return path.join(resolvedHome, '.codex');
|
|
23
|
+
if (!rootedAbsolute(codexHome)) {
|
|
24
|
+
throw new Refusal('CODEX_HOME must be set to a non-empty absolute path; nothing was written');
|
|
25
|
+
}
|
|
26
|
+
return path.resolve(codexHome);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Walk every path component from the filesystem root without following symlinks.
|
|
30
|
+
// On macOS, top-level /tmp, /var and /etc are system symlinks to /private/*; allowDarwinRootLink
|
|
31
|
+
// resolves only that depth-0 OS link on user-supplied paths, never on stored canonical paths.
|
|
32
|
+
function walkRealChain(absPath, { allowDarwinRootLink = false, action = 'nothing was written' } = {}) {
|
|
33
|
+
const normalized = path.resolve(absPath);
|
|
34
|
+
const { root } = path.parse(normalized);
|
|
35
|
+
const rest = normalized.slice(root.length);
|
|
36
|
+
const parts = rest ? rest.split(path.sep).filter(Boolean) : [];
|
|
37
|
+
let cur = root;
|
|
38
|
+
const missingDirs = [];
|
|
39
|
+
for (let i = 0; i < parts.length; i++) {
|
|
40
|
+
if (missingDirs.length) {
|
|
41
|
+
missingDirs.push(parts[i]);
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
const next = path.join(cur, parts[i]);
|
|
45
|
+
let st;
|
|
46
|
+
try { st = fs.lstatSync(next); }
|
|
47
|
+
catch (e) {
|
|
48
|
+
if (e.code === 'ENOENT') {
|
|
49
|
+
missingDirs.push(parts[i]);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
throw e;
|
|
53
|
+
}
|
|
54
|
+
if (st.isSymbolicLink()) {
|
|
55
|
+
if (allowDarwinRootLink && process.platform === 'darwin' && i === 0 && (next === '/tmp' || next === '/var' || next === '/etc')) {
|
|
56
|
+
cur = fs.realpathSync(next);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
throw new Refusal(`${next} is a symlink; ${action}`);
|
|
60
|
+
}
|
|
61
|
+
if (!st.isDirectory()) {
|
|
62
|
+
throw new Refusal(`${next} is not a directory; ${action}`);
|
|
63
|
+
}
|
|
64
|
+
cur = next;
|
|
65
|
+
}
|
|
66
|
+
return { base: cur, missingDirs, dir: path.join(cur, ...missingDirs) };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function hasNonEmptyOverride(dir) {
|
|
70
|
+
const file = path.join(dir, 'AGENTS.override.md');
|
|
71
|
+
try {
|
|
72
|
+
const stat = fs.statSync(file);
|
|
73
|
+
if (!stat.isFile() || stat.size === 0) return false;
|
|
74
|
+
return fs.readFileSync(file, 'utf8').replace(/^\ufeff/, '').trim().length > 0;
|
|
75
|
+
} catch (_) {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { rootedAbsolute, resolveHome, resolveCodexHome, walkRealChain, hasNonEmptyOverride };
|
package/bin/install-plan.cjs
CHANGED
|
@@ -22,16 +22,20 @@ function validateInventory(cfg) {
|
|
|
22
22
|
if ('createdDirectories' in cfg && (!Array.isArray(cfg.createdDirectories) || cfg.createdDirectories.some(rel => !validPath(rel)) || new Set(cfg.createdDirectories).size !== cfg.createdDirectories.length)) throw new Error('"createdDirectories" must be a unique list of relative paths');
|
|
23
23
|
if ('toolingVersions' in cfg && (!cfg.toolingVersions || typeof cfg.toolingVersions !== 'object' || Array.isArray(cfg.toolingVersions))) throw new Error('"toolingVersions" must be an object');
|
|
24
24
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
let cachedKnownFiles = null;
|
|
26
|
+
function knownVersions(rel, bytes, precomputedHash) {
|
|
27
|
+
cachedKnownFiles ||= require('./known-hashes.json').files;
|
|
28
|
+
const hashes = cachedKnownFiles[rel] || {};
|
|
29
|
+
const hash = precomputedHash || sha256(bytes);
|
|
28
30
|
return Object.entries(hashes).filter(([, variants]) => Object.values(variants).includes(hash)).map(([version]) => version.slice(1));
|
|
29
31
|
}
|
|
30
32
|
function ownership(cfg, rel, bytes, { legacy = false, expected } = {}) {
|
|
31
33
|
const recorded = recordedHash(cfg, rel);
|
|
32
|
-
const
|
|
33
|
-
const
|
|
34
|
-
|
|
34
|
+
const hash = sha256(bytes);
|
|
35
|
+
const savedVersion = (cfg.toolingVersions || {})[rel] || cfg.toolingVersion;
|
|
36
|
+
const versions = (recorded === undefined ? legacy : !savedVersion) ? knownVersions(rel, bytes, hash) : [];
|
|
37
|
+
const version = savedVersion || versions.at(-1);
|
|
38
|
+
return { unedited: recorded !== undefined ? hash === recorded : legacy && (versions.length > 0 || (expected && bytes.equals(expected))), version, hash };
|
|
35
39
|
}
|
|
36
40
|
|
|
37
41
|
// Match one semantic pointer slot at a time, then compare the whole original line.
|
package/bin/learn.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Consent separates project inspection from access to the AI apps' private history.
|
|
3
3
|
const fs = require('fs');
|
|
4
4
|
const path = require('path');
|
|
5
|
-
const { resolveHome } = require('./home.cjs');
|
|
5
|
+
const { resolveHome, resolveCodexHome } = require('./home.cjs');
|
|
6
6
|
const { sha256 } = require('./cli-util.cjs');
|
|
7
7
|
const crypto = require('crypto');
|
|
8
8
|
const readline = require('readline');
|
|
@@ -28,8 +28,8 @@ that Claude Code, Codex and Gemini CLI still keep, to find corrections you repea
|
|
|
28
28
|
· Other people's details in there? Add their names to your private list first.
|
|
29
29
|
· Delete it any time: npx agent-personalizer learn --forget
|
|
30
30
|
(your AI app's own history stays as it is)
|
|
31
|
-
· Codex
|
|
32
|
-
They
|
|
31
|
+
· Local Codex memory notes from your Codex home are included when you choose Codex.
|
|
32
|
+
They span sessions on this machine (or connected host), not just this folder.
|
|
33
33
|
· When your AI reads the file, its provider sees these messages again.
|
|
34
34
|
· Work or client accounts: check your agreement before reusing their sessions.
|
|
35
35
|
· Not affiliated with Anthropic, OpenAI or Google. Their formats can change.
|
|
@@ -163,7 +163,8 @@ async function learn({ dir = '.', yes = false, consented = false, allProjects =
|
|
|
163
163
|
const entries = renderer.readLearned(root);
|
|
164
164
|
const sources = [...new Set((cfg.targets || []).map(target => SOURCE[target]).filter(Boolean))];
|
|
165
165
|
const home = resolveHome();
|
|
166
|
-
const
|
|
166
|
+
const codexHome = sources.includes('codex') ? resolveCodexHome(home) : path.join(home, '.codex');
|
|
167
|
+
const data = await require('./sessions.cjs').readSessions({ home, codexHome, projectDir: root, allProjects, sources, limit: 20, privateTerms: terms });
|
|
167
168
|
const now = new Date().toISOString();
|
|
168
169
|
const text = digestText(data, entries, { sources, home, terms, now });
|
|
169
170
|
const folder = probe(root, FOLDER, 'dir');
|
package/bin/sessions.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const fs = require('node:fs');
|
|
4
4
|
const path = require('node:path');
|
|
5
|
-
const { resolveHome } = require('./home.cjs');
|
|
5
|
+
const { resolveHome, resolveCodexHome, walkRealChain } = require('./home.cjs');
|
|
6
6
|
const crypto = require('node:crypto');
|
|
7
7
|
|
|
8
8
|
const MAX_LINE = 8 * 1024 * 1024;
|
|
@@ -45,12 +45,24 @@ const SECRETS = [
|
|
|
45
45
|
const secretMatch = text => SECRETS.some(pattern => pattern.test(String(text).replace(CTRL, '')));
|
|
46
46
|
const fold = (text) => String(text).replace(CTRL, '').normalize('NFC').toLowerCase();
|
|
47
47
|
const compact = (text) => fold(text).replace(/\s+/g, '');
|
|
48
|
-
function
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
48
|
+
function compilePrivateTerms(privateTerms) {
|
|
49
|
+
if (!Array.isArray(privateTerms) || !privateTerms.length) return [];
|
|
50
|
+
const out = [];
|
|
51
|
+
for (const raw of privateTerms) {
|
|
52
|
+
if (typeof raw !== 'string') continue;
|
|
52
53
|
const term = fold(raw).trim();
|
|
53
54
|
const tight = compact(raw);
|
|
55
|
+
if (term || tight) out.push({ term, tight });
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function privateMatch(text, terms) {
|
|
61
|
+
if (!terms.length) return false;
|
|
62
|
+
const lower = fold(text);
|
|
63
|
+
const collapsed = lower.replace(/\s+/g, '');
|
|
64
|
+
return terms.some(entry => {
|
|
65
|
+
const { term, tight } = typeof entry === 'string' ? { term: fold(entry).trim(), tight: compact(entry) } : entry;
|
|
54
66
|
return (term && lower.includes(term)) || (tight && collapsed.includes(tight));
|
|
55
67
|
});
|
|
56
68
|
}
|
|
@@ -221,8 +233,19 @@ async function discover(home, sources, state) {
|
|
|
221
233
|
}
|
|
222
234
|
}
|
|
223
235
|
if (sources.has('codex')) {
|
|
224
|
-
|
|
225
|
-
|
|
236
|
+
let app = state.codexHome || path.join(home, '.codex');
|
|
237
|
+
let chainOk = true;
|
|
238
|
+
if (app !== path.join(home, '.codex')) {
|
|
239
|
+
try {
|
|
240
|
+
const chain = walkRealChain(app, { allowDarwinRootLink: true, action: 'skipped' });
|
|
241
|
+
if (chain.missingDirs.length) chainOk = false;
|
|
242
|
+
else app = chain.dir;
|
|
243
|
+
} catch (err) {
|
|
244
|
+
bump(state, /is a symlink/.test(err.message) ? 'symlink' : 'non_regular');
|
|
245
|
+
chainOk = false;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (chainOk && await statPath(app, 'directory', state)) {
|
|
226
249
|
async function walk(dir) {
|
|
227
250
|
for (const name of await children(dir, state)) {
|
|
228
251
|
const file = path.join(dir, name);
|
|
@@ -269,10 +292,26 @@ async function discover(home, sources, state) {
|
|
|
269
292
|
}
|
|
270
293
|
|
|
271
294
|
async function safeOpen(file, state) {
|
|
272
|
-
// Recheck each path within HOME immediately before opening to catch replaced links.
|
|
273
|
-
|
|
274
|
-
if (
|
|
275
|
-
|
|
295
|
+
// Recheck each path within HOME (or active CODEX_HOME) immediately before opening to catch replaced links.
|
|
296
|
+
let codexRoot = null;
|
|
297
|
+
if (state.codexHome && state.codexHome !== path.join(state.home, '.codex')) {
|
|
298
|
+
try {
|
|
299
|
+
const chain = walkRealChain(state.codexHome, { allowDarwinRootLink: true, action: 'skipped' });
|
|
300
|
+
if (!chain.missingDirs.length) codexRoot = chain.dir;
|
|
301
|
+
} catch { return null; }
|
|
302
|
+
}
|
|
303
|
+
const roots = codexRoot ? [codexRoot, state.home] : [state.home];
|
|
304
|
+
let baseRoot = null, relative = null;
|
|
305
|
+
for (const candidateRoot of roots) {
|
|
306
|
+
const rel = path.relative(candidateRoot, file);
|
|
307
|
+
if (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel)) {
|
|
308
|
+
baseRoot = candidateRoot;
|
|
309
|
+
relative = rel;
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (!baseRoot) return null;
|
|
314
|
+
let current = baseRoot;
|
|
276
315
|
if (!await statPath(current, 'directory', state)) return null;
|
|
277
316
|
const parts = relative.split(path.sep);
|
|
278
317
|
for (const name of parts.slice(0, -1)) {
|
|
@@ -602,15 +641,19 @@ async function readMemory(file, state) {
|
|
|
602
641
|
return { file: file.file, text, date: new Date(file.mtimeMs).toISOString() };
|
|
603
642
|
}
|
|
604
643
|
|
|
605
|
-
async function readSessions({ home
|
|
644
|
+
async function readSessions({ home, codexHome, projectDir = process.cwd(), allProjects = false, sources = [], limit = 20, privateTerms = [] } = {}) {
|
|
606
645
|
const selectedSources = new Set(Array.isArray(sources) ? sources.filter(source => SOURCES.has(source)) : []);
|
|
607
646
|
const maximum = Number.isInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 20;
|
|
608
647
|
projectDir = path.resolve(projectDir);
|
|
648
|
+
const resolvedHome = path.resolve(resolveHome(home));
|
|
649
|
+
const resolvedCodexHome = codexHome !== undefined
|
|
650
|
+
? path.resolve(resolveCodexHome(resolvedHome, codexHome))
|
|
651
|
+
: (home === undefined ? path.resolve(resolveCodexHome(resolvedHome)) : path.join(resolvedHome, '.codex'));
|
|
609
652
|
const state = {
|
|
610
|
-
home:
|
|
653
|
+
home: resolvedHome, codexHome: resolvedCodexHome, projectDir, allProjects,
|
|
611
654
|
geminiProjectHash: crypto.createHash('sha256').update(projectDir).digest('hex'),
|
|
612
655
|
candidates: [], memoryFiles: [], filesRead: [], filesChecked: 0, skipped: {},
|
|
613
|
-
privateTerms:
|
|
656
|
+
privateTerms: compilePrivateTerms(privateTerms)
|
|
614
657
|
};
|
|
615
658
|
await discover(state.home, selectedSources, state);
|
|
616
659
|
state.candidates.sort((a, b) => b.mtimeMs - a.mtimeMs || a.file.localeCompare(b.file));
|