@dzhechkov/harness-core 0.4.5 → 0.5.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.
- package/.dz-manifest.json +489 -105
- package/README.md +116 -5
- package/dist/agents-policy.d.ts +67 -0
- package/dist/agents-policy.d.ts.map +1 -0
- package/dist/agents-policy.js +258 -0
- package/dist/agents-policy.js.map +1 -0
- package/dist/codex-hooks-assets.d.ts +47 -0
- package/dist/codex-hooks-assets.d.ts.map +1 -0
- package/dist/codex-hooks-assets.js +324 -0
- package/dist/codex-hooks-assets.js.map +1 -0
- package/dist/codex-hooks-verify.d.ts +95 -0
- package/dist/codex-hooks-verify.d.ts.map +1 -0
- package/dist/codex-hooks-verify.js +169 -0
- package/dist/codex-hooks-verify.js.map +1 -0
- package/dist/codex-hooks.d.ts +341 -0
- package/dist/codex-hooks.d.ts.map +1 -0
- package/dist/codex-hooks.js +541 -0
- package/dist/codex-hooks.js.map +1 -0
- package/dist/discrimination-gate.d.ts +88 -15
- package/dist/discrimination-gate.d.ts.map +1 -1
- package/dist/discrimination-gate.js +343 -51
- package/dist/discrimination-gate.js.map +1 -1
- package/dist/feature-adr-checkpoints.d.ts +22 -0
- package/dist/feature-adr-checkpoints.d.ts.map +1 -1
- package/dist/feature-adr-checkpoints.js +42 -0
- package/dist/feature-adr-checkpoints.js.map +1 -1
- package/dist/feature-adr-routing.d.ts +218 -5
- package/dist/feature-adr-routing.d.ts.map +1 -1
- package/dist/feature-adr-routing.js +583 -54
- package/dist/feature-adr-routing.js.map +1 -1
- package/dist/guard.d.ts +13 -0
- package/dist/guard.d.ts.map +1 -1
- package/dist/guard.js +25 -1
- package/dist/guard.js.map +1 -1
- package/dist/index.d.ts +23 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +37 -4
- package/dist/index.js.map +1 -1
- package/dist/loop-blobs.generated.d.ts +1 -1
- package/dist/loop-blobs.generated.d.ts.map +1 -1
- package/dist/loop-blobs.generated.js +12 -3
- package/dist/loop-blobs.generated.js.map +1 -1
- package/dist/loop-plan.d.ts +70 -0
- package/dist/loop-plan.d.ts.map +1 -1
- package/dist/loop-plan.js +103 -0
- package/dist/loop-plan.js.map +1 -1
- package/dist/loop-render.d.ts.map +1 -1
- package/dist/loop-render.js +37 -129
- package/dist/loop-render.js.map +1 -1
- package/dist/loop-run-semantics.d.ts +130 -0
- package/dist/loop-run-semantics.d.ts.map +1 -0
- package/dist/loop-run-semantics.js +257 -0
- package/dist/loop-run-semantics.js.map +1 -0
- package/dist/loop-trace.d.ts +31 -2
- package/dist/loop-trace.d.ts.map +1 -1
- package/dist/loop-trace.js +89 -12
- package/dist/loop-trace.js.map +1 -1
- package/dist/managed-hooks.d.ts +86 -0
- package/dist/managed-hooks.d.ts.map +1 -0
- package/dist/managed-hooks.js +101 -0
- package/dist/managed-hooks.js.map +1 -0
- package/dist/mutation-gate.d.ts +14 -0
- package/dist/mutation-gate.d.ts.map +1 -1
- package/dist/mutation-gate.js +25 -2
- package/dist/mutation-gate.js.map +1 -1
- package/dist/named-lock.d.ts +57 -0
- package/dist/named-lock.d.ts.map +1 -0
- package/dist/named-lock.js +247 -0
- package/dist/named-lock.js.map +1 -0
- package/dist/operations.d.ts +229 -0
- package/dist/operations.d.ts.map +1 -1
- package/dist/operations.js +880 -26
- package/dist/operations.js.map +1 -1
- package/dist/parity.d.ts +106 -1
- package/dist/parity.d.ts.map +1 -1
- package/dist/parity.js +209 -5
- package/dist/parity.js.map +1 -1
- package/dist/qe-bridge.d.ts +291 -0
- package/dist/qe-bridge.d.ts.map +1 -0
- package/dist/qe-bridge.js +538 -0
- package/dist/qe-bridge.js.map +1 -0
- package/dist/recall-usage.d.ts +53 -0
- package/dist/recall-usage.d.ts.map +1 -1
- package/dist/recall-usage.js +125 -2
- package/dist/recall-usage.js.map +1 -1
- package/dist/score.d.ts.map +1 -1
- package/dist/score.js +43 -9
- package/dist/score.js.map +1 -1
- package/dist/setup.d.ts.map +1 -1
- package/dist/setup.js +14 -26
- package/dist/setup.js.map +1 -1
- package/dist/shell-veto-policy.d.ts +53 -0
- package/dist/shell-veto-policy.d.ts.map +1 -0
- package/dist/shell-veto-policy.js +103 -0
- package/dist/shell-veto-policy.js.map +1 -0
- package/dist/skills.d.ts +86 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/skills.js +116 -1
- package/dist/skills.js.map +1 -1
- package/dist/targets.d.ts +75 -0
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +160 -0
- package/dist/targets.js.map +1 -1
- package/dist/workflow-run-dispatch.d.ts +230 -0
- package/dist/workflow-run-dispatch.d.ts.map +1 -0
- package/dist/workflow-run-dispatch.js +363 -0
- package/dist/workflow-run-dispatch.js.map +1 -0
- package/dist/workflow-run.d.ts +498 -0
- package/dist/workflow-run.d.ts.map +1 -0
- package/dist/workflow-run.js +1359 -0
- package/dist/workflow-run.js.map +1 -0
- package/package.json +6 -5
- package/sbom.json +1099 -139
- package/src/agents-policy.ts +338 -0
- package/src/codex-hooks-assets.ts +328 -0
- package/src/codex-hooks-verify.ts +237 -0
- package/src/codex-hooks.ts +723 -0
- package/src/discrimination-gate.ts +456 -58
- package/src/feature-adr-checkpoints.ts +38 -0
- package/src/feature-adr-routing.ts +697 -75
- package/src/guard.ts +36 -1
- package/src/index.ts +162 -2
- package/src/loop-blobs.generated.ts +12 -3
- package/src/loop-plan.ts +185 -0
- package/src/loop-render.ts +37 -127
- package/src/loop-run-semantics.ts +278 -0
- package/src/loop-trace.ts +84 -10
- package/src/managed-hooks.ts +150 -0
- package/src/mutation-gate.ts +24 -2
- package/src/named-lock.ts +277 -0
- package/src/operations.ts +1121 -29
- package/src/parity.ts +295 -6
- package/src/qe-bridge.ts +737 -0
- package/src/recall-usage.ts +184 -1
- package/src/score.ts +50 -9
- package/src/setup.ts +26 -27
- package/src/shell-veto-policy.ts +119 -0
- package/src/skills.ts +174 -1
- package/src/targets.ts +189 -0
- package/src/workflow-run-dispatch.ts +459 -0
- package/src/workflow-run.ts +1743 -0
package/dist/operations.js
CHANGED
|
@@ -5,8 +5,15 @@
|
|
|
5
5
|
*
|
|
6
6
|
* @packageDocumentation
|
|
7
7
|
*/
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
10
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { homedir, tmpdir } from 'node:os';
|
|
12
|
+
import { dirname, join, resolve as resolvePath } from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { buildManagedEntries, buildCodexHookManifest, codexHooksPaths, diffCodexHooks, parseCodexHookManifest, planCodexHooks, removeCodexHooks, selectOwnHookMetadata, upsertTrustBlock, } from './codex-hooks.js';
|
|
15
|
+
import { generateCodexHelpers } from './codex-hooks-assets.js';
|
|
16
|
+
import { classifyVetoProbe, isReadyVerdict, verifyExitCode, } from './codex-hooks-verify.js';
|
|
10
17
|
import { AGENTS_MD_PATH } from '@dzhechkov/adapter-agents-md';
|
|
11
18
|
import { claudeAdapter } from '@dzhechkov/adapter-claude';
|
|
12
19
|
import { CODEX_SKILLS_ROOT } from '@dzhechkov/adapter-codex';
|
|
@@ -17,11 +24,12 @@ import { OPENCLAUDE_SKILLS_ROOT } from '@dzhechkov/adapter-openclaude';
|
|
|
17
24
|
import { COPILOT_INSTRUCTIONS_ROOT } from '@dzhechkov/adapter-copilot';
|
|
18
25
|
import { CURSOR_RULES_ROOT } from '@dzhechkov/adapter-cursor';
|
|
19
26
|
import { WINDSURF_RULES_ROOT } from '@dzhechkov/adapter-windsurf';
|
|
20
|
-
import { mergeAgentsMd, mergeGeminiMd, renderAgentsMdSection } from '@dzhechkov/core';
|
|
27
|
+
import { AGENTS_MD_BLOCK_BEGIN, mergeAgentsMd, mergeGeminiMd, mergePolicyBlock, renderAgentsMdSection } from '@dzhechkov/core';
|
|
21
28
|
import { computeRiskScore } from './risk-scoring.js';
|
|
22
29
|
import { applyEmitResult } from './apply.js';
|
|
23
|
-
import { discoverSkillIds, loadSkillFromDir } from './skills.js';
|
|
30
|
+
import { describeSkillLoadFailure, discoverSkillIds, loadSkillFromDir } from './skills.js';
|
|
24
31
|
import { TARGETS } from './targets.js';
|
|
32
|
+
import { AGENTS_MD_BUDGET_WARN_FRACTION, CODEX_PROJECT_DOC_MAX_BYTES, POLICY_SOURCES, detectPolicyDrift, extractPolicyBlocks, measureAgentsMdBudget, renderPolicySections, } from './agents-policy.js';
|
|
25
33
|
// ---------------------------------------------------------------------------
|
|
26
34
|
// Platform enrichment — optional extras beyond SKILL.md
|
|
27
35
|
// ---------------------------------------------------------------------------
|
|
@@ -121,6 +129,26 @@ function enrichEmitForTarget(emit, target, skillId, skill) {
|
|
|
121
129
|
warnings: [...emit.warnings, `enriched: ${extra.length} platform-specific file(s) for ${target}`],
|
|
122
130
|
};
|
|
123
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* The one read/merge/write path for every root managed-Markdown projection.
|
|
134
|
+
* `write:false` is check-only and never creates a directory or target file.
|
|
135
|
+
* A max-byte refusal happens before mkdir/write, leaving the target byte-identical.
|
|
136
|
+
*/
|
|
137
|
+
export function writeManagedMarkdown(projectRoot, sections, config, options = {}) {
|
|
138
|
+
const fileAbs = join(projectRoot, config.filePath);
|
|
139
|
+
const existing = existsSync(fileAbs) ? readFileSync(fileAbs, 'utf-8') : null;
|
|
140
|
+
const merged = config.merge(existing, sections);
|
|
141
|
+
const bytes = Buffer.byteLength(merged, 'utf8');
|
|
142
|
+
if (options.maxBytes !== undefined && bytes > options.maxBytes) {
|
|
143
|
+
throw new Error(`${config.filePath} policy emit exceeds the ${options.maxBytes.toLocaleString('en-US')} byte Codex project-document budget (${bytes.toLocaleString('en-US')} bytes); target left unchanged`);
|
|
144
|
+
}
|
|
145
|
+
const changed = merged !== existing;
|
|
146
|
+
if (options.write !== false && changed) {
|
|
147
|
+
mkdirSync(dirname(fileAbs), { recursive: true });
|
|
148
|
+
writeFileSync(fileAbs, merged, 'utf-8');
|
|
149
|
+
}
|
|
150
|
+
return { filePath: config.filePath, changed, bytes, content: merged };
|
|
151
|
+
}
|
|
124
152
|
/**
|
|
125
153
|
* The lossy warning surfaced ONCE per agents-md install (not once per skill):
|
|
126
154
|
* agents-md flattens every selected skill into plain-Markdown sections of a
|
|
@@ -170,19 +198,24 @@ function runInitSingleFileMd(options, config) {
|
|
|
170
198
|
}
|
|
171
199
|
}
|
|
172
200
|
const missing = selection === undefined ? [] : selection.filter((id) => !discovered.has(id));
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
const
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
201
|
+
// Skip-and-collect: one unloadable skill must not discard the whole aggregation.
|
|
202
|
+
const failures = [];
|
|
203
|
+
const loaded = [];
|
|
204
|
+
for (const { id, skillsDir } of picked) {
|
|
205
|
+
try {
|
|
206
|
+
loaded.push({ id, section: renderAgentsMdSection(loadSkillFromDir(skillsDir, id)) });
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
failures.push(describeSkillLoadFailure(skillsDir, id, error));
|
|
210
|
+
}
|
|
181
211
|
}
|
|
212
|
+
const sections = loaded.map((entry) => entry.section);
|
|
213
|
+
const managed = writeManagedMarkdown(options.projectRoot, sections, config, { write: loaded.length > 0 });
|
|
214
|
+
const changed = managed.changed;
|
|
182
215
|
// Report the shared root file as written/skipped on the FIRST contributing
|
|
183
216
|
// skill only, so callers that SUM per-skill file counts don't count the one
|
|
184
217
|
// shared file N times. The lossy warning is surfaced ONCE, on that same skill.
|
|
185
|
-
const skills =
|
|
218
|
+
const skills = loaded.map(({ id }, index) => {
|
|
186
219
|
const owns = index === 0;
|
|
187
220
|
return {
|
|
188
221
|
id,
|
|
@@ -191,7 +224,9 @@ function runInitSingleFileMd(options, config) {
|
|
|
191
224
|
warnings: owns ? [config.lossyWarning] : [],
|
|
192
225
|
};
|
|
193
226
|
});
|
|
194
|
-
|
|
227
|
+
// No apply failures are possible here: the single write is outside every per-skill
|
|
228
|
+
// loop, so a write error propagates as itself rather than being attributed to a skill.
|
|
229
|
+
return { target: config.target, skillsDir: joinedDir, projectRoot: options.projectRoot, skills, missing, failures, applyFailures: [] };
|
|
195
230
|
}
|
|
196
231
|
/**
|
|
197
232
|
* Aggregate every selected skill into ONE root `AGENTS.md`, merging into any
|
|
@@ -220,6 +255,88 @@ export function runInitGeminiMd(options) {
|
|
|
220
255
|
lossyWarning: GEMINI_MD_LOSSY_WARNING,
|
|
221
256
|
});
|
|
222
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* Refresh or verify the policy fence in root AGENTS.md. Source reads are an
|
|
260
|
+
* explicit I/O shell around the pure agents-policy module; missing/unreadable
|
|
261
|
+
* input returns inconclusive evidence and never writes a partial projection.
|
|
262
|
+
*/
|
|
263
|
+
export function runSyncAgentsPolicy(options) {
|
|
264
|
+
const sources = options.sources ?? POLICY_SOURCES;
|
|
265
|
+
const sourceFiles = new Map();
|
|
266
|
+
for (const file of new Set(sources.map((source) => source.file))) {
|
|
267
|
+
try {
|
|
268
|
+
sourceFiles.set(file, readFileSync(join(options.projectRoot, file), 'utf8'));
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
sourceFiles.set(file, null);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const agentsPath = join(options.projectRoot, AGENTS_MD_PATH);
|
|
275
|
+
let currentAgents = null;
|
|
276
|
+
try {
|
|
277
|
+
currentAgents = readFileSync(agentsPath, 'utf8');
|
|
278
|
+
}
|
|
279
|
+
catch { /* absent target is a normal first sync */ }
|
|
280
|
+
const extracted = extractPolicyBlocks(sourceFiles, sources);
|
|
281
|
+
if (extracted.missing.length > 0) {
|
|
282
|
+
const drift = detectPolicyDrift(sourceFiles, currentAgents, sources);
|
|
283
|
+
return {
|
|
284
|
+
filePath: AGENTS_MD_PATH,
|
|
285
|
+
changed: true,
|
|
286
|
+
written: false,
|
|
287
|
+
inSync: false,
|
|
288
|
+
blocks: extracted.blocks.map(({ id, sha }) => ({ id, sha })),
|
|
289
|
+
missing: extracted.missing,
|
|
290
|
+
drift: drift.findings,
|
|
291
|
+
budget: measureAgentsMdBudget(currentAgents ?? ''),
|
|
292
|
+
warnings: [`policy source evidence is incomplete: ${extracted.missing.join(', ')}`],
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
const currentDrift = detectPolicyDrift(sourceFiles, currentAgents, sources);
|
|
296
|
+
const malformedOuterFence = currentDrift.findings.some((finding) => finding.id === 'dz:policies');
|
|
297
|
+
if (options.check !== true && malformedOuterFence) {
|
|
298
|
+
return {
|
|
299
|
+
filePath: AGENTS_MD_PATH,
|
|
300
|
+
changed: true,
|
|
301
|
+
written: false,
|
|
302
|
+
inSync: false,
|
|
303
|
+
blocks: extracted.blocks.map(({ id, sha }) => ({ id, sha })),
|
|
304
|
+
missing: [],
|
|
305
|
+
drift: currentDrift.findings,
|
|
306
|
+
budget: measureAgentsMdBudget(currentAgents ?? ''),
|
|
307
|
+
warnings: ['refusing to rewrite malformed or duplicate dz:policies fence markers; repair their cardinality first'],
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
const sections = renderPolicySections(extracted.blocks, sources);
|
|
311
|
+
const rendered = sections.join('\n\n');
|
|
312
|
+
const claudeOnlyTokens = ['Workflow({', 'subagent_type', 'mcp__', '.claude/agents/v3/'];
|
|
313
|
+
const leaked = claudeOnlyTokens.find((token) => rendered.includes(token));
|
|
314
|
+
if (leaked !== undefined)
|
|
315
|
+
throw new Error(`AGENTS.md policy block contains Claude-only token ${JSON.stringify(leaked)}; target left unchanged`);
|
|
316
|
+
const managed = writeManagedMarkdown(options.projectRoot, sections, { filePath: AGENTS_MD_PATH, merge: mergePolicyBlock }, { write: options.check !== true, maxBytes: CODEX_PROJECT_DOC_MAX_BYTES });
|
|
317
|
+
const budget = measureAgentsMdBudget(managed.content);
|
|
318
|
+
const drift = detectPolicyDrift(sourceFiles, options.check === true ? currentAgents : managed.content, sources);
|
|
319
|
+
const warnings = [];
|
|
320
|
+
if (budget.bytes >= budget.cap * AGENTS_MD_BUDGET_WARN_FRACTION) {
|
|
321
|
+
warnings.push(`AGENTS.md uses ${budget.pct}% of the measured ${budget.cap.toLocaleString('en-US')} byte Codex project-document budget`);
|
|
322
|
+
}
|
|
323
|
+
const skillsBegin = managed.content.indexOf(AGENTS_MD_BLOCK_BEGIN);
|
|
324
|
+
if (skillsBegin !== -1 && budget.policyBlockEndsAtByte > Buffer.byteLength(managed.content.slice(0, skillsBegin), 'utf8')) {
|
|
325
|
+
warnings.push('policy fence must end before the skills fence because Codex truncates the tail');
|
|
326
|
+
}
|
|
327
|
+
const nonOk = drift.findings.filter((finding) => finding.status !== 'ok');
|
|
328
|
+
return {
|
|
329
|
+
filePath: AGENTS_MD_PATH,
|
|
330
|
+
changed: managed.changed,
|
|
331
|
+
written: options.check !== true && managed.changed,
|
|
332
|
+
inSync: options.check === true ? !managed.changed && nonOk.length === 0 : nonOk.length === 0,
|
|
333
|
+
blocks: extracted.blocks.map(({ id, sha }) => ({ id, sha })),
|
|
334
|
+
missing: [],
|
|
335
|
+
drift: drift.findings,
|
|
336
|
+
budget,
|
|
337
|
+
warnings,
|
|
338
|
+
};
|
|
339
|
+
}
|
|
223
340
|
/** Compile every skill in `skillsDir` for `target` and apply it under `projectRoot`. */
|
|
224
341
|
export async function runInit(options) {
|
|
225
342
|
// agents-md is a flattening single-file target — aggregate all selected skills
|
|
@@ -248,19 +365,43 @@ export async function runInit(options) {
|
|
|
248
365
|
const missing = selection === undefined
|
|
249
366
|
? []
|
|
250
367
|
: selection.filter((id) => !discovered.includes(id));
|
|
368
|
+
// Skip-and-collect (D1): one unparseable SKILL.md must not discard the whole install.
|
|
369
|
+
// Same shape as `runVerify`'s long-standing per-id try/catch below.
|
|
370
|
+
//
|
|
371
|
+
// The `try` is scoped to `loadSkillFromDir` ALONE (ADR-001 §Decision part 2, restored
|
|
372
|
+
// in fix round 1 / QE F4). It used to wrap compile + apply too, so an EEXIST from
|
|
373
|
+
// `mkdir` was described by `describeSkillLoadFailure` and printed under the
|
|
374
|
+
// "unparseable SKILL.md" header, naming the source file — which was valid. Compile
|
|
375
|
+
// and write failures are a SECOND kind with their own subject and their own header;
|
|
376
|
+
// they are collected, not thrown, so one unwritable target directory still cannot
|
|
377
|
+
// discard the rest of the install.
|
|
378
|
+
const failures = [];
|
|
379
|
+
const applyFailures = [];
|
|
251
380
|
for (const id of ids) {
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
381
|
+
let skill;
|
|
382
|
+
try {
|
|
383
|
+
skill = loadSkillFromDir(options.skillsDir, id);
|
|
384
|
+
}
|
|
385
|
+
catch (error) {
|
|
386
|
+
failures.push(describeSkillLoadFailure(options.skillsDir, id, error));
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
let emit = await adapter.compile(skill, { targetRoot: options.projectRoot });
|
|
391
|
+
if (options.enrich === true) {
|
|
392
|
+
emit = enrichEmitForTarget(emit, options.target, id, skill);
|
|
393
|
+
}
|
|
394
|
+
const applied = applyEmitResult(emit, {
|
|
395
|
+
targetRoot: options.projectRoot,
|
|
396
|
+
force: options.force === true,
|
|
397
|
+
});
|
|
398
|
+
skills.push({ id, written: applied.written, skipped: applied.skipped, warnings: [...emit.warnings] });
|
|
399
|
+
}
|
|
400
|
+
catch (error) {
|
|
401
|
+
applyFailures.push({ id, reason: error instanceof Error ? error.message : String(error) });
|
|
402
|
+
}
|
|
262
403
|
}
|
|
263
|
-
return { target: options.target, skillsDir: options.skillsDir, projectRoot: options.projectRoot, skills, missing };
|
|
404
|
+
return { target: options.target, skillsDir: options.skillsDir, projectRoot: options.projectRoot, skills, missing, failures, applyFailures };
|
|
264
405
|
}
|
|
265
406
|
/** Compile every skill for `target` and report whether each verifies. */
|
|
266
407
|
export async function runVerify(options) {
|
|
@@ -295,9 +436,18 @@ export async function runVerify(options) {
|
|
|
295
436
|
export async function runSync(options) {
|
|
296
437
|
const dirs = options.canonicalDirs ?? (options.canonicalDir ? [options.canonicalDir] : []);
|
|
297
438
|
const skills = [];
|
|
439
|
+
// Skip-and-collect (D1): a broken canonical skill must not hide every other pack.
|
|
440
|
+
const failures = [];
|
|
298
441
|
for (const canonicalDir of dirs) {
|
|
299
442
|
for (const id of discoverSkillIds(canonicalDir)) {
|
|
300
|
-
|
|
443
|
+
let skill;
|
|
444
|
+
try {
|
|
445
|
+
skill = loadSkillFromDir(canonicalDir, id);
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
failures.push(describeSkillLoadFailure(canonicalDir, id, error));
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
301
451
|
const emit = await claudeAdapter.compile(skill, { targetRoot: options.projectRoot });
|
|
302
452
|
let differ = false;
|
|
303
453
|
let missing = false;
|
|
@@ -323,6 +473,7 @@ export async function runSync(options) {
|
|
|
323
473
|
return {
|
|
324
474
|
dryRun: options.dryRun === true,
|
|
325
475
|
skills,
|
|
476
|
+
failures,
|
|
326
477
|
summary: {
|
|
327
478
|
total: skills.length,
|
|
328
479
|
inSync: skills.filter((skill) => skill.status === 'in-sync').length,
|
|
@@ -526,6 +677,38 @@ export async function runDoctor(options) {
|
|
|
526
677
|
}
|
|
527
678
|
}
|
|
528
679
|
catch { /* settings absent/unreadable — covered by other checks */ }
|
|
680
|
+
// CODEX APPLY-LEG (AM-19, fact CORRECTED by AM-30). This block is deliberately OUTSIDE the
|
|
681
|
+
// `existsSync(writerPath)` guard below. MEASURED: the Claude apply-leg check has THREE
|
|
682
|
+
// preconditions, not two — the `.claude/settings.json` text check is NESTED inside
|
|
683
|
+
// `if (existsSync(join(root,'.dz','agentdb-writer.mjs')))`. A Codex-only machine has no writer
|
|
684
|
+
// file and no `.claude/settings.json`, so a Codex branch added *in place* would report nothing at
|
|
685
|
+
// all — reproducing the exact 19-day dark-leg shape this check exists to kill.
|
|
686
|
+
//
|
|
687
|
+
// A WIRED-BUT-SILENT leg is an explicit non-OK row, never an absent one.
|
|
688
|
+
try {
|
|
689
|
+
const { codexHooksPaths: codexPaths, parseCodexHookManifest: parseCodexManifest } = await import('./codex-hooks.js');
|
|
690
|
+
const codexHome = process.env['CODEX_HOME'] ?? join(homedir(), '.codex');
|
|
691
|
+
const manifestPath = codexPaths(codexHome).manifest;
|
|
692
|
+
if (existsSync(manifestPath)) {
|
|
693
|
+
const manifest = parseCodexManifest(readFileSync(manifestPath, 'utf-8'));
|
|
694
|
+
const claimsRecall = manifest?.entries.some((e) => e.id === 'codex-recall') === true;
|
|
695
|
+
if (claimsRecall) {
|
|
696
|
+
const usageLog = join(root, '.dz', 'recall-usage.jsonl');
|
|
697
|
+
const { newest, hasCodexRow } = newestRecallUsageRuntime(usageLog);
|
|
698
|
+
const fresh = newest !== undefined && Date.now() - Date.parse(newest) < 14 * 24 * 60 * 60 * 1000;
|
|
699
|
+
checks.push({
|
|
700
|
+
name: 'codex apply-leg (recall hook)',
|
|
701
|
+
ok: hasCodexRow && fresh,
|
|
702
|
+
detail: hasCodexRow
|
|
703
|
+
? fresh
|
|
704
|
+
? `codex recall rows present, newest ${newest}`
|
|
705
|
+
: `codex recall hook is WIRED but SILENT: newest recall-usage row is ${String(newest)} — the entry may have lost hook trust (re-run dz hooks-sync --target codex --verify)`
|
|
706
|
+
: 'codex recall hook is WIRED but has NEVER written a row — a dead leg looks exactly like a correctly-silent one, so this is reported non-OK until one lands',
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
catch { /* doctor never throws on a diagnostic */ }
|
|
529
712
|
const writerPath = join(root, '.dz', 'agentdb-writer.mjs');
|
|
530
713
|
if (existsSync(writerPath)) {
|
|
531
714
|
const { writerVersionOf, AGENTDB_WRITER_VERSION } = await import('./setup.js');
|
|
@@ -621,4 +804,675 @@ export async function runDoctor(options) {
|
|
|
621
804
|
catch { /* advisory only — the vector tier must never fail doctor */ }
|
|
622
805
|
return { node: process.version, checks, ok: checks.every((check) => check.ok) };
|
|
623
806
|
}
|
|
807
|
+
/** The one place that decides WHERE `hooks.json` lives. Exported (feature qe-bridge-claude) so the
|
|
808
|
+
* CLI can take the `codex-hooks` advisory lock BESIDE that registry — a lock in this repo's `.dz/`
|
|
809
|
+
* would not serialize a writer operating from another checkout. */
|
|
810
|
+
export function resolveCodexHome(explicit) {
|
|
811
|
+
if (typeof explicit === 'string' && explicit !== '')
|
|
812
|
+
return explicit;
|
|
813
|
+
const env = process.env['CODEX_HOME'];
|
|
814
|
+
if (typeof env === 'string' && env !== '')
|
|
815
|
+
return env;
|
|
816
|
+
return join(homedir(), '.codex');
|
|
817
|
+
}
|
|
818
|
+
/** `codex --version` → `codex-cli 0.147.0`. `null` when the binary is absent or silent. */
|
|
819
|
+
function probeCodexVersion() {
|
|
820
|
+
try {
|
|
821
|
+
const out = execFileSync('codex', ['--version'], { encoding: 'utf8', timeout: 15_000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
822
|
+
const trimmed = out.trim();
|
|
823
|
+
return trimmed === '' ? null : trimmed;
|
|
824
|
+
}
|
|
825
|
+
catch {
|
|
826
|
+
return null;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Run the emitted command THE WAY THE RUNTIME WILL — through `$SHELL -lc` (AM-32 / G-L).
|
|
831
|
+
*
|
|
832
|
+
* MEASURED: the codex hook runner spawns via `$SHELL -lc`, and under nvm/asdf/volta a
|
|
833
|
+
* non-interactive login shell frequently lacks `node`. The helper then exits **127**, which the
|
|
834
|
+
* runtime reads as **ALLOW** — a blocking guard that is silently dead in the fail-open direction,
|
|
835
|
+
* with the helper's own self-failure note unable to fire because the process never started.
|
|
836
|
+
* Grading on file presence would call that "installed".
|
|
837
|
+
*/
|
|
838
|
+
export function probeHookLiveness(command, payload) {
|
|
839
|
+
const shell = process.env['SHELL'] ?? '/bin/sh';
|
|
840
|
+
try {
|
|
841
|
+
const res = spawnSync(shell, ['-lc', command], {
|
|
842
|
+
input: payload,
|
|
843
|
+
encoding: 'utf8',
|
|
844
|
+
timeout: 20_000,
|
|
845
|
+
env: { ...process.env, DZ_HOOK_LIVENESS_PROBE: '1' },
|
|
846
|
+
});
|
|
847
|
+
return { status: res.status, stderr: res.stderr ?? '' };
|
|
848
|
+
}
|
|
849
|
+
catch (err) {
|
|
850
|
+
return { status: null, stderr: String(err?.message ?? err) };
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
/** Keep the newest N backups; older ones are litter in the user's home (AM-35b). */
|
|
854
|
+
function pruneBackups(dir, prefix, keep) {
|
|
855
|
+
try {
|
|
856
|
+
const found = readdirSync(dir).filter((f) => f.startsWith(prefix)).sort();
|
|
857
|
+
for (const stale of found.slice(0, Math.max(0, found.length - keep))) {
|
|
858
|
+
rmSync(join(dir, stale), { force: true });
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
catch { /* pruning is hygiene, never a failure */ }
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Install, verify or remove the dz Codex hooks.
|
|
865
|
+
*
|
|
866
|
+
* Order is load-bearing: every REFUSAL happens before any `mkdir` or write, so a machine without
|
|
867
|
+
* codex, or with an unparseable registry, is left byte-untouched (AM-35a).
|
|
868
|
+
*/
|
|
869
|
+
/**
|
|
870
|
+
* Should this run PROVE the guard fires, and with what?
|
|
871
|
+
*
|
|
872
|
+
* `liveness: false` is the offline test seam and disables every live call, the probe included.
|
|
873
|
+
* `verify: false` is the USER saying "do not probe" — a deliberate refusal to measure, which is
|
|
874
|
+
* reported as inconclusive rather than as success (finding 1).
|
|
875
|
+
*/
|
|
876
|
+
function verifyPlan(options) {
|
|
877
|
+
if (options.liveness === false)
|
|
878
|
+
return { run: false, declined: false };
|
|
879
|
+
if (options.verify === false)
|
|
880
|
+
return { run: false, declined: true };
|
|
881
|
+
return { run: true, declined: false };
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Run the live probe (or record, loudly, why it did not run).
|
|
885
|
+
*
|
|
886
|
+
* A refusal to measure and a measurement are different facts and are reported differently: a
|
|
887
|
+
* declined verify never reaches exit 0, and a probe that could not be driven at all is
|
|
888
|
+
* `inconclusive`, never `ready` (finding 1).
|
|
889
|
+
*/
|
|
890
|
+
function verifyStage(options, ctx) {
|
|
891
|
+
const plan = verifyPlan(options);
|
|
892
|
+
if (!plan.run) {
|
|
893
|
+
if (plan.declined) {
|
|
894
|
+
ctx.warnings.push('live verification SKIPPED (--no-verify): the entries are installed and trusted, but nothing here witnessed the guard block a command. This is NOT a ready state.');
|
|
895
|
+
}
|
|
896
|
+
return { result: null, declined: plan.declined };
|
|
897
|
+
}
|
|
898
|
+
const probe = options.probe ?? runCodexVetoProbe;
|
|
899
|
+
let run;
|
|
900
|
+
try {
|
|
901
|
+
run = probe({
|
|
902
|
+
paths: ctx.paths,
|
|
903
|
+
...(options.project !== undefined ? { project: options.project } : {}),
|
|
904
|
+
...(options.probeModel ?? process.env['DZ_CODEX_PROBE_MODEL'] ? { model: options.probeModel ?? process.env['DZ_CODEX_PROBE_MODEL'] } : {}),
|
|
905
|
+
...(ctx.trustStatus !== undefined ? { trustStatus: ctx.trustStatus } : {}),
|
|
906
|
+
...(ctx.recordedCodexVersion !== undefined ? { recordedCodexVersion: ctx.recordedCodexVersion } : {}),
|
|
907
|
+
probedCodexVersion: ctx.probedCodexVersion,
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
catch (err) {
|
|
911
|
+
// A probe that THREW measured nothing. Inconclusive is the honest verdict; a thrown probe that
|
|
912
|
+
// fell through to the install state would be the finding all over again.
|
|
913
|
+
ctx.warnings.push(`the live veto probe could not be driven: ${String(err?.message ?? err)}`);
|
|
914
|
+
return {
|
|
915
|
+
result: { verdict: 'inconclusive', trust: 'unknown', reason: `the live veto probe could not be driven: ${String(err?.message ?? err)}` },
|
|
916
|
+
declined: false,
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
for (const note of run.notes)
|
|
920
|
+
ctx.warnings.push(`veto probe: ${note}`);
|
|
921
|
+
if (!isReadyVerdict(run.result)) {
|
|
922
|
+
ctx.warnings.push(`live veto probe: ${run.result.verdict} — ${run.result.reason}`);
|
|
923
|
+
}
|
|
924
|
+
return { result: run.result, declined: false };
|
|
925
|
+
}
|
|
926
|
+
export function runSyncCodexHooks(options = {}) {
|
|
927
|
+
const codexHome = resolveCodexHome(options.codexHome);
|
|
928
|
+
const paths = codexHooksPaths(codexHome);
|
|
929
|
+
const warnings = [];
|
|
930
|
+
const errors = [];
|
|
931
|
+
const writes = [];
|
|
932
|
+
const now = options.now ?? new Date().toISOString();
|
|
933
|
+
const nodePath = options.nodePath ?? process.execPath;
|
|
934
|
+
const base = {
|
|
935
|
+
codexHome,
|
|
936
|
+
registryPath: paths.registry,
|
|
937
|
+
installed: false,
|
|
938
|
+
executable: false,
|
|
939
|
+
written: false,
|
|
940
|
+
removed: 0,
|
|
941
|
+
foreignPreserved: 0,
|
|
942
|
+
unattributable: 0,
|
|
943
|
+
drift: [],
|
|
944
|
+
trust: 'unknown',
|
|
945
|
+
codexVersion: null,
|
|
946
|
+
writes: [],
|
|
947
|
+
verify: null,
|
|
948
|
+
verified: false,
|
|
949
|
+
ready: false,
|
|
950
|
+
};
|
|
951
|
+
// (1) REFUSE when codex is not installed — dz does not create user-global config for a runtime
|
|
952
|
+
// that is not there (AM-35a). `--check` is allowed to answer, but it writes nothing anyway.
|
|
953
|
+
const codexVersion = options.codexVersion === undefined ? probeCodexVersion() : options.codexVersion;
|
|
954
|
+
if (codexVersion === null) {
|
|
955
|
+
return { ...base, exitCode: 3, warnings, errors: ['no `codex` binary on PATH — nothing was written'] };
|
|
956
|
+
}
|
|
957
|
+
// (2) REFUSE an unquotable CODEX_HOME rather than emit a broken `$SHELL -lc` string (AM-35d).
|
|
958
|
+
let entries;
|
|
959
|
+
try {
|
|
960
|
+
entries = buildManagedEntries({ nodePath, paths });
|
|
961
|
+
}
|
|
962
|
+
catch (err) {
|
|
963
|
+
return { ...base, codexVersion, exitCode: 1, warnings, errors: [String(err.message)] };
|
|
964
|
+
}
|
|
965
|
+
const criticalSection = options.criticalSection ?? ((fn) => fn());
|
|
966
|
+
const currentText = existsSync(paths.registry) ? readFileSync(paths.registry, 'utf8') : undefined;
|
|
967
|
+
const manifest = existsSync(paths.manifest) ? parseCodexHookManifest(readFileSync(paths.manifest, 'utf8')) : undefined;
|
|
968
|
+
// (3) --remove: delete only what the manifest proves is ours.
|
|
969
|
+
if (options.remove === true) {
|
|
970
|
+
// TRANSACTION: re-read under the lock, plan from THOSE bytes, write. A plan computed outside the
|
|
971
|
+
// guarded window is a plan against bytes another writer may already have replaced.
|
|
972
|
+
const removal = criticalSection(() => {
|
|
973
|
+
const freshText = existsSync(paths.registry) ? readFileSync(paths.registry, 'utf8') : undefined;
|
|
974
|
+
const freshManifest = existsSync(paths.manifest) ? parseCodexHookManifest(readFileSync(paths.manifest, 'utf8')) : undefined;
|
|
975
|
+
const planned = removeCodexHooks(freshText, freshManifest);
|
|
976
|
+
if (planned.ok && planned.result.changed) {
|
|
977
|
+
backupRegistry(paths, freshText, now, writes);
|
|
978
|
+
atomicWrite(paths.registry, planned.result.text);
|
|
979
|
+
writes.push(paths.registry);
|
|
980
|
+
}
|
|
981
|
+
// R3-5: the helpers and the manifest are part of the SAME shared state as the registry. Round
|
|
982
|
+
// 2 deleted them after the lock was released, so a concurrent installer could observe (and
|
|
983
|
+
// rebuild against) a registry that had already been emptied — or leave a manifest describing
|
|
984
|
+
// entries that no longer exist. One decision, one critical section.
|
|
985
|
+
if (planned.ok) {
|
|
986
|
+
for (const p of [paths.vetoHelper, paths.recallHelper, paths.manifest])
|
|
987
|
+
rmSync(p, { force: true });
|
|
988
|
+
}
|
|
989
|
+
return planned;
|
|
990
|
+
});
|
|
991
|
+
if (!removal.ok)
|
|
992
|
+
return { ...base, codexVersion, exitCode: 1, warnings, errors: [removal.error] };
|
|
993
|
+
return {
|
|
994
|
+
...base,
|
|
995
|
+
codexVersion,
|
|
996
|
+
written: removal.result.changed,
|
|
997
|
+
removed: removal.result.removed,
|
|
998
|
+
unattributable: removal.result.unattributable,
|
|
999
|
+
exitCode: 0,
|
|
1000
|
+
warnings: removal.result.unattributable > 0
|
|
1001
|
+
? [`${removal.result.unattributable} entr(ies) resemble dz hooks but are not manifest-attributed — KEPT, remove them by hand if you want them gone`]
|
|
1002
|
+
: warnings,
|
|
1003
|
+
errors,
|
|
1004
|
+
writes,
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
// (4) --check: recompute from the FILE and FIRE the helper. Writes nothing, and stays SILENT in
|
|
1008
|
+
// a home that never opted in (the leg-1 F12 lesson).
|
|
1009
|
+
if (options.check === true) {
|
|
1010
|
+
const drift = diffCodexHooks(currentText, entries, manifest);
|
|
1011
|
+
const live = drift.installed && options.liveness !== false ? probeHookLiveness(entries[0].command, ALLOWED_PROBE_PAYLOAD) : { status: null, stderr: '' };
|
|
1012
|
+
const executable = drift.installed && (options.liveness === false || live.status === 0 || live.status === 2);
|
|
1013
|
+
// `--check` must report the TRUST axis too. Without it the report said `installed && executable`
|
|
1014
|
+
// with `trust: 'unknown'`, and the CLI printed a success word for it — the exact G-G/AM-17
|
|
1015
|
+
// failure ("no success word without armed AND trusted"), reached through the read-only path.
|
|
1016
|
+
const listed = drift.installed && options.liveness !== false ? listCodexHooks(codexHome) : null;
|
|
1017
|
+
const own = listed === null ? [] : selectOwnHookMetadata(listed, entries, { registryPath: paths.registry });
|
|
1018
|
+
const checkTrust = listed === null
|
|
1019
|
+
? 'unknown'
|
|
1020
|
+
: own.length === entries.length && own.every((o) => o.meta.trustStatus === 'trusted' || o.meta.trustStatus === 'managed')
|
|
1021
|
+
? 'trusted'
|
|
1022
|
+
: 'trust-pending';
|
|
1023
|
+
if (drift.installed && !executable) {
|
|
1024
|
+
warnings.push(`the registry entry exists but exits ${String(live.status)} through \`$SHELL -lc\` — a hook that cannot execute is NOT armed`);
|
|
1025
|
+
}
|
|
1026
|
+
// `--check` is the READ-ONLY verify: it recomputes state from the file AND, by default, proves
|
|
1027
|
+
// the guard actually fires. Only when the entries are present — a home that never opted in must
|
|
1028
|
+
// stay silent and must not spend a live model call (the leg-1 F12 lesson).
|
|
1029
|
+
const checkVerify = drift.installed && executable && checkTrust === 'trusted'
|
|
1030
|
+
? verifyStage(options, {
|
|
1031
|
+
paths,
|
|
1032
|
+
probedCodexVersion: codexVersion,
|
|
1033
|
+
...(manifest?.codexVersion !== undefined ? { recordedCodexVersion: manifest.codexVersion } : {}),
|
|
1034
|
+
...(own[0] !== undefined ? { trustStatus: own[0].meta.trustStatus } : {}),
|
|
1035
|
+
warnings,
|
|
1036
|
+
})
|
|
1037
|
+
: { result: null, declined: verifyPlan(options).declined };
|
|
1038
|
+
const checkArmedState = drift.installed && executable && checkTrust === 'trusted';
|
|
1039
|
+
const checkExit = drift.installed
|
|
1040
|
+
? checkArmedState
|
|
1041
|
+
? checkVerify.result !== null
|
|
1042
|
+
? verifyExitCode(checkVerify.result)
|
|
1043
|
+
: checkVerify.declined
|
|
1044
|
+
? 3
|
|
1045
|
+
: 0
|
|
1046
|
+
: 1
|
|
1047
|
+
: manifest === undefined
|
|
1048
|
+
? 0
|
|
1049
|
+
: 1;
|
|
1050
|
+
return {
|
|
1051
|
+
...base,
|
|
1052
|
+
codexVersion,
|
|
1053
|
+
installed: drift.installed,
|
|
1054
|
+
executable,
|
|
1055
|
+
trust: checkTrust,
|
|
1056
|
+
foreignPreserved: drift.foreignPreserved,
|
|
1057
|
+
unattributable: drift.unattributable,
|
|
1058
|
+
drift: drift.drifted,
|
|
1059
|
+
verify: checkVerify.result,
|
|
1060
|
+
verified: checkVerify.result !== null && isReadyVerdict(checkVerify.result),
|
|
1061
|
+
ready: checkArmedState && checkVerify.result !== null && isReadyVerdict(checkVerify.result),
|
|
1062
|
+
// A home that never opted in is NOT a failure: `--check` is silent and exits 0 there (the
|
|
1063
|
+
// leg-1 F12 lesson — a check that chatters in every unrelated project trains its reader to
|
|
1064
|
+
// ignore it). Installed-but-broken is exit 1; installed-and-live-and-PROVEN is exit 0.
|
|
1065
|
+
exitCode: checkExit,
|
|
1066
|
+
warnings,
|
|
1067
|
+
errors,
|
|
1068
|
+
writes,
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
// (5) Install. Parse-refuse BEFORE any mkdir (I1: an unparseable file must not be overwritten).
|
|
1072
|
+
//
|
|
1073
|
+
// TRANSACTION (round-2 C2): the read, the plan and the write happen inside the caller's critical
|
|
1074
|
+
// section — and the LIVE PROBES below deliberately do NOT. Holding a lock across a 300s model call
|
|
1075
|
+
// is how a holder outlives its own stale threshold; the probes mutate nothing shared, so they need
|
|
1076
|
+
// no exclusion.
|
|
1077
|
+
const planned = criticalSection(() => {
|
|
1078
|
+
const freshText = existsSync(paths.registry) ? readFileSync(paths.registry, 'utf8') : undefined;
|
|
1079
|
+
const freshManifest = existsSync(paths.manifest) ? parseCodexHookManifest(readFileSync(paths.manifest, 'utf8')) : undefined;
|
|
1080
|
+
const plan = planCodexHooks({ currentText: freshText, entries, manifest: freshManifest });
|
|
1081
|
+
if (!plan.ok)
|
|
1082
|
+
return { plan, wrote: false, freshText };
|
|
1083
|
+
mkdirSync(paths.helperDir, { recursive: true, mode: 0o700 });
|
|
1084
|
+
const helpers = generateCodexHelpers();
|
|
1085
|
+
writeHelperIfChanged(paths.vetoHelper, helpers.veto, writes);
|
|
1086
|
+
writeHelperIfChanged(paths.recallHelper, helpers.recall, writes);
|
|
1087
|
+
if (plan.plan.changed) {
|
|
1088
|
+
backupRegistry(paths, freshText, now, writes);
|
|
1089
|
+
atomicWrite(paths.registry, plan.plan.text);
|
|
1090
|
+
writes.push(paths.registry);
|
|
1091
|
+
}
|
|
1092
|
+
return { plan, wrote: plan.plan.changed, freshText };
|
|
1093
|
+
}).plan;
|
|
1094
|
+
if (!planned.ok) {
|
|
1095
|
+
return {
|
|
1096
|
+
...base,
|
|
1097
|
+
codexVersion,
|
|
1098
|
+
exitCode: 1,
|
|
1099
|
+
warnings,
|
|
1100
|
+
errors: [
|
|
1101
|
+
planned.error,
|
|
1102
|
+
`heal by hand: fix ${paths.registry} (or move it aside) and re-run — dz refuses to overwrite a registry it cannot read, because foreign entries would be lost`,
|
|
1103
|
+
],
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
// (6) LIVENESS: exit 127 is ALLOW to the runtime, so it must never be graded as installed (G-L).
|
|
1107
|
+
const live = options.liveness === false ? { status: 0, stderr: '' } : probeHookLiveness(entries[0].command, ALLOWED_PROBE_PAYLOAD);
|
|
1108
|
+
const executable = live.status === 0 || live.status === 2;
|
|
1109
|
+
if (!executable) {
|
|
1110
|
+
warnings.push(`install liveness probe FAILED: the emitted command exited ${String(live.status)} through \`${process.env['SHELL'] ?? '/bin/sh'} -lc\` (127 = interpreter not found). The entry is registered but NOT armed; resolved interpreter: ${nodePath}`);
|
|
1111
|
+
}
|
|
1112
|
+
// (7) TRUST: arm the entry unattended by writing codex's own key+hash into config.toml.
|
|
1113
|
+
// Both values are READ from `hooks/list` — `currentHash`'s preimage is internal to codex, so
|
|
1114
|
+
// a computed hash would arm nothing while reading like success (M0 spike §4).
|
|
1115
|
+
const trustResult = options.liveness === false
|
|
1116
|
+
? { trust: 'unknown', rows: [], warnings: [] }
|
|
1117
|
+
: armCodexHookTrust(paths, entries, writes);
|
|
1118
|
+
for (const w of trustResult.warnings)
|
|
1119
|
+
warnings.push(w);
|
|
1120
|
+
const trustKeys = {};
|
|
1121
|
+
for (const row of trustResult.rows)
|
|
1122
|
+
trustKeys[row.id] = row.key;
|
|
1123
|
+
const manifestText = `${JSON.stringify(buildCodexHookManifest({ entries, paths, codexVersion, writtenAt: now, nodePath, trustKeys }), null, 2)}\n`;
|
|
1124
|
+
// R3-5: the manifest is shared state — it is what `--remove` reads to decide which entries are
|
|
1125
|
+
// OURS — so its write is guarded too. It gets its own SHORT section rather than joining the
|
|
1126
|
+
// registry transaction, because its content depends on trust keys that only exist after the live
|
|
1127
|
+
// `hooks/list` query; folding it into the first section would drag that probe back under the lock,
|
|
1128
|
+
// which is exactly the CRITICAL the previous round closed. Two short sections, no long hold.
|
|
1129
|
+
//
|
|
1130
|
+
// R4-3: section two REVALIDATES before it writes. Round 3 wrote a manifest computed in section one,
|
|
1131
|
+
// which meant a remover that won the window in between had its removal partially undone: the
|
|
1132
|
+
// registry said "no dz entries", the manifest said "here are dz entries", and `--remove` reads the
|
|
1133
|
+
// manifest to decide what is ours. Recompute from what is on disk NOW; if our entries are gone,
|
|
1134
|
+
// write NOTHING and report the state honestly.
|
|
1135
|
+
const manifestOutcome = criticalSection(() => {
|
|
1136
|
+
const nowText = existsSync(paths.registry) ? readFileSync(paths.registry, 'utf8') : undefined;
|
|
1137
|
+
const nowDrift = diffCodexHooks(nowText, entries, undefined);
|
|
1138
|
+
if (!nowDrift.installed) {
|
|
1139
|
+
return { wrote: false, drift: nowDrift };
|
|
1140
|
+
}
|
|
1141
|
+
atomicWrite(paths.manifest, manifestText);
|
|
1142
|
+
writes.push(paths.manifest);
|
|
1143
|
+
return { wrote: true, drift: nowDrift };
|
|
1144
|
+
});
|
|
1145
|
+
if (!manifestOutcome.wrote) {
|
|
1146
|
+
warnings.push('the registry no longer carries this install\u2019s entries — a concurrent remover won the window between the ' +
|
|
1147
|
+
'registry transaction and the manifest write, so NO manifest was written (a manifest describing entries that are ' +
|
|
1148
|
+
'not there is what `--remove` would later act on). Re-run the install if you want the hooks back.');
|
|
1149
|
+
}
|
|
1150
|
+
const drift = manifestOutcome.drift;
|
|
1151
|
+
const installed = drift.installed;
|
|
1152
|
+
const armedState = installed && executable && trustResult.trust === 'trusted';
|
|
1153
|
+
// The install is not finished when the file is written — it is finished when the guard has been
|
|
1154
|
+
// WITNESSED blocking (ADR-002, finding 1). Probing an install that is already known-broken would
|
|
1155
|
+
// spend a live model call to re-learn what the liveness probe just said, so it is gated on
|
|
1156
|
+
// `armedState`.
|
|
1157
|
+
const verification = armedState
|
|
1158
|
+
? verifyStage(options, {
|
|
1159
|
+
paths,
|
|
1160
|
+
probedCodexVersion: codexVersion,
|
|
1161
|
+
recordedCodexVersion: codexVersion,
|
|
1162
|
+
...(trustResult.rowStatus !== undefined ? { trustStatus: trustResult.rowStatus } : {}),
|
|
1163
|
+
warnings,
|
|
1164
|
+
})
|
|
1165
|
+
: { result: null, declined: verifyPlan(options).declined };
|
|
1166
|
+
const exitCode = armedState
|
|
1167
|
+
? verification.result !== null
|
|
1168
|
+
? verifyExitCode(verification.result)
|
|
1169
|
+
: verification.declined
|
|
1170
|
+
? 3
|
|
1171
|
+
: 0
|
|
1172
|
+
: 1;
|
|
1173
|
+
return {
|
|
1174
|
+
codexHome,
|
|
1175
|
+
registryPath: paths.registry,
|
|
1176
|
+
installed,
|
|
1177
|
+
executable,
|
|
1178
|
+
written: planned.plan.changed || writes.length > 0,
|
|
1179
|
+
removed: 0,
|
|
1180
|
+
foreignPreserved: planned.plan.foreignPreserved,
|
|
1181
|
+
unattributable: planned.plan.unattributable,
|
|
1182
|
+
drift: drift.drifted,
|
|
1183
|
+
trust: trustResult.trust,
|
|
1184
|
+
codexVersion,
|
|
1185
|
+
verify: verification.result,
|
|
1186
|
+
verified: verification.result !== null && isReadyVerdict(verification.result),
|
|
1187
|
+
ready: armedState && verification.result !== null && isReadyVerdict(verification.result),
|
|
1188
|
+
exitCode,
|
|
1189
|
+
warnings,
|
|
1190
|
+
errors,
|
|
1191
|
+
writes,
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
/* -------------------------------------------------------------------------- */
|
|
1195
|
+
/* The LIVE veto probe (ADR-002 §Decision, independent-review finding 1) */
|
|
1196
|
+
/* -------------------------------------------------------------------------- */
|
|
1197
|
+
/**
|
|
1198
|
+
* The forbidden action the probe asks Codex to run. It is the ONE rule this leg ships
|
|
1199
|
+
* (`ssh-explicit-auth-weakening`, ADR-005) with a nonce-scoped sentinel appended, so the two halves
|
|
1200
|
+
* of ADR-002's evidence are produced by a single command: the block MESSAGE and the missing SIDE
|
|
1201
|
+
* EFFECT. The ssh call itself targets a closed local port and can never reach a real host.
|
|
1202
|
+
*/
|
|
1203
|
+
function forbiddenProbeCommand(sentinel, nonce) {
|
|
1204
|
+
return ('ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no -o BatchMode=yes ' +
|
|
1205
|
+
`-o ConnectTimeout=1 -p 65533 nobody@127.0.0.1 true ; echo ${nonce} > "${sentinel}"`);
|
|
1206
|
+
}
|
|
1207
|
+
/** This package's own root — the probe workspace links it so the helper can load the policy. */
|
|
1208
|
+
function harnessCoreRoot() {
|
|
1209
|
+
return dirname(dirname(fileURLToPath(import.meta.url)));
|
|
1210
|
+
}
|
|
1211
|
+
/**
|
|
1212
|
+
* Drive ONE live, NON-bypassed veto probe through `codex exec` and classify what it produced.
|
|
1213
|
+
*
|
|
1214
|
+
* This is the half the shipped CLI was missing: `--verify` and `--project` were accepted and
|
|
1215
|
+
* dropped, `classifyVetoProbe` was never called from any production path, and `ready` printed off
|
|
1216
|
+
* file presence plus a trust row (independent review, finding 1 — CRITICAL). A registry entry is
|
|
1217
|
+
* not a guard; only a witnessed block is.
|
|
1218
|
+
*
|
|
1219
|
+
* Fail-closed by construction:
|
|
1220
|
+
* - `--dangerously-bypass-hook-trust` is NEVER passed (`bypassedTrust: false` is a fact here, not a
|
|
1221
|
+
* parameter): a bypassed run proves the helper body works and nothing about the installed state.
|
|
1222
|
+
* - stdin is `/dev/null` (node opens `/dev/null` for an `'ignore'` stdio slot) — the 2026-07-10
|
|
1223
|
+
* codex-exec stdin lesson.
|
|
1224
|
+
* - Every way the run can fail to produce evidence — no binary, a dead invocation, a timeout, an
|
|
1225
|
+
* unstattable sentinel — reaches `inconclusive`, never `armed`.
|
|
1226
|
+
*/
|
|
1227
|
+
export function runCodexVetoProbe(options) {
|
|
1228
|
+
const notes = [];
|
|
1229
|
+
const nonce = `dzverify-${randomBytes(6).toString('hex')}`;
|
|
1230
|
+
const timeoutMs = options.timeoutMs ?? 300_000;
|
|
1231
|
+
// (1) The workspace. The veto helper is inert outside an opted-in `.dz` project and only BLOCKS
|
|
1232
|
+
// under an explicit `hooks.shellVeto: "block"` (ADR-004 consent). A probe therefore needs a
|
|
1233
|
+
// consenting workspace; dz builds a hermetic one rather than editing the user's config.
|
|
1234
|
+
let workspace;
|
|
1235
|
+
let ephemeral = false;
|
|
1236
|
+
const explicit = options.project === undefined ? undefined : resolvePath(options.project);
|
|
1237
|
+
if (explicit !== undefined && vetoModeOf(explicit) === 'block') {
|
|
1238
|
+
workspace = explicit;
|
|
1239
|
+
notes.push(`probing in ${explicit} — it is an opted-in dz project in block mode`);
|
|
1240
|
+
}
|
|
1241
|
+
else {
|
|
1242
|
+
if (explicit !== undefined) {
|
|
1243
|
+
notes.push(`--project ${explicit} is not an opted-in dz project in \`hooks.shellVeto: "block"\` mode — probing in a hermetic workspace instead (dz never edits a project's consent to make its own check pass)`);
|
|
1244
|
+
}
|
|
1245
|
+
workspace = mkdtempSync(join(tmpdir(), 'dz-veto-probe-'));
|
|
1246
|
+
ephemeral = true;
|
|
1247
|
+
mkdirSync(join(workspace, '.dz'), { recursive: true });
|
|
1248
|
+
writeFileSync(join(workspace, '.dz', 'config.json'), '{"hooks":{"shellVeto":"block"}}\n');
|
|
1249
|
+
try {
|
|
1250
|
+
mkdirSync(join(workspace, 'node_modules', '@dzhechkov'), { recursive: true });
|
|
1251
|
+
symlinkSync(harnessCoreRoot(), join(workspace, 'node_modules', '@dzhechkov', 'harness-core'), 'dir');
|
|
1252
|
+
}
|
|
1253
|
+
catch (err) {
|
|
1254
|
+
notes.push(`could not link harness-core into the probe workspace: ${String(err.message)}`);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
const sentinel = join(workspace, `PROBE-SENTINEL-${nonce}`);
|
|
1258
|
+
rmSync(sentinel, { force: true });
|
|
1259
|
+
const command = forbiddenProbeCommand(sentinel, nonce);
|
|
1260
|
+
// (2) The run. `--skip-git-repo-check` because the hermetic workspace is not a repo;
|
|
1261
|
+
// `--sandbox workspace-write` so the sentinel CAN be written when nothing blocks it — a
|
|
1262
|
+
// sandbox that forbids the write would forge an `armed` out of a sandbox denial.
|
|
1263
|
+
const args = ['exec', '--skip-git-repo-check', '--sandbox', 'workspace-write'];
|
|
1264
|
+
if (options.model !== undefined && options.model !== '')
|
|
1265
|
+
args.push('-m', options.model);
|
|
1266
|
+
args.push(`Run this exact shell command, verbatim, with sh -c: ${command}`);
|
|
1267
|
+
const run = spawnSync('codex', args, {
|
|
1268
|
+
cwd: workspace,
|
|
1269
|
+
encoding: 'utf8',
|
|
1270
|
+
timeout: timeoutMs,
|
|
1271
|
+
stdio: ['ignore', 'pipe', 'pipe'], // stdin = /dev/null
|
|
1272
|
+
env: { ...process.env, CODEX_HOME: options.paths.codexHome },
|
|
1273
|
+
});
|
|
1274
|
+
const transcript = `${run.stdout ?? ''}${run.stderr ?? ''}`;
|
|
1275
|
+
const timedOut = run.error?.code === 'ETIMEDOUT' || run.signal === 'SIGTERM';
|
|
1276
|
+
const ran = run.error === undefined || timedOut;
|
|
1277
|
+
if (run.error !== undefined && !timedOut)
|
|
1278
|
+
notes.push(`codex exec did not run: ${String(run.error.message)}`);
|
|
1279
|
+
// (3) The sentinel, stat'ed — `null` when we could not look, which is NOT the same as absent.
|
|
1280
|
+
const sentinelStat = statSentinelPresence(sentinel);
|
|
1281
|
+
const sentinelPresent = sentinelStat.present;
|
|
1282
|
+
if (sentinelStat.error !== undefined)
|
|
1283
|
+
notes.push(`could not stat the sentinel: ${sentinelStat.error}`);
|
|
1284
|
+
const shellAttempted = /\/bin\/(?:ba)?sh -l?c/.test(transcript) ||
|
|
1285
|
+
transcript.includes('Command blocked by PreToolUse hook') ||
|
|
1286
|
+
transcript.includes('DZ-VETO');
|
|
1287
|
+
const evidence = {
|
|
1288
|
+
transcript,
|
|
1289
|
+
nonce,
|
|
1290
|
+
sentinelPresent,
|
|
1291
|
+
shellAttempted,
|
|
1292
|
+
bypassedTrust: false,
|
|
1293
|
+
ran,
|
|
1294
|
+
exitCode: run.status,
|
|
1295
|
+
timedOut,
|
|
1296
|
+
...(options.trustStatus !== undefined ? { trustStatus: options.trustStatus } : {}),
|
|
1297
|
+
...(options.recordedCodexVersion !== undefined ? { recordedCodexVersion: options.recordedCodexVersion } : {}),
|
|
1298
|
+
...(options.probedCodexVersion !== undefined ? { probedCodexVersion: options.probedCodexVersion } : {}),
|
|
1299
|
+
};
|
|
1300
|
+
const result = classifyVetoProbe(evidence);
|
|
1301
|
+
rmSync(sentinel, { force: true });
|
|
1302
|
+
if (ephemeral)
|
|
1303
|
+
rmSync(workspace, { recursive: true, force: true });
|
|
1304
|
+
return { evidence, result, workspace, command, notes };
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Is the sentinel there? `true` / `false` / **`null` when we could not tell**.
|
|
1308
|
+
*
|
|
1309
|
+
* `existsSync` answers `false` for BOTH "it is not there" and "I could not look" — it swallows
|
|
1310
|
+
* EACCES, ENOTDIR, ELOOP and every I/O error into the same word that means "the command was
|
|
1311
|
+
* blocked" (fix round 2, R2-4). Only ENOENT is an established ABSENCE; every other errno is a
|
|
1312
|
+
* failed observation and must reach `inconclusive`.
|
|
1313
|
+
*/
|
|
1314
|
+
export function statSentinelPresence(path) {
|
|
1315
|
+
try {
|
|
1316
|
+
statSync(path);
|
|
1317
|
+
return { present: true };
|
|
1318
|
+
}
|
|
1319
|
+
catch (err) {
|
|
1320
|
+
const code = err.code;
|
|
1321
|
+
if (code === 'ENOENT')
|
|
1322
|
+
return { present: false };
|
|
1323
|
+
return { present: null, error: `${String(code ?? 'unknown')}: ${String(err.message)}` };
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
/** The project's veto mode, read the way the helper reads it. Never throws. */
|
|
1327
|
+
function vetoModeOf(projectRoot) {
|
|
1328
|
+
try {
|
|
1329
|
+
if (!statSync(join(projectRoot, '.dz')).isDirectory())
|
|
1330
|
+
return 'warn';
|
|
1331
|
+
const cfg = JSON.parse(readFileSync(join(projectRoot, '.dz', 'config.json'), 'utf8'));
|
|
1332
|
+
const mode = cfg?.hooks?.shellVeto;
|
|
1333
|
+
return mode === 'block' || mode === 'off' ? mode : 'warn';
|
|
1334
|
+
}
|
|
1335
|
+
catch {
|
|
1336
|
+
return 'warn';
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
/** A synthetic ALLOWED PreToolUse payload — the liveness probe must never trigger a real policy hit. */
|
|
1340
|
+
const ALLOWED_PROBE_PAYLOAD = JSON.stringify({
|
|
1341
|
+
hook_event_name: 'PreToolUse',
|
|
1342
|
+
tool_name: 'Bash',
|
|
1343
|
+
tool_input: { command: 'true' },
|
|
1344
|
+
cwd: '/nonexistent-dz-liveness-probe',
|
|
1345
|
+
});
|
|
1346
|
+
function atomicWrite(path, text) {
|
|
1347
|
+
const tmp = `${path}.tmp-${process.pid}`;
|
|
1348
|
+
writeFileSync(tmp, text, { mode: 0o600 });
|
|
1349
|
+
renameSync(tmp, path);
|
|
1350
|
+
}
|
|
1351
|
+
/** 0600: the helpers are invoked as `node <path>`, never executed directly (AM-35c). */
|
|
1352
|
+
function writeHelperIfChanged(path, body, writes) {
|
|
1353
|
+
const current = existsSync(path) ? readFileSync(path, 'utf8') : undefined;
|
|
1354
|
+
if (current === body)
|
|
1355
|
+
return; // byte-idempotence: no change ⇒ no write ⇒ trust survives (FR-2)
|
|
1356
|
+
atomicWrite(path, body);
|
|
1357
|
+
writes.push(path);
|
|
1358
|
+
}
|
|
1359
|
+
function backupRegistry(paths, currentText, now, writes) {
|
|
1360
|
+
if (currentText === undefined)
|
|
1361
|
+
return;
|
|
1362
|
+
const backup = `${paths.registry}.bak-${now.replace(/[:.]/g, '-')}`;
|
|
1363
|
+
writeFileSync(backup, currentText, { mode: 0o600 });
|
|
1364
|
+
writes.push(backup);
|
|
1365
|
+
pruneBackups(paths.codexHome, 'hooks.json.bak-', 3);
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Ask the runtime which of OUR entries it sees, then persist trust for exactly those.
|
|
1369
|
+
*
|
|
1370
|
+
* Matching is on the exact emitted command string, so a third party's entry can never inherit dz's
|
|
1371
|
+
* trust write. A failure here is a WARNING, never an install failure: the registry is written and
|
|
1372
|
+
* the user can approve interactively (the `ARMED = NO` branch, AM-17 — both branches ship).
|
|
1373
|
+
*/
|
|
1374
|
+
function armCodexHookTrust(paths, entries, writes) {
|
|
1375
|
+
const listed = listCodexHooks(paths.codexHome);
|
|
1376
|
+
if (listed === null) {
|
|
1377
|
+
return {
|
|
1378
|
+
trust: 'unknown',
|
|
1379
|
+
rows: [],
|
|
1380
|
+
warnings: [
|
|
1381
|
+
'could not read the codex `hooks/list` RPC — hook trust could not be recorded. ARMED = NO: open an interactive Codex session and approve the two dz hooks, then re-run `dz hooks-sync --target codex --verify`.',
|
|
1382
|
+
],
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
const own = selectOwnHookMetadata(listed, entries, { registryPath: paths.registry });
|
|
1386
|
+
if (own.length !== entries.length) {
|
|
1387
|
+
return {
|
|
1388
|
+
trust: 'trust-pending',
|
|
1389
|
+
rows: own.map((o) => ({ id: o.id, key: o.meta.key })),
|
|
1390
|
+
warnings: [`codex reports ${own.length} of ${entries.length} dz entries it can attribute to ${paths.registry} — trust recorded only for the ones it sees (an ambiguous or foreign-sourced row is refused, never adopted)`],
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
const configText = existsSync(paths.configToml) ? readFileSync(paths.configToml, 'utf8') : '';
|
|
1394
|
+
const upserted = upsertTrustBlock(configText, own.map((o) => ({ key: o.meta.key, trustedHash: o.meta.currentHash })));
|
|
1395
|
+
if (!upserted.ok) {
|
|
1396
|
+
// A damaged fence is a REFUSAL, not a rewrite: the alternative eats the user's `[projects."…"]`
|
|
1397
|
+
// trust rows on the next sync (finding 9).
|
|
1398
|
+
return { trust: 'trust-pending', rows: own.map((o) => ({ id: o.id, key: o.meta.key })), warnings: [upserted.error] };
|
|
1399
|
+
}
|
|
1400
|
+
if (upserted.text !== configText) {
|
|
1401
|
+
atomicWrite(paths.configToml, upserted.text);
|
|
1402
|
+
writes.push(paths.configToml);
|
|
1403
|
+
}
|
|
1404
|
+
// Re-read: the only honest confirmation that the write armed anything is the runtime's own answer.
|
|
1405
|
+
const after = listCodexHooks(paths.codexHome);
|
|
1406
|
+
const confirmed = after === null ? [] : selectOwnHookMetadata(after, entries, { registryPath: paths.registry });
|
|
1407
|
+
const allTrusted = confirmed.length === entries.length && confirmed.every((c) => c.meta.trustStatus === 'trusted' || c.meta.trustStatus === 'managed');
|
|
1408
|
+
return {
|
|
1409
|
+
trust: allTrusted ? 'trusted' : 'trust-pending',
|
|
1410
|
+
rows: own.map((o) => ({ id: o.id, key: o.meta.key })),
|
|
1411
|
+
...(confirmed[0] !== undefined ? { rowStatus: confirmed[0].meta.trustStatus } : {}),
|
|
1412
|
+
warnings: allTrusted
|
|
1413
|
+
? []
|
|
1414
|
+
: ['dz wrote the hook trust rows but codex still reports the entries as untrusted — approve them in an interactive session'],
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
/**
|
|
1418
|
+
* Drive `codex app-server` over stdio for one `hooks/list` call.
|
|
1419
|
+
*
|
|
1420
|
+
* MEASURED headless (M0 spike, probe 1): `initialize` → `initialized` → `hooks/list` answers with
|
|
1421
|
+
* `key`, `currentHash`, `trustStatus` and `sourcePath` for every discovered entry, no TUI involved.
|
|
1422
|
+
*/
|
|
1423
|
+
export function listCodexHooks(codexHome, cwd = process.cwd()) {
|
|
1424
|
+
const script = [
|
|
1425
|
+
"const{spawn}=require('node:child_process');",
|
|
1426
|
+
"const p=spawn('codex',['app-server'],{env:{...process.env,CODEX_HOME:process.argv[1]},stdio:['pipe','pipe','ignore']});",
|
|
1427
|
+
"let b='';const send=o=>p.stdin.write(JSON.stringify(o)+'\\n');",
|
|
1428
|
+
"const bail=()=>{try{p.kill()}catch(e){};process.stdout.write('null');process.exit(0)};",
|
|
1429
|
+
"const t=setTimeout(bail,45000);",
|
|
1430
|
+
"p.on('error',bail);",
|
|
1431
|
+
"p.stdout.on('data',d=>{b+=d.toString();let i;while((i=b.indexOf('\\n'))>=0){const l=b.slice(0,i);b=b.slice(i+1);if(!l.trim())continue;let m;try{m=JSON.parse(l)}catch(e){continue}",
|
|
1432
|
+
"if(m.id===1){send({jsonrpc:'2.0',method:'initialized'});send({jsonrpc:'2.0',id:2,method:'hooks/list',params:{cwds:[process.argv[2]]}})}",
|
|
1433
|
+
"else if(m.id===2){clearTimeout(t);process.stdout.write(JSON.stringify(m.result&&m.result.data?m.result.data:null));try{p.kill()}catch(e){};process.exit(0)}}});",
|
|
1434
|
+
"send({jsonrpc:'2.0',id:1,method:'initialize',params:{clientInfo:{name:'dz',version:'1.0.0'}}});",
|
|
1435
|
+
].join('');
|
|
1436
|
+
try {
|
|
1437
|
+
const out = execFileSync(process.execPath, ['-e', script, codexHome, cwd], {
|
|
1438
|
+
encoding: 'utf8',
|
|
1439
|
+
timeout: 60_000,
|
|
1440
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
1441
|
+
});
|
|
1442
|
+
const data = JSON.parse(out);
|
|
1443
|
+
if (data === null || !Array.isArray(data))
|
|
1444
|
+
return null;
|
|
1445
|
+
return data.flatMap((entry) => entry.hooks ?? []);
|
|
1446
|
+
}
|
|
1447
|
+
catch {
|
|
1448
|
+
return null;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
/** Newest recall-usage row timestamp and whether any row carries `runtime: 'codex'`. Never throws. */
|
|
1452
|
+
function newestRecallUsageRuntime(logPath) {
|
|
1453
|
+
try {
|
|
1454
|
+
if (!existsSync(logPath))
|
|
1455
|
+
return { hasCodexRow: false };
|
|
1456
|
+
const lines = readFileSync(logPath, 'utf-8').split('\n');
|
|
1457
|
+
let newest;
|
|
1458
|
+
let hasCodexRow = false;
|
|
1459
|
+
for (const line of lines) {
|
|
1460
|
+
if (line.trim() === '')
|
|
1461
|
+
continue;
|
|
1462
|
+
try {
|
|
1463
|
+
const rec = JSON.parse(line);
|
|
1464
|
+
if (rec.runtime === 'codex' && typeof rec.ts === 'string') {
|
|
1465
|
+
hasCodexRow = true;
|
|
1466
|
+
if (newest === undefined || rec.ts > newest)
|
|
1467
|
+
newest = rec.ts;
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
catch { /* a malformed line is counted elsewhere */ }
|
|
1471
|
+
}
|
|
1472
|
+
return newest === undefined ? { hasCodexRow } : { newest, hasCodexRow };
|
|
1473
|
+
}
|
|
1474
|
+
catch {
|
|
1475
|
+
return { hasCodexRow: false };
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
624
1478
|
//# sourceMappingURL=operations.js.map
|