@mainwave/cli 0.13.0 → 0.14.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.
- package/README.md +70 -2
- package/dist/adapters/claude-code.js +4 -21
- package/dist/adapters/codex-cli.js +375 -53
- package/dist/adapters/index.js +4 -2
- package/dist/commands.js +11 -2
- package/dist/core/apply.js +82 -15
- package/dist/core/codecs/toml-profile.js +245 -0
- package/dist/core/codex-trust.js +30 -6
- package/dist/core/detect.js +20 -1
- package/dist/core/doctor.js +69 -25
- package/dist/core/entry-script.js +24 -10
- package/dist/core/install-hooks.js +1 -1
- package/dist/core/markers.js +25 -20
- package/dist/core/pinned-use-case.js +2 -2
- package/dist/core/prompts.js +15 -0
- package/dist/core/status.js +15 -7
- package/dist/core/wizard.js +63 -2
- package/dist/main.js +34 -2
- package/hooks/codex-turns.mjs +13 -3
- package/hooks/git-commit-marker.mjs +8 -1
- package/hooks/github-pr-marker.mjs +8 -1
- package/hooks/glab-mr-marker.mjs +8 -1
- package/hooks/jira-ticket-marker.mjs +8 -1
- package/hooks/linear-ticket-marker.mjs +8 -1
- package/hooks/marker-core.mjs +122 -23
- package/hooks/plan-snapshot.mjs +1 -0
- package/package.json +11 -8
package/dist/core/apply.js
CHANGED
|
@@ -5,10 +5,11 @@ import { countTrust, readCodexTrust } from './codex-trust.js';
|
|
|
5
5
|
import { activeHierarchy, effectiveEnv } from './effective-settings.js';
|
|
6
6
|
import { color, renderDiff } from './format.js';
|
|
7
7
|
import { claudeHookShellMissing, GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
|
|
8
|
-
import { activeManagedScans, BOOTSTRAP_KEY, commandGeneration, copyHookScripts, DEFAULT_MARKER_TOOL, deliveryKey, describeMarkersPlan, hooksBlocked, hostRunsBootstrap, installedHooksDir, isPlanSnapshot, isPlanSnapshotRoute, legacyCommandSends, managedDeliversEntry, managedDeliversPlanSnapshot, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, planMarkers, prepareMarkersFile, readPackagedMatchers, routeLabel, scanForMarkers, scanRoutes, selectHookMatchers, syncManagedHooks, syncOrgDelivered, userHookGroups, writeOptOutFlags, } from './markers.js';
|
|
8
|
+
import { activeManagedScans, BOOTSTRAP_KEY, codexRefreshCommand, commandGeneration, copyHookScripts, DEFAULT_MARKER_TOOL, deliveryKey, describeMarkersPlan, hooksBlocked, hostRunsBootstrap, installedHooksDir, isPlanSnapshot, isPlanSnapshotRoute, legacyCommandSends, managedDeliversEntry, managedDeliversPlanSnapshot, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, planMarkers, prepareMarkersFile, readPackagedMatchers, routeLabel, scanForMarkers, scanRoutes, selectHookMatchers, syncManagedHooks, syncOrgDelivered, userHookGroups, writeOptOutFlags, } from './markers.js';
|
|
9
|
+
import { hasCredentialShape } from './headers.js';
|
|
9
10
|
import { isManagedLayer } from './layer-policy.js';
|
|
10
|
-
import { adapterEffective } from './status.js';
|
|
11
|
-
import { applyUpdate, prepareUpdate, readExistingEnv } from './settings.js';
|
|
11
|
+
import { adapterEffective, statusSetups } from './status.js';
|
|
12
|
+
import { applyUpdate, isSamePath, prepareUpdate, readExistingEnv } from './settings.js';
|
|
12
13
|
import { say } from './ui.js';
|
|
13
14
|
import { VERSION } from './version.js';
|
|
14
15
|
const hasAnyChange = (diff) => diff.added.length > 0 || diff.changed.length > 0 || diff.removed.length > 0;
|
|
@@ -16,7 +17,7 @@ export const teamUcidStanding = async (adapter, ucid, stored) => {
|
|
|
16
17
|
if (stored?.id === ucid)
|
|
17
18
|
return stored.pinned ? 'pinned' : 'stored';
|
|
18
19
|
const others = Object.values(adapters).filter((a) => a.name !== adapter.name);
|
|
19
|
-
const carried = await Promise.all(others.map(async (
|
|
20
|
+
const carried = await Promise.all(others.flatMap(statusSetups).map(async (s) => (await adapterEffective(s.adapter)).ucid));
|
|
20
21
|
return carried.includes(ucid) ? 'shared' : 'own';
|
|
21
22
|
};
|
|
22
23
|
const writeTargets = (adapter) => ({
|
|
@@ -140,9 +141,11 @@ export const planAdapter = async (adapter, answers, context = {}) => {
|
|
|
140
141
|
const delivered = managedMarkerDeliveries(managedScans);
|
|
141
142
|
orgDeliversEntry = managedDeliversEntry(managedScans);
|
|
142
143
|
planSnapshotOrgDelivered = planSnapshotOn !== null && managedDeliversPlanSnapshot(managedScans);
|
|
143
|
-
const groups = hookShellMissing
|
|
144
|
+
const groups = hookShellMissing
|
|
145
|
+
? []
|
|
146
|
+
: userHookGroups(hosted, on, delivered, hookHost, adapter.markers?.hookArgs);
|
|
144
147
|
const hooksFile = adapter.markers?.hooksFile;
|
|
145
|
-
if (hooksFile) {
|
|
148
|
+
if (hooksFile && !isSamePath(hooksFile.path, primary)) {
|
|
146
149
|
const prepared = await prepareMarkersFile(hooksFile.path, hooksFile.codec, groups);
|
|
147
150
|
markersPlan = prepared.plan;
|
|
148
151
|
separateMarkersUpdate = prepared.update;
|
|
@@ -168,7 +171,9 @@ export const planAdapter = async (adapter, answers, context = {}) => {
|
|
|
168
171
|
codec: aw.codec,
|
|
169
172
|
mode: aw.mode,
|
|
170
173
|
})));
|
|
174
|
+
const replaced = (await Promise.all((adapter.replaces ?? []).map((r) => planReplaced(r)))).flat();
|
|
171
175
|
const labeled = [
|
|
176
|
+
...replaced.map(({ update }) => ({ label: update.path, update })),
|
|
172
177
|
{ label: primary, update: primaryUpdate },
|
|
173
178
|
...(separateMarkersUpdate
|
|
174
179
|
? [{ label: separateMarkersUpdate.path, update: separateMarkersUpdate }]
|
|
@@ -179,7 +184,9 @@ export const planAdapter = async (adapter, answers, context = {}) => {
|
|
|
179
184
|
})),
|
|
180
185
|
];
|
|
181
186
|
const markersChanged = markersPlan?.changed ?? false;
|
|
182
|
-
const changed = labeled.filter(({ update }) => hasAnyChange(update.diff) ||
|
|
187
|
+
const changed = labeled.filter(({ update }) => hasAnyChange(update.diff) ||
|
|
188
|
+
(update === markersCarrier && markersChanged) ||
|
|
189
|
+
replaced.some((r) => r.update === update && r.markersPlan?.changed === true));
|
|
183
190
|
return {
|
|
184
191
|
adapter,
|
|
185
192
|
primaryPath: primary,
|
|
@@ -190,6 +197,8 @@ export const planAdapter = async (adapter, answers, context = {}) => {
|
|
|
190
197
|
planSnapshotOrgDelivered,
|
|
191
198
|
markersPlan,
|
|
192
199
|
markersCarrier,
|
|
200
|
+
replaced: replaced.filter((r) => changed.some((c) => c.update === r.update)),
|
|
201
|
+
replacedHooksFiles: (adapter.replaces ?? []).flatMap((r) => r.markers?.hooksFile ? [r.markers.hooksFile.path] : []),
|
|
193
202
|
hookHost,
|
|
194
203
|
stageHooks,
|
|
195
204
|
hookEvents,
|
|
@@ -200,6 +209,31 @@ export const planAdapter = async (adapter, answers, context = {}) => {
|
|
|
200
209
|
...(keptPin ? { keptPin: pin } : {}),
|
|
201
210
|
};
|
|
202
211
|
};
|
|
212
|
+
const planReplaced = async (replaced) => {
|
|
213
|
+
const path = replaced.paths.global;
|
|
214
|
+
const env = await readExistingEnv(path, replaced.codec);
|
|
215
|
+
const owns = env !== null && (replaced.holdsOwnSetup?.(env) ?? true);
|
|
216
|
+
const config = await prepareUpdate({
|
|
217
|
+
path,
|
|
218
|
+
newEnv: {},
|
|
219
|
+
managedKeys: owns ? [...replaced.managedEnvKeys, ...(replaced.retiredEnvKeys ?? [])] : [],
|
|
220
|
+
codec: replaced.codec,
|
|
221
|
+
});
|
|
222
|
+
const hooksFile = replaced.markers?.hooksFile;
|
|
223
|
+
if (hooksFile === undefined)
|
|
224
|
+
return [{ update: config, markersPlan: null }];
|
|
225
|
+
if (isSamePath(hooksFile.path, path)) {
|
|
226
|
+
const markersPlan = config.exists ? planMarkers(config.next, []) : null;
|
|
227
|
+
if (markersPlan !== null)
|
|
228
|
+
config.next = markersPlan.next;
|
|
229
|
+
return [{ update: config, markersPlan }];
|
|
230
|
+
}
|
|
231
|
+
const hooks = await prepareMarkersFile(hooksFile.path, hooksFile.codec, []);
|
|
232
|
+
return [
|
|
233
|
+
{ update: config, markersPlan: null },
|
|
234
|
+
{ update: hooks.update, markersPlan: hooks.plan },
|
|
235
|
+
];
|
|
236
|
+
};
|
|
203
237
|
export const hookShellMissingFor = async (adapter, settingsEnv) => {
|
|
204
238
|
if (process.platform !== 'win32')
|
|
205
239
|
return false;
|
|
@@ -251,8 +285,11 @@ export const renderPlan = (plan) => {
|
|
|
251
285
|
const body = renderDiff(update.diff);
|
|
252
286
|
if (body)
|
|
253
287
|
say(body);
|
|
254
|
-
|
|
255
|
-
|
|
288
|
+
const markersPlan = update === plan.markersCarrier
|
|
289
|
+
? plan.markersPlan
|
|
290
|
+
: plan.replaced.find((r) => r.update === update)?.markersPlan;
|
|
291
|
+
if (markersPlan?.changed) {
|
|
292
|
+
for (const line of describeMarkersPlan(markersPlan)) {
|
|
256
293
|
const painted = line.startsWith('+')
|
|
257
294
|
? color.green(line)
|
|
258
295
|
: line.startsWith('-')
|
|
@@ -289,8 +326,18 @@ export const writePlan = async (plan, dirs = defaultHookDirs(), holdFlat = false
|
|
|
289
326
|
say('');
|
|
290
327
|
say(color.dim(`Hook scripts refreshed in ${dest}.`));
|
|
291
328
|
}
|
|
329
|
+
const done = [];
|
|
292
330
|
for (const { update } of plan.changed) {
|
|
293
|
-
|
|
331
|
+
let result;
|
|
332
|
+
try {
|
|
333
|
+
result = await applyUpdate(update);
|
|
334
|
+
}
|
|
335
|
+
catch (err) {
|
|
336
|
+
if (done.length > 0)
|
|
337
|
+
say(color.yellow(partialWriteNote(plan.adapter, done)));
|
|
338
|
+
throw err;
|
|
339
|
+
}
|
|
340
|
+
done.push({ update, result });
|
|
294
341
|
say('');
|
|
295
342
|
say(color.green(`✓ Wrote ${result.written}`));
|
|
296
343
|
if (result.backupPath) {
|
|
@@ -298,6 +345,26 @@ export const writePlan = async (plan, dirs = defaultHookDirs(), holdFlat = false
|
|
|
298
345
|
}
|
|
299
346
|
}
|
|
300
347
|
};
|
|
348
|
+
const setupCommand = (adapter) => ['mainwave-cli setup', adapter.name, ...(adapter.setupArgs ?? [])].join(' ');
|
|
349
|
+
const partialWriteNote = (adapter, done) => {
|
|
350
|
+
const lines = [
|
|
351
|
+
'',
|
|
352
|
+
'! Setup stopped before it finished. It had already changed these files:',
|
|
353
|
+
...done.map(({ result }) => result.backupPath
|
|
354
|
+
? ` ${result.written}, backup at ${result.backupPath}`
|
|
355
|
+
: ` ${result.written}, a new file`),
|
|
356
|
+
];
|
|
357
|
+
const keyHolder = done.find(({ update, result }) => result.backupPath !== null &&
|
|
358
|
+
update.diff.removed.some(({ key, before }) => hasCredentialShape(`${key} ${before}`)));
|
|
359
|
+
if (keyHolder !== undefined) {
|
|
360
|
+
const { written } = keyHolder.result;
|
|
361
|
+
const command = setupCommand(adapter);
|
|
362
|
+
lines.push(` This run removed your Mainwave API key from ${written}. Its backup still holds the key.`, ` To recover, copy that backup back to ${written}, or run \`${command} --api-key <your key>\` again. ` +
|
|
363
|
+
`If you are signed in (\`mainwave-cli login\`), running \`${command}\` again is enough, since setup ` +
|
|
364
|
+
"then uses this machine's saved key or makes a new one.");
|
|
365
|
+
}
|
|
366
|
+
return lines.join('\n');
|
|
367
|
+
};
|
|
301
368
|
export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn = true) => {
|
|
302
369
|
const scans = await scanForMarkers(await activeHierarchy(adapter));
|
|
303
370
|
const activeManaged = new Set(activeManagedScans(scans));
|
|
@@ -358,8 +425,8 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
|
|
|
358
425
|
}
|
|
359
426
|
}
|
|
360
427
|
};
|
|
361
|
-
const codexTrustNote = (reading, hooksPath) => {
|
|
362
|
-
const how =
|
|
428
|
+
const codexTrustNote = (reading, hooksPath, run = 'codex') => {
|
|
429
|
+
const how = `Start \`${run}\` and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each ` +
|
|
363
430
|
'Mainwave hook, the session-start hook included. Codex asks again whenever a Mainwave hook changes, such as ' +
|
|
364
431
|
'when a setup run adds a route or a release changes a command, so approve again after such a run; a run that ' +
|
|
365
432
|
"removes a Mainwave hook moves the hooks after it, so Codex may ask about other tools' hooks too. " +
|
|
@@ -396,7 +463,7 @@ export const printPostSetup = (plan) => {
|
|
|
396
463
|
if (plan.hookEvents.includes('SessionStart')) {
|
|
397
464
|
say('');
|
|
398
465
|
say(color.dim(plan.hookHost === 'codex'
|
|
399
|
-
? `${plan.adapter.displayName} also runs \`
|
|
466
|
+
? `${plan.adapter.displayName} also runs \`${codexRefreshCommand(plan.adapter.markers?.hookArgs)}\` in the background ` +
|
|
400
467
|
'when a session starts, resumes or forks: it refreshes the hook scripts from the latest release and adds hooks ' +
|
|
401
468
|
'a later release brings to the events above, never changing one you approved.'
|
|
402
469
|
: `${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks\` in the background when a session ` +
|
|
@@ -407,9 +474,9 @@ export const printPostSetup = (plan) => {
|
|
|
407
474
|
const hooksFile = plan.adapter.markers?.hooksFile;
|
|
408
475
|
const reading = hooksFile === undefined
|
|
409
476
|
? undefined
|
|
410
|
-
: readCodexTrust(hooksFile.path, plan.adapter.
|
|
477
|
+
: readCodexTrust(hooksFile.path, plan.adapter.trustFiles ?? [], hooksFile.path, hooksFile.codec);
|
|
411
478
|
say('');
|
|
412
|
-
say(color.dim(codexTrustNote(reading, hooksFile?.path)));
|
|
479
|
+
say(color.dim(codexTrustNote(reading, hooksFile?.path, plan.adapter.runInstruction)));
|
|
413
480
|
}
|
|
414
481
|
const snippet = plan.adapter.printPostSetupInstructions?.(plan.input);
|
|
415
482
|
if (snippet) {
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { tomlOtelCodec } from './toml-otel.js';
|
|
2
|
+
const RAW = Symbol('toml-profile:raw');
|
|
3
|
+
const CODEX_HOOK_EVENTS = new Set([
|
|
4
|
+
'PreModelRequest',
|
|
5
|
+
'PostModelRequest',
|
|
6
|
+
'PreToolUse',
|
|
7
|
+
'PermissionRequest',
|
|
8
|
+
'PostToolUse',
|
|
9
|
+
'PreCompact',
|
|
10
|
+
'PostCompact',
|
|
11
|
+
'SessionStart',
|
|
12
|
+
'SessionEnd',
|
|
13
|
+
'UserPromptSubmit',
|
|
14
|
+
'SubagentStart',
|
|
15
|
+
'SubagentStop',
|
|
16
|
+
'Stop',
|
|
17
|
+
'Interrupt',
|
|
18
|
+
]);
|
|
19
|
+
const HANDLER_KEY_ORDER = ['type', 'command', 'commandWindows', 'timeout', 'async', 'statusMessage'];
|
|
20
|
+
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
21
|
+
const keySegments = (raw) => {
|
|
22
|
+
const out = [];
|
|
23
|
+
let rest = raw.trim();
|
|
24
|
+
while (rest.length > 0) {
|
|
25
|
+
const m = /^(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*/.exec(rest);
|
|
26
|
+
if (m === null)
|
|
27
|
+
return undefined;
|
|
28
|
+
out.push(m[1] !== undefined ? unescapeBasic(m[1]) : (m[2] ?? m[3]));
|
|
29
|
+
rest = rest.slice(m[0].length);
|
|
30
|
+
if (rest.length === 0)
|
|
31
|
+
break;
|
|
32
|
+
if (!rest.startsWith('.'))
|
|
33
|
+
return undefined;
|
|
34
|
+
rest = rest.slice(1).trimStart();
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
};
|
|
38
|
+
const unescapeBasic = (s) => s.replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_m, c) => {
|
|
39
|
+
if (c[0] === 'u' || c[0] === 'U')
|
|
40
|
+
return String.fromCodePoint(parseInt(c.slice(1), 16));
|
|
41
|
+
return { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '"': '"', '\\': '\\' }[c] ?? c;
|
|
42
|
+
});
|
|
43
|
+
const escapeBasic = (s) => '"' +
|
|
44
|
+
s.replace(/[\\"\u0000-\u001f\u007f]/g, (c) => {
|
|
45
|
+
const named = {
|
|
46
|
+
'\\': '\\\\',
|
|
47
|
+
'"': '\\"',
|
|
48
|
+
'\n': '\\n',
|
|
49
|
+
'\t': '\\t',
|
|
50
|
+
'\r': '\\r',
|
|
51
|
+
};
|
|
52
|
+
return named[c] ?? `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`;
|
|
53
|
+
}) +
|
|
54
|
+
'"';
|
|
55
|
+
const header = (line) => {
|
|
56
|
+
const m = /^\s*(\[\[?)\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$/.exec(line);
|
|
57
|
+
if (m === null)
|
|
58
|
+
return undefined;
|
|
59
|
+
return { array: m[1] === '[[', key: keySegments(m[2]) };
|
|
60
|
+
};
|
|
61
|
+
const assignment = (line) => {
|
|
62
|
+
const eq = /^\s*((?:"(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.\s-])+?)\s*=\s*(.*)$/.exec(line);
|
|
63
|
+
if (eq === null)
|
|
64
|
+
return undefined;
|
|
65
|
+
const key = keySegments(eq[1]);
|
|
66
|
+
if (key === undefined)
|
|
67
|
+
return undefined;
|
|
68
|
+
const raw = eq[2];
|
|
69
|
+
const tail = (rest) => /^\s*(?:#.*)?$/.test(rest);
|
|
70
|
+
let m = /^"((?:[^"\\]|\\.)*)"(.*)$/.exec(raw);
|
|
71
|
+
if (m !== null && tail(m[2]))
|
|
72
|
+
return { key, value: unescapeBasic(m[1]) };
|
|
73
|
+
m = /^'([^']*)'(.*)$/.exec(raw);
|
|
74
|
+
if (m !== null && !raw.startsWith("'''") && tail(m[2]))
|
|
75
|
+
return { key, value: m[1] };
|
|
76
|
+
m = /^(true|false)(.*)$/.exec(raw);
|
|
77
|
+
if (m !== null && tail(m[2]))
|
|
78
|
+
return { key, value: m[1] === 'true' };
|
|
79
|
+
m = /^([+-]?\d+)(.*)$/.exec(raw);
|
|
80
|
+
if (m !== null && tail(m[2]))
|
|
81
|
+
return { key, value: Number(m[1]) };
|
|
82
|
+
return undefined;
|
|
83
|
+
};
|
|
84
|
+
const isEventKey = (key, length) => key !== undefined &&
|
|
85
|
+
key.length >= length &&
|
|
86
|
+
key[0] === 'hooks' &&
|
|
87
|
+
CODEX_HOOK_EVENTS.has(key[1] ?? '');
|
|
88
|
+
const splitHooks = (body, path) => {
|
|
89
|
+
const hooks = {};
|
|
90
|
+
const rest = [];
|
|
91
|
+
let group;
|
|
92
|
+
let handler;
|
|
93
|
+
let table = [];
|
|
94
|
+
const close = () => {
|
|
95
|
+
if (group === undefined)
|
|
96
|
+
return;
|
|
97
|
+
const lines = [...group.lines];
|
|
98
|
+
while (lines.length > 0 && lines[lines.length - 1].trim() === '')
|
|
99
|
+
lines.pop();
|
|
100
|
+
Object.defineProperty(group.value, RAW, { value: lines.join('\n') });
|
|
101
|
+
(hooks[group.event] ??= []).push(group.value);
|
|
102
|
+
group = undefined;
|
|
103
|
+
handler = undefined;
|
|
104
|
+
};
|
|
105
|
+
const lines = body.split('\n');
|
|
106
|
+
for (const [i, line] of lines.entries()) {
|
|
107
|
+
if (line.includes('"""') || line.includes("'''")) {
|
|
108
|
+
throw new Error(`${path}:${i + 1}: has """ or ''', which opens a multi-line string; setup does not edit a ` +
|
|
109
|
+
'profile file with one, even in a comment. Write that value on one line or move it out of ' +
|
|
110
|
+
'this file, then re-run');
|
|
111
|
+
}
|
|
112
|
+
const h = header(line);
|
|
113
|
+
if (h !== undefined) {
|
|
114
|
+
if (h.array && isEventKey(h.key, 2) && h.key.length === 2) {
|
|
115
|
+
close();
|
|
116
|
+
group = { event: h.key[1], value: { hooks: [] }, lines: [line] };
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const sameEvent = group !== undefined && isEventKey(h.key, 3) && h.key[1] === group.event;
|
|
120
|
+
if (sameEvent && h.array && h.key.length === 3 && h.key[2] === 'hooks') {
|
|
121
|
+
handler = {};
|
|
122
|
+
group.value.hooks.push(handler);
|
|
123
|
+
group.lines.push(line);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (sameEvent && h.key[2] === 'hooks') {
|
|
127
|
+
handler = undefined;
|
|
128
|
+
group.lines.push(line);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
close();
|
|
132
|
+
table = h.key ?? [];
|
|
133
|
+
rest.push(line);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (group !== undefined) {
|
|
137
|
+
group.lines.push(line);
|
|
138
|
+
const a = assignment(line);
|
|
139
|
+
if (a === undefined || a.key.length !== 1)
|
|
140
|
+
continue;
|
|
141
|
+
const name = a.key[0];
|
|
142
|
+
if (handler !== undefined)
|
|
143
|
+
handler[name] = a.value;
|
|
144
|
+
else if (group.value.hooks.length === 0 &&
|
|
145
|
+
name === 'matcher' &&
|
|
146
|
+
typeof a.value === 'string') {
|
|
147
|
+
group.value.matcher = a.value;
|
|
148
|
+
}
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const key = /^\s*[^#\s[]/.test(line) ? /^\s*([^=]+?)\s*=/.exec(line)?.[1] : undefined;
|
|
152
|
+
const full = key === undefined ? undefined : [...table, ...(keySegments(key) ?? [])];
|
|
153
|
+
if (full !== undefined &&
|
|
154
|
+
(full.join('.') === 'hooks' || (full[0] === 'hooks' && CODEX_HOOK_EVENTS.has(full[1] ?? '')))) {
|
|
155
|
+
throw new Error(`${path}:${i + 1}: holds Codex hooks in a form setup does not edit (${full.join('.')}); ` +
|
|
156
|
+
'write them as [[hooks.<Event>]] tables or remove them, then re-run setup');
|
|
157
|
+
}
|
|
158
|
+
rest.push(line);
|
|
159
|
+
}
|
|
160
|
+
close();
|
|
161
|
+
return { hooks, rest: rest.join('\n') };
|
|
162
|
+
};
|
|
163
|
+
const renderValue = (v) => (typeof v === 'string' ? escapeBasic(v) : String(v));
|
|
164
|
+
const renderKey = (k) => (/^[A-Za-z0-9_-]+$/.test(k) ? k : escapeBasic(k));
|
|
165
|
+
const renderGroup = (event, group) => {
|
|
166
|
+
const lines = [`[[hooks.${event}]]`];
|
|
167
|
+
for (const [k, v] of Object.entries(group)) {
|
|
168
|
+
if (k === 'hooks')
|
|
169
|
+
continue;
|
|
170
|
+
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
|
|
171
|
+
lines.push(`${renderKey(k)} = ${renderValue(v)}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const handlers = Array.isArray(group.hooks) ? group.hooks : [];
|
|
175
|
+
for (const h of handlers) {
|
|
176
|
+
if (!isRecord(h))
|
|
177
|
+
continue;
|
|
178
|
+
lines.push('', `[[hooks.${event}.hooks]]`);
|
|
179
|
+
const keys = [
|
|
180
|
+
...HANDLER_KEY_ORDER.filter((k) => k in h),
|
|
181
|
+
...Object.keys(h).filter((k) => !HANDLER_KEY_ORDER.includes(k)),
|
|
182
|
+
];
|
|
183
|
+
for (const k of keys) {
|
|
184
|
+
const v = h[k];
|
|
185
|
+
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
|
|
186
|
+
lines.push(`${renderKey(k)} = ${renderValue(v)}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return lines.join('\n');
|
|
191
|
+
};
|
|
192
|
+
const parse = (body, path) => {
|
|
193
|
+
let split;
|
|
194
|
+
try {
|
|
195
|
+
split = splitHooks(body, path);
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
throw new Error(`failed to parse ${path} as TOML: ${err.message}`);
|
|
199
|
+
}
|
|
200
|
+
const root = tomlOtelCodec.parse(split.rest, path);
|
|
201
|
+
if (Object.keys(split.hooks).length > 0)
|
|
202
|
+
root.hooks = split.hooks;
|
|
203
|
+
return root;
|
|
204
|
+
};
|
|
205
|
+
const withoutHooks = (doc) => {
|
|
206
|
+
if (!isRecord(doc))
|
|
207
|
+
throw new Error('expected a TOML table at the top level');
|
|
208
|
+
const { hooks: _hooks, ...rest } = doc;
|
|
209
|
+
return rest;
|
|
210
|
+
};
|
|
211
|
+
const serialize = (doc) => {
|
|
212
|
+
const rest = tomlOtelCodec.serialize(withoutHooks(doc));
|
|
213
|
+
const hooks = isRecord(doc) && isRecord(doc.hooks) ? doc.hooks : {};
|
|
214
|
+
const blocks = [];
|
|
215
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
216
|
+
if (!Array.isArray(groups))
|
|
217
|
+
continue;
|
|
218
|
+
for (const g of groups) {
|
|
219
|
+
if (!isRecord(g))
|
|
220
|
+
continue;
|
|
221
|
+
const raw = g[RAW];
|
|
222
|
+
blocks.push(raw ?? renderGroup(event, g));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const hooksText = blocks.length > 0 ? blocks.join('\n\n') + '\n' : '';
|
|
226
|
+
if (rest.trim() === '')
|
|
227
|
+
return hooksText;
|
|
228
|
+
if (hooksText === '')
|
|
229
|
+
return rest;
|
|
230
|
+
return rest.replace(/\s+$/, '') + '\n\n' + hooksText;
|
|
231
|
+
};
|
|
232
|
+
const applyEnv = (doc, newEnv, managedKeys) => {
|
|
233
|
+
const next = tomlOtelCodec.applyEnv(withoutHooks(doc), newEnv, managedKeys);
|
|
234
|
+
if (isRecord(doc) && doc.hooks !== undefined)
|
|
235
|
+
next.hooks = doc.hooks;
|
|
236
|
+
return next;
|
|
237
|
+
};
|
|
238
|
+
export const tomlProfileCodec = {
|
|
239
|
+
format: 'toml',
|
|
240
|
+
parse,
|
|
241
|
+
serialize,
|
|
242
|
+
empty: tomlOtelCodec.empty,
|
|
243
|
+
readEnv: (doc) => tomlOtelCodec.readEnv(withoutHooks(doc)),
|
|
244
|
+
applyEnv,
|
|
245
|
+
};
|
package/dist/core/codex-trust.js
CHANGED
|
@@ -116,24 +116,48 @@ const readText = (path) => {
|
|
|
116
116
|
}
|
|
117
117
|
};
|
|
118
118
|
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
119
|
-
export const
|
|
119
|
+
export const hookTrustKey = (sourceFile, event, group, handler) => `${sourceFile}:${eventLabel(event)}:${group}:${handler}`;
|
|
120
|
+
const mergedStates = (trustFiles) => {
|
|
121
|
+
const merged = new Map();
|
|
122
|
+
for (const file of trustFiles) {
|
|
123
|
+
const states = readHookStates(readText(file) ?? '');
|
|
124
|
+
if (states === undefined)
|
|
125
|
+
return { unreadable: file };
|
|
126
|
+
for (const [key, state] of states) {
|
|
127
|
+
const into = merged.get(key) ?? {};
|
|
128
|
+
if (state.trustedHash !== undefined)
|
|
129
|
+
into.trustedHash = state.trustedHash;
|
|
130
|
+
if (state.enabled !== undefined)
|
|
131
|
+
into.enabled = state.enabled;
|
|
132
|
+
merged.set(key, into);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { states: merged };
|
|
136
|
+
};
|
|
137
|
+
export const readCodexTrust = (hooksPath, trustFiles, keySource = hooksPath, codec) => {
|
|
120
138
|
const body = readText(hooksPath);
|
|
121
139
|
let doc;
|
|
122
140
|
try {
|
|
123
|
-
doc =
|
|
141
|
+
doc =
|
|
142
|
+
body === undefined
|
|
143
|
+
? undefined
|
|
144
|
+
: codec === undefined
|
|
145
|
+
? JSON.parse(body)
|
|
146
|
+
: codec.parse(body, hooksPath);
|
|
124
147
|
}
|
|
125
148
|
catch {
|
|
126
149
|
return { state: 'no-hooks' };
|
|
127
150
|
}
|
|
128
151
|
if (!isRecord(doc) || !isRecord(doc.hooks))
|
|
129
152
|
return { state: 'no-hooks' };
|
|
130
|
-
const
|
|
131
|
-
if (
|
|
153
|
+
const merged = mergedStates(trustFiles);
|
|
154
|
+
if ('unreadable' in merged) {
|
|
132
155
|
return {
|
|
133
156
|
state: 'unreadable',
|
|
134
|
-
reason: `${
|
|
157
|
+
reason: `${merged.unreadable} records hook state in a form doctor does not read`,
|
|
135
158
|
};
|
|
136
159
|
}
|
|
160
|
+
const { states } = merged;
|
|
137
161
|
const hooks = [];
|
|
138
162
|
for (const [event, groups] of Object.entries(doc.hooks)) {
|
|
139
163
|
if (!Array.isArray(groups))
|
|
@@ -146,7 +170,7 @@ export const readCodexTrust = (hooksPath, configPath) => {
|
|
|
146
170
|
continue;
|
|
147
171
|
if (commandOwnership(handler.command) !== 'cli')
|
|
148
172
|
continue;
|
|
149
|
-
const key =
|
|
173
|
+
const key = hookTrustKey(keySource, event, gi, hi);
|
|
150
174
|
const state = states.get(key);
|
|
151
175
|
const current = codexHookHash(event, typeof group.matcher === 'string' ? group.matcher : undefined, {
|
|
152
176
|
type: 'command',
|
package/dist/core/detect.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, readdirSync } from 'node:fs';
|
|
2
|
+
import { accessSync, constants as fsConstants, existsSync, readdirSync } from 'node:fs';
|
|
3
3
|
import { platform as osPlatform } from 'node:os';
|
|
4
|
+
import { delimiter, isAbsolute, join } from 'node:path';
|
|
4
5
|
export const hasPath = (path) => existsSync(path);
|
|
5
6
|
export const hasBinary = (name) => {
|
|
6
7
|
const finder = osPlatform() === 'win32' ? 'where' : 'which';
|
|
@@ -20,3 +21,21 @@ export const hasEntryPrefixed = (dir, prefix) => {
|
|
|
20
21
|
return false;
|
|
21
22
|
}
|
|
22
23
|
};
|
|
24
|
+
export const trustedPath = (env = process.env) => (env.PATH ?? '')
|
|
25
|
+
.split(delimiter)
|
|
26
|
+
.filter((dir) => dir && isAbsolute(dir) && !/[\\/]node_modules[\\/]\.bin[\\/]?$/.test(dir))
|
|
27
|
+
.join(delimiter);
|
|
28
|
+
export const trustedBinary = (name, env = process.env) => {
|
|
29
|
+
for (const dir of trustedPath(env).split(delimiter)) {
|
|
30
|
+
if (!dir)
|
|
31
|
+
continue;
|
|
32
|
+
const candidate = join(dir, name);
|
|
33
|
+
try {
|
|
34
|
+
accessSync(candidate, fsConstants.X_OK);
|
|
35
|
+
return candidate;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return undefined;
|
|
41
|
+
};
|