cocheck 0.4.0 → 0.4.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/README.md +17 -3
- package/dist/agent-transcripts.js +15 -12
- package/dist/attribution/evidence.js +2 -1
- package/dist/attribution/reconstruct.js +19 -0
- package/dist/attribution/tag.js +3 -3
- package/dist/build-info.json +1 -1
- package/dist/cli.js +31 -11
- package/dist/connector/export-view.js +1 -1
- package/dist/coverage.js +5 -3
- package/dist/credit-guard.js +59 -54
- package/dist/harness-cmd/create.js +76 -0
- package/dist/harness-cmd/index.js +19 -0
- package/dist/harness-cmd/record.js +327 -0
- package/dist/harness-cmd/scrub.js +25 -0
- package/dist/harness-cmd/test.js +318 -0
- package/dist/harnesses/README.md +5 -0
- package/dist/harnesses/claude/cocheck-harness.json +344 -0
- package/dist/harnesses/codex/cocheck-harness.json +212 -0
- package/dist/harnesses/copilot/cocheck-harness.json +296 -0
- package/dist/{copilot-helpers.js → helper-linker.js} +43 -32
- package/dist/hook-adapter.js +287 -63
- package/dist/hook-cli.js +73 -36
- package/dist/hook-journal.js +40 -12
- package/dist/hosts/claude.js +23 -159
- package/dist/hosts/codex.js +41 -81
- package/dist/hosts/compile.js +275 -0
- package/dist/hosts/copilot.js +7 -162
- package/dist/hosts/extras.js +55 -0
- package/dist/hosts/harnesses.js +66 -0
- package/dist/hosts/index.js +176 -8
- package/dist/hosts/install-block.js +332 -0
- package/dist/hosts/manifest.js +372 -0
- package/dist/hosts/shared.js +21 -0
- package/dist/hosts/tool-classes.js +6 -0
- package/dist/hosts/types.js +1 -0
- package/dist/install.js +69 -22
- package/dist/ledger.js +11 -0
- package/dist/normalize.js +33 -9
- package/dist/open-pick.js +5 -3
- package/dist/patch-secrets.js +11 -11
- package/dist/review-server.js +2 -2
- package/dist/timeline/attribution.js +2 -2
- package/dist/timeline/describe.js +20 -17
- package/dist/timeline/load.js +2 -2
- package/dist/timeline/rail/assets/review.js +1 -1
- package/dist/timeline/rail/model.js +8 -8
- package/dist/timeline/read-signal.js +4 -4
- package/dist/timeline/render/view-v1.js +2 -13
- package/dist/timeline/runs.js +9 -9
- package/dist/timeline/timeline.js +8 -8
- package/dist/timeline/write-signal.js +4 -3
- package/package.json +2 -2
- package/public-kit/harness/GUIDE.md +81 -0
- package/public-kit/harness/README.md +10 -0
- package/public-kit/harness/cases/claude/shell-writes-file.json +120 -0
- package/public-kit/harness/cases/codex/apply-patch-writes-files.json +177 -0
- package/public-kit/harness/cases/codex/helper-writes-file.json +160 -0
- package/public-kit/harness/cases/codex/shell-writes-and-fails.json +110 -0
- package/public-kit/harness/cases/copilot/camel-case-patch-and-failure.json +126 -0
- package/public-kit/harness/cases/copilot/helper-writes-file.json +209 -0
- package/public-kit/harness/cases/copilot/vscode-helper-writes-file.json +236 -0
- package/public-kit/harness/examples/toyagent/cases/write-notes.json +142 -0
- package/public-kit/harness/examples/toyagent/cocheck-harness.json +47 -0
- package/public-kit/harness/examples/toyagent/recordings/payloads.jsonl +8 -0
- package/public-kit/harness/harnesses/antigravity/README.md +32 -0
- package/public-kit/harness/harnesses/antigravity/cases/failed-edit.json +99 -0
- package/public-kit/harness/harnesses/antigravity/cases/helper-writes-file.json +270 -0
- package/public-kit/harness/harnesses/antigravity/cases/shell-ok-fail-and-denied.json +211 -0
- package/public-kit/harness/harnesses/antigravity/cases/write-then-edit.json +191 -0
- package/public-kit/harness/harnesses/antigravity/cocheck-harness.json +62 -0
- package/public-kit/harness/harnesses/antigravity/recordings/payloads.jsonl +63 -0
- package/public-kit/harness/harnesses/cursor/README.md +40 -0
- package/public-kit/harness/harnesses/cursor/cases/editor-write-edit-shell-helper.json +359 -0
- package/public-kit/harness/harnesses/cursor/cases/read-then-write-one-call-id.json +159 -0
- package/public-kit/harness/harnesses/cursor/cocheck-harness.json +67 -0
- package/public-kit/harness/harnesses/cursor/recordings/payloads.jsonl +28 -0
- package/public-kit/harness/scaffold/README.md +42 -0
- package/public-kit/harness/scaffold/cocheck-harness.json +72 -0
- package/public-kit/harness/scaffold/recordings/.gitkeep +0 -0
- package/public-kit/harness/spec/v1.md +286 -0
- package/scripts/hook-launch.sh +1 -1
package/dist/hook-cli.js
CHANGED
|
@@ -2,49 +2,54 @@
|
|
|
2
2
|
// the raw stdin bytes go to the hook journal (hook-journal.ts) before the host argument, the folder or the JSON are checked, and any later
|
|
3
3
|
// failure writes a marker linked to that record. The contract toward the host: exit 0, or exit 1 on any failure (never 2: exit 2 would
|
|
4
4
|
// block the host's tool call); stdout stays empty except for the context text on a recorded UserPromptSubmit (see promptContext)
|
|
5
|
-
// and, on a recorded
|
|
5
|
+
// and, on a recorded shell PreToolUse of a host with an argv tag, the tag (see tagOutput and src/attribution/tag.ts). A journal failure is one line on stderr and changes nothing else.
|
|
6
6
|
import { scrubPayloadBytes } from "./patch-secrets.js";
|
|
7
|
-
import { appendFileSync } from "node:fs";
|
|
7
|
+
import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { homedir } from "node:os";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { HOME_REFUSAL, isUnsafeTaskFolder, userHomeDir } from "./platform/index.js";
|
|
11
11
|
import { handleEvent, hookClientName, markTrackingStopped, parkedOpsOf, parseOutsideWatching, resolveAdapterHome } from "./hook-adapter.js";
|
|
12
12
|
import { beforeSideOfCall, callTimesOfCall, JOURNAL_STEM, journalBeforeSide, journalDone, journalEvent, journalFailure, noteDegraded, sessionKeyOfBytes } from "./hook-journal.js";
|
|
13
13
|
import { markNotChecked, reconcileSession } from "./coverage.js";
|
|
14
|
-
import { allProfiles,
|
|
14
|
+
import { allProfiles, findProfile, hasCapability, isHostKey, loadOutsiderHarnesses, outsiderHarnessDir, profileWithExtra, runsOtherHostsHook } from "./hosts/index.js";
|
|
15
15
|
import { openLedger } from "./ledger.js";
|
|
16
16
|
import { normalize } from "./normalize.js";
|
|
17
17
|
import { readRegistry, RegistryError, resolveFolder } from "./registry.js";
|
|
18
18
|
import { writeOpenRecord } from "./open-pick.js";
|
|
19
|
-
import {
|
|
19
|
+
import { isShellTool } from "./credit-guard.js";
|
|
20
20
|
import { isOpenCommand, setTracking, trackCommand, trackingOf } from "./tracking.js";
|
|
21
21
|
import { cliCommand, sessionContextText } from "./session-context.js";
|
|
22
|
-
import { helperGate, pruneHelperState } from "./
|
|
23
|
-
import { copilotRunsOtherHostsHook } from "./hosts/copilot.js";
|
|
22
|
+
import { helperGate, pruneHelperState } from "./helper-linker.js";
|
|
24
23
|
import { AFTER_SNAPSHOT_ACCEPT_MS, AfterNotTaken, httpLocalProcess } from "./connector/local-process.js";
|
|
25
24
|
import { recordNoSubject, recordNotTaken } from "./connector/after-gap.js";
|
|
26
25
|
import { answerIsError, beforeReadMsFor, loadCallTemplates, loadSubjectTemplates, MAX_CALL_ANSWER_BYTES, renderSubject } from "./connector/subjects.js";
|
|
27
26
|
import { DEFAULT_BEFORE_READ_MS } from "./connector/schema.js";
|
|
28
27
|
import { callShell, markSessionTagged, sessionReady, parseTagSetting, prepareSession, stripTag, tagCommand, tagsInMode } from "./attribution/tag.js";
|
|
29
28
|
/**
|
|
30
|
-
* The
|
|
29
|
+
* The Pre hook output that tags a shell call of a host with an argv tag (`argvTag.preOutput`: the whole input with the command
|
|
31
30
|
* tagged), or "" when the call is not tagged. No permission decision is returned: the call goes through the permission flow as it would.
|
|
32
31
|
*/
|
|
33
|
-
function tagOutput(raw, setting, env) {
|
|
34
|
-
|
|
32
|
+
function tagOutput(raw, host, permissionMode, setting, env) {
|
|
33
|
+
const profile = findProfile(host);
|
|
34
|
+
const tag = profile?.argvTag;
|
|
35
|
+
if (profile === undefined || tag === undefined || raw === null || typeof raw !== "object")
|
|
35
36
|
return "";
|
|
36
|
-
|
|
37
|
+
const f = profile.fields;
|
|
38
|
+
const eventName = raw[f.eventName];
|
|
39
|
+
if (typeof eventName !== "string" || profile.eventKinds[eventName] !== "tool-pre" || raw[f.toolName] !== tag.tool)
|
|
37
40
|
return "";
|
|
38
|
-
|
|
41
|
+
if (!tagsInMode(setting, permissionMode))
|
|
42
|
+
return "";
|
|
43
|
+
const input = raw[f.toolInput];
|
|
39
44
|
if (input === null || typeof input !== "object" || Array.isArray(input))
|
|
40
45
|
return "";
|
|
41
|
-
const shell = callShell(env);
|
|
46
|
+
const shell = callShell(env, tag.shellEnv);
|
|
42
47
|
if (shell === undefined)
|
|
43
48
|
return "";
|
|
44
|
-
const tagged = tagCommand(input.command, raw.
|
|
49
|
+
const tagged = tagCommand(input.command, raw[f.toolUseId], raw[f.agentId], shell);
|
|
45
50
|
if (tagged === null)
|
|
46
51
|
return "";
|
|
47
|
-
return
|
|
52
|
+
return tag.preOutput(eventName, { ...input, command: tagged });
|
|
48
53
|
}
|
|
49
54
|
const shellCommandOf = (input) => {
|
|
50
55
|
if (input === null || typeof input !== "object")
|
|
@@ -52,13 +57,17 @@ const shellCommandOf = (input) => {
|
|
|
52
57
|
const o = input;
|
|
53
58
|
return o.command ?? o.cmd;
|
|
54
59
|
};
|
|
55
|
-
/** A Post or failure payload carries the tagged command; the record keeps the command the agent wrote. */
|
|
56
|
-
function untag(raw) {
|
|
57
|
-
const
|
|
60
|
+
/** A Post or failure payload carries the tagged command; the record keeps the command the agent wrote. Only a host with an argv tag has a tagged command. */
|
|
61
|
+
function untag(raw, host) {
|
|
62
|
+
const profile = findProfile(host);
|
|
63
|
+
if (profile?.argvTag === undefined)
|
|
64
|
+
return raw;
|
|
65
|
+
const key = profile.fields.toolInput;
|
|
66
|
+
const cmd = raw?.[key]?.command;
|
|
58
67
|
if (typeof cmd !== "string")
|
|
59
68
|
return raw;
|
|
60
69
|
const plain = stripTag(cmd);
|
|
61
|
-
return plain === cmd ? raw : { ...raw,
|
|
70
|
+
return plain === cmd ? raw : { ...raw, [key]: { ...raw[key], command: plain } };
|
|
62
71
|
}
|
|
63
72
|
/**
|
|
64
73
|
* The task folder: `--folder`, else the folder the session was started in, else the host's folder variable (an unknown host gets the default host's), else the payload's `cwd` when
|
|
@@ -71,7 +80,7 @@ function taskFolder(argv, env, hostArg, bytes, started) {
|
|
|
71
80
|
// `cocheck track start` made the session's cwd its task folder.
|
|
72
81
|
if (started?.folder !== undefined)
|
|
73
82
|
return started.folder;
|
|
74
|
-
const install = (findProfile(hostArg) ??
|
|
83
|
+
const install = (findProfile(hostArg) ?? profileWithExtra("install-default")).install;
|
|
75
84
|
const fromEnv = install?.projectDirEnv === undefined ? undefined : env[install.projectDirEnv];
|
|
76
85
|
if (fromEnv)
|
|
77
86
|
return fromEnv;
|
|
@@ -85,6 +94,11 @@ function taskFolder(argv, env, hostArg, bytes, started) {
|
|
|
85
94
|
return undefined;
|
|
86
95
|
}
|
|
87
96
|
}
|
|
97
|
+
/** The `--event` argument of a hook command line (a host whose payload names no event is told it there). */
|
|
98
|
+
const eventArgOf = (argv) => {
|
|
99
|
+
const i = argv.indexOf("--event");
|
|
100
|
+
return i >= 0 ? argv[i + 1] : undefined;
|
|
101
|
+
};
|
|
88
102
|
/** The before-read wait when no manifest says otherwise (a matched connector's `beforeReadMs` replaces it, `beforeReadMsFor`). */
|
|
89
103
|
const BEFORE_SNAPSHOT_BUDGET_MS = DEFAULT_BEFORE_READ_MS;
|
|
90
104
|
/** The most the hook waits for the review process to accept an after-snapshot or file-capture request (it does the work after answering). */
|
|
@@ -262,6 +276,23 @@ const safeJson = (bytes) => {
|
|
|
262
276
|
};
|
|
263
277
|
/** Class-level wording for a marker: a JSON error's own message quotes the payload, so it is replaced. */
|
|
264
278
|
const markerText = (error) => (error instanceof SyntaxError ? "payload is not valid JSON" : error instanceof Error ? error.message : String(error));
|
|
279
|
+
/** The skipped-manifest lines for `cocheck status`, kept in the data home beside the other notes; the file is emptied when nothing is skipped. */
|
|
280
|
+
function noteSkippedHarnesses(home, skipped) {
|
|
281
|
+
if (home === undefined)
|
|
282
|
+
return;
|
|
283
|
+
try {
|
|
284
|
+
const file = path.join(home, "harness-skipped.txt");
|
|
285
|
+
if (skipped.length > 0) {
|
|
286
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
287
|
+
writeFileSync(file, skipped.map((l) => `${l}\n`).join(""), { mode: 0o600 });
|
|
288
|
+
}
|
|
289
|
+
else if (existsSync(file))
|
|
290
|
+
writeFileSync(file, "", { mode: 0o600 });
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
// a note that cannot be written changes nothing else
|
|
294
|
+
}
|
|
295
|
+
}
|
|
265
296
|
export async function runHook(run) {
|
|
266
297
|
const now = run.journalNow ?? Date.now;
|
|
267
298
|
let stderr = "";
|
|
@@ -279,6 +310,8 @@ export async function runHook(run) {
|
|
|
279
310
|
failure = error;
|
|
280
311
|
}
|
|
281
312
|
process.umask(0o077);
|
|
313
|
+
// The person's own harness manifests. One that does not load is skipped; no other host's hook is affected. It is noted after the tracking gate (nothing is written before it).
|
|
314
|
+
const skippedHarnesses = loadOutsiderHarnesses(outsiderHarnessDir(run.env, home));
|
|
282
315
|
const hostArg = run.argv[run.argv.indexOf("--host") + 1];
|
|
283
316
|
// The payload is read first: the tracking gate below needs the session id. Nothing is written before the gate.
|
|
284
317
|
const chunks = [];
|
|
@@ -296,8 +329,9 @@ export async function runHook(run) {
|
|
|
296
329
|
// a prune that cannot run changes nothing else
|
|
297
330
|
}
|
|
298
331
|
}
|
|
299
|
-
// Copilot also runs the hooks of a repo's `.claude/settings.json
|
|
300
|
-
|
|
332
|
+
// Copilot also runs the hooks of a repo's `.claude/settings.json`, and Cursor those of ~/.claude/settings.json; a run of another host's hook that such a host started
|
|
333
|
+
// records nothing (that host's own entry does). An outsider harness's fingerprint counts only while its own CoCheck hook is installed for the payload's folder.
|
|
334
|
+
if (home !== undefined && isHostKey(hostArg) && runsOtherHostsHook(hostArg, safeJson(bytes), { env: run.env, userHome: userHomeDir(run.env) }))
|
|
301
335
|
return { exitCode: 0, stderr, stdout: "" };
|
|
302
336
|
// The tracking gate. Every session starts untracked: nothing is journaled, recorded or injected until `cocheck track start` ran
|
|
303
337
|
// in it. The switch commands are recognised here, keyed by the hook's own session id, and are themselves never recorded. A payload
|
|
@@ -306,13 +340,13 @@ export async function runHook(run) {
|
|
|
306
340
|
let ev;
|
|
307
341
|
try {
|
|
308
342
|
const eventIdx = run.argv.indexOf("--event");
|
|
309
|
-
ev = normalize(hostArg, untag(JSON.parse(bytes.toString("utf8"))), eventIdx >= 0 ? run.argv[eventIdx + 1] : undefined);
|
|
343
|
+
ev = normalize(hostArg, untag(JSON.parse(bytes.toString("utf8")), hostArg), eventIdx >= 0 ? run.argv[eventIdx + 1] : undefined);
|
|
310
344
|
}
|
|
311
345
|
catch {
|
|
312
346
|
ev = undefined;
|
|
313
347
|
}
|
|
314
348
|
if (ev !== undefined && typeof ev.session === "string" && ev.session !== "") {
|
|
315
|
-
const verb =
|
|
349
|
+
const verb = isShellTool(ev.toolName, ev.host) && ev.kind !== "other" ? trackCommand(shellCommandOf(ev.toolInput)) : undefined;
|
|
316
350
|
if (verb !== undefined) {
|
|
317
351
|
if (ev.kind === "tool-pre" && verb !== "status") {
|
|
318
352
|
try {
|
|
@@ -342,7 +376,7 @@ export async function runHook(run) {
|
|
|
342
376
|
return { exitCode: 0, stderr, stdout: "" };
|
|
343
377
|
}
|
|
344
378
|
// `cocheck open` names no session; the hook writes who asked, before the tracking check so it also fires after `track stop`.
|
|
345
|
-
if (ev.kind === "tool-pre" &&
|
|
379
|
+
if (ev.kind === "tool-pre" && isShellTool(ev.toolName, ev.host) && isOpenCommand(shellCommandOf(ev.toolInput))) {
|
|
346
380
|
try {
|
|
347
381
|
writeOpenRecord(home, hostArg, ev.session, (run.journalNow ?? Date.now)());
|
|
348
382
|
}
|
|
@@ -352,7 +386,7 @@ export async function runHook(run) {
|
|
|
352
386
|
}
|
|
353
387
|
started = trackingOf(home, hostArg, ev.session);
|
|
354
388
|
if (hasCapability(hostArg, "helperSessions")) {
|
|
355
|
-
// A helper's calls under a session id of their own are linked to their main session, or held until they are (src/
|
|
389
|
+
// A helper's calls under a session id of their own are linked to their main session, or held until they are (src/helper-linker.ts).
|
|
356
390
|
const eventName = typeof ev.eventName === "string" ? ev.eventName : "";
|
|
357
391
|
const gate = await helperGate(home, started, ev, bytes, eventName, (run.journalNow ?? Date.now)());
|
|
358
392
|
if (gate.stop)
|
|
@@ -365,7 +399,7 @@ export async function runHook(run) {
|
|
|
365
399
|
stderr += again.stderr;
|
|
366
400
|
}
|
|
367
401
|
}
|
|
368
|
-
const sessionStart = hasCapability(hostArg, "argvTag") && ev.eventName ===
|
|
402
|
+
const sessionStart = hasCapability(hostArg, "argvTag") && ev.eventName === findProfile(hostArg)?.argvTag?.sessionStartEvent;
|
|
369
403
|
if (started === undefined && !sessionStart)
|
|
370
404
|
return { exitCode: 0, stderr, stdout: "" };
|
|
371
405
|
}
|
|
@@ -383,6 +417,7 @@ export async function runHook(run) {
|
|
|
383
417
|
failure = error;
|
|
384
418
|
}
|
|
385
419
|
}
|
|
420
|
+
noteSkippedHarnesses(home, skippedHarnesses);
|
|
386
421
|
const tagSetting = parseTagSetting(run.argv, run.env);
|
|
387
422
|
if (home !== undefined && failure === undefined && hasCapability(hostArg, "argvTag")) {
|
|
388
423
|
// SessionStart only sets the write hooks' environment for the session's Bash calls (CLAUDE_ENV_FILE); it records nothing.
|
|
@@ -393,15 +428,16 @@ export async function runHook(run) {
|
|
|
393
428
|
catch {
|
|
394
429
|
start = undefined;
|
|
395
430
|
}
|
|
396
|
-
|
|
397
|
-
|
|
431
|
+
const tagParams = findProfile(hostArg)?.argvTag;
|
|
432
|
+
if (tagParams !== undefined && start?.[findProfile(hostArg).fields.eventName] === tagParams.sessionStartEvent) {
|
|
433
|
+
const envFile = run.env[tagParams.envFileVar];
|
|
398
434
|
// The SessionStart payload carries no permission_mode (the hooks reference's SessionStart input lists none), and the mode can
|
|
399
435
|
// change mid-session, so the environment is set whenever the setting is not off. The hooks stay inert (no process walk, no
|
|
400
436
|
// record) until a Pre tags one of the session's calls and marks the session (markSessionTagged).
|
|
401
437
|
if (envFile && path.isAbsolute(envFile) && tagSetting !== "off") {
|
|
402
438
|
try {
|
|
403
439
|
const roots = [...(registered ?? []), taskFolder(run.argv, run.env, hostArg, bytes, started)].filter((f) => typeof f === "string");
|
|
404
|
-
appendFileSync(envFile, prepareSession(home, start.
|
|
440
|
+
appendFileSync(envFile, prepareSession(home, start[findProfile(hostArg).fields.session], roots, now()));
|
|
405
441
|
}
|
|
406
442
|
catch (error) {
|
|
407
443
|
stderr += `cocheck hook: could not set the write hooks' environment: ${error.code ?? "error"}\n`;
|
|
@@ -412,11 +448,11 @@ export async function runHook(run) {
|
|
|
412
448
|
}
|
|
413
449
|
if (home !== undefined) {
|
|
414
450
|
try {
|
|
415
|
-
ref = journalEvent(home, bytes, isHostKey(hostArg) ? hostArg : "unknown", now);
|
|
451
|
+
ref = journalEvent(home, bytes, isHostKey(hostArg) ? hostArg : "unknown", now, eventArgOf(run.argv));
|
|
416
452
|
}
|
|
417
453
|
catch (error) {
|
|
418
454
|
stderr += `cocheck hook: journal unavailable: ${error.code ?? "error"}\n`;
|
|
419
|
-
noteDegraded(home, error.code ?? "error", now, sessionKeyOfBytes(bytes));
|
|
455
|
+
noteDegraded(home, error.code ?? "error", now, sessionKeyOfBytes(bytes, isHostKey(hostArg) ? hostArg : "unknown", eventArgOf(run.argv)));
|
|
420
456
|
}
|
|
421
457
|
}
|
|
422
458
|
if (!isHostKey(hostArg)) {
|
|
@@ -426,19 +462,20 @@ export async function runHook(run) {
|
|
|
426
462
|
throw failure;
|
|
427
463
|
const folder = taskFolder(run.argv, run.env, hostArg, bytes, started);
|
|
428
464
|
if (!folder) {
|
|
429
|
-
|
|
465
|
+
const sources = allProfiles().flatMap((p) => [...(p.install?.projectDirEnv === undefined ? [] : [`${p.fullName ?? p.displayName} sets ${p.install.projectDirEnv}`]), ...(p.install?.folderFromPayloadCwd === true ? [`${p.displayName}'s payload carries a cwd`] : [])]);
|
|
466
|
+
throw new Error(`no task folder: pass --folder <dir> in the hook command (${sources.join("; ")})`);
|
|
430
467
|
}
|
|
431
468
|
const eventIdx = run.argv.indexOf("--event");
|
|
432
469
|
const parsed = JSON.parse(bytes.toString("utf8"));
|
|
433
|
-
const event = normalize(hostArg,
|
|
470
|
+
const event = normalize(hostArg, untag(parsed, hostArg), eventIdx >= 0 ? run.argv[eventIdx + 1] : undefined);
|
|
434
471
|
let tag = "";
|
|
435
472
|
if (event.kind === "tool-pre" && hasCapability(hostArg, "argvTag")) {
|
|
436
473
|
try {
|
|
437
474
|
// Only a session whose SessionStart set the write hooks' environment is tagged: a tag without hooks would read as observed.
|
|
438
|
-
tag = sessionReady(home, parsed.
|
|
475
|
+
tag = sessionReady(home, parsed[findProfile(hostArg).fields.session]) ? tagOutput(parsed, hostArg, event.extra.permissionMode, tagSetting, run.env) : "";
|
|
439
476
|
// The session is marked before the call is recorded as tagged: a call is never believed tagged unless its children will look.
|
|
440
477
|
if (tag !== "")
|
|
441
|
-
markSessionTagged(home, parsed.
|
|
478
|
+
markSessionTagged(home, parsed[findProfile(hostArg).fields.session]);
|
|
442
479
|
}
|
|
443
480
|
catch {
|
|
444
481
|
tag = "";
|
|
@@ -451,7 +488,7 @@ export async function runHook(run) {
|
|
|
451
488
|
}
|
|
452
489
|
catch (error) {
|
|
453
490
|
stderr += `cocheck hook: could not record the before side: ${error.code ?? "error"}\n`;
|
|
454
|
-
noteDegraded(home, error.code ?? "error", now, sessionKeyOfBytes(bytes));
|
|
491
|
+
noteDegraded(home, error.code ?? "error", now, sessionKeyOfBytes(bytes, isHostKey(hostArg) ? hostArg : "unknown", eventArgOf(run.argv)));
|
|
455
492
|
}
|
|
456
493
|
}
|
|
457
494
|
await handleEvent(event, { host: event.host, home: home, folder, outsideWatching: parseOutsideWatching(run.argv, run.env), now: run.now, fault: run.fault, attributionTag: tagSetting, taggedCall: tag !== "", ...(run.heldReplay === true ? { heldReplay: true } : {}) });
|
package/dist/hook-journal.js
CHANGED
|
@@ -8,6 +8,8 @@ import { createHash } from "node:crypto";
|
|
|
8
8
|
import { appendFileSync, chmodSync, mkdirSync, readFileSync } from "node:fs";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { scrubPayloadBytes } from "./patch-secrets.js";
|
|
11
|
+
import { isHostKey } from "./hosts/index.js";
|
|
12
|
+
import { normalize } from "./normalize.js";
|
|
11
13
|
const JOURNAL_VERSION = 1;
|
|
12
14
|
const FIELD_MAX = 128;
|
|
13
15
|
/** The file stem of a session's own journal (a hash of its session id); the shared "unknown" and "unparsed" buckets do not match. */
|
|
@@ -19,8 +21,30 @@ const fileOf = (home, session) => path.join(journalDir(home), `${session}.jsonl`
|
|
|
19
21
|
function line(home, session, record) {
|
|
20
22
|
appendFileSync(fileOf(home, session), `${JSON.stringify({ v: JOURNAL_VERSION, ...record })}\n`, { mode: 0o600 });
|
|
21
23
|
}
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
+
/**
|
|
25
|
+
* The event name, session and call id of a parsed payload, as the host's own normalizer reads them (a host with camelCase fields, or
|
|
26
|
+
* one whose hook command names the event, has none of Claude's keys). A field it finds nothing in, a host it does not know and a payload it refuses are read by Claude's keys.
|
|
27
|
+
*/
|
|
28
|
+
function namesOf(obj, host, eventArg) {
|
|
29
|
+
let named = {};
|
|
30
|
+
if (isHostKey(host)) {
|
|
31
|
+
try {
|
|
32
|
+
const ev = normalize(host, obj, eventArg);
|
|
33
|
+
named = { event: ev.eventName, session: ev.session, id: ev.toolUseId };
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// read by the raw keys below
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// A field the normalizer finds nothing in (no `--event` argument given, a Claude-shaped payload under another host) is read by Claude's key, as before.
|
|
40
|
+
return {
|
|
41
|
+
event: typeof named.event === "string" ? named.event : obj.hook_event_name,
|
|
42
|
+
session: typeof named.session === "string" && named.session !== "" ? named.session : obj.session_id,
|
|
43
|
+
id: typeof named.id === "string" && named.id !== "" ? named.id : obj.tool_use_id,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Writes the index record (never a body) for the raw bytes of one event. `host` is the --host argument, or "unknown"; `eventArg` is the --event argument of a host whose payload names no event. Parses the bytes only to name the record. */
|
|
47
|
+
export function journalEvent(home, raw, host, now, eventArg) {
|
|
24
48
|
// Idempotent: the hook entry already scrubbed these bytes, and a caller that did not still never gets a patch body on disk.
|
|
25
49
|
const bytes = scrubPayloadBytes(raw);
|
|
26
50
|
mkdirSync(journalDir(home), { recursive: true, mode: 0o700 });
|
|
@@ -33,12 +57,13 @@ export function journalEvent(home, raw, host, now) {
|
|
|
33
57
|
event = "unknown";
|
|
34
58
|
session = "unknown";
|
|
35
59
|
if (obj !== null && typeof obj === "object") {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
60
|
+
const named = namesOf(obj, host, eventArg);
|
|
61
|
+
if (typeof named.event === "string")
|
|
62
|
+
event = clip(named.event);
|
|
63
|
+
if (typeof named.session === "string" && named.session !== "")
|
|
64
|
+
session = sha(named.session).slice(0, 16);
|
|
65
|
+
if (typeof named.id === "string" && named.id !== "")
|
|
66
|
+
id = clip(named.id);
|
|
42
67
|
}
|
|
43
68
|
}
|
|
44
69
|
catch {
|
|
@@ -75,12 +100,15 @@ export function readJournalSession(home, session) {
|
|
|
75
100
|
}
|
|
76
101
|
return out;
|
|
77
102
|
}
|
|
78
|
-
/** The journal stem of the session a raw event names, or "-" when its bytes name none. */
|
|
79
|
-
export function sessionKeyOfBytes(bytes) {
|
|
103
|
+
/** The journal stem of the session a raw event names (read as `journalEvent` reads it), or "-" when its bytes name none. */
|
|
104
|
+
export function sessionKeyOfBytes(bytes, host = "unknown", eventArg) {
|
|
80
105
|
try {
|
|
81
106
|
const o = JSON.parse(bytes.toString("utf8"));
|
|
82
|
-
if (o !== null && typeof o === "object"
|
|
83
|
-
|
|
107
|
+
if (o !== null && typeof o === "object") {
|
|
108
|
+
const { session } = namesOf(o, host, eventArg);
|
|
109
|
+
if (typeof session === "string" && session !== "")
|
|
110
|
+
return journalSessionKey(session);
|
|
111
|
+
}
|
|
84
112
|
}
|
|
85
113
|
catch {
|
|
86
114
|
// no session
|
package/dist/hosts/claude.js
CHANGED
|
@@ -1,19 +1,14 @@
|
|
|
1
|
-
// Claude Code
|
|
2
|
-
//
|
|
1
|
+
// Claude Code's first-party extras (harnesses/claude/cocheck-harness.json names them): reading the transcript (the words before a call and the closing
|
|
2
|
+
// message, the calls it holds, a withheld input field) and finding a helper's own files. Everything that is data lives in the manifest.
|
|
3
3
|
import { createReadStream } from "node:fs";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import readline from "node:readline";
|
|
6
6
|
import path from "node:path";
|
|
7
|
-
import { readClaudeCalls } from "../coverage.js";
|
|
8
7
|
import { CLOSING_MAX, NARRATION_MAX, joined, remember } from "../narration.js";
|
|
9
|
-
import { platform } from "../platform/index.js";
|
|
10
|
-
import { claudeShapeExtra, claudeShapeFailure } from "./shared.js";
|
|
11
|
-
import { claudeSessionTitle } from "./session-titles.js";
|
|
12
|
-
import { SHARED_EVENT_KINDS, SHARED_FIELDS } from "./types.js";
|
|
13
8
|
const ASSISTANT_LINE = /"type"\s*:\s*"assistant"/;
|
|
14
9
|
const USER_LINE = /"type"\s*:\s*"user"/;
|
|
15
10
|
/** One line of a Claude Code transcript. Only assistant lines are parsed. */
|
|
16
|
-
function claudeLine(cur, line) {
|
|
11
|
+
export function claudeLine(cur, line) {
|
|
17
12
|
if (!ASSISTANT_LINE.test(line)) {
|
|
18
13
|
// A user line that is not a tool result starts a new turn: text before it was the last turn's closing words.
|
|
19
14
|
if (USER_LINE.test(line) && !line.includes('"tool_result"')) {
|
|
@@ -58,85 +53,15 @@ function claudeLine(cur, line) {
|
|
|
58
53
|
}
|
|
59
54
|
}
|
|
60
55
|
}
|
|
61
|
-
|
|
62
|
-
}
|
|
63
|
-
/** Parses the settings text. An empty file is an empty object. Anything that is not a settings object with sane hooks is refused untouched. */
|
|
64
|
-
function parseSettings(text, file) {
|
|
65
|
-
if (text.trim() === "")
|
|
66
|
-
return {};
|
|
67
|
-
let value;
|
|
68
|
-
try {
|
|
69
|
-
value = JSON.parse(text);
|
|
70
|
-
}
|
|
71
|
-
catch {
|
|
72
|
-
throw new SettingsRefusal(`${file} is not valid JSON; nothing was changed`);
|
|
73
|
-
}
|
|
74
|
-
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
75
|
-
throw new SettingsRefusal(`${file} is not a JSON object; nothing was changed`);
|
|
76
|
-
const hooks = value.hooks;
|
|
77
|
-
if (hooks !== undefined) {
|
|
78
|
-
if (hooks === null || typeof hooks !== "object" || Array.isArray(hooks))
|
|
79
|
-
throw new SettingsRefusal(`${file}: "hooks" is not an object; nothing was changed`);
|
|
80
|
-
for (const [event, groups] of Object.entries(hooks)) {
|
|
81
|
-
if (!Array.isArray(groups))
|
|
82
|
-
throw new SettingsRefusal(`${file}: hooks.${event} is not an array; nothing was changed`);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
return value;
|
|
86
|
-
}
|
|
87
|
-
// Which entries are CoCheck's is decided by the platform's hook command parser, which matches the shape CoCheck writes whole (launcher form,
|
|
88
|
-
// with the Homebrew COCHECK_NODE when present). An entry that merely contains the marker text is the user's own and is never matched.
|
|
89
|
-
const WITH_MATCHER = new Set(["PreToolUse", "PostToolUse", "PostToolUseFailure"]);
|
|
90
|
-
const isManaged = (hook, plat) => typeof hook?.command === "string" && plat.hookCommand.parse(hook.command)?.host === "claude";
|
|
91
|
-
/** Removes every CoCheck entry. Groups, events and `hooks` that this empties are dropped; ones the user left empty are not touched. Returns whether anything went. */
|
|
92
|
-
function removeManaged(settings, plat = platform()) {
|
|
93
|
-
const hooks = settings.hooks;
|
|
94
|
-
if (hooks === undefined)
|
|
95
|
-
return false;
|
|
96
|
-
let removed = false;
|
|
97
|
-
for (const event of Object.keys(hooks)) {
|
|
98
|
-
const kept = [];
|
|
99
|
-
let touched = false;
|
|
100
|
-
for (const group of hooks[event]) {
|
|
101
|
-
if (!Array.isArray(group?.hooks) || !group.hooks.some((h) => isManaged(h, plat))) {
|
|
102
|
-
kept.push(group);
|
|
103
|
-
continue;
|
|
104
|
-
}
|
|
105
|
-
removed = touched = true;
|
|
106
|
-
const rest = group.hooks.filter((h) => !isManaged(h, plat));
|
|
107
|
-
if (rest.length > 0)
|
|
108
|
-
kept.push({ ...group, hooks: rest });
|
|
109
|
-
}
|
|
110
|
-
if (touched) {
|
|
111
|
-
if (kept.length === 0)
|
|
112
|
-
delete hooks[event];
|
|
113
|
-
else
|
|
114
|
-
hooks[event] = kept;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
if (removed && Object.keys(hooks).length === 0)
|
|
118
|
-
delete settings.hooks;
|
|
119
|
-
return removed;
|
|
120
|
-
}
|
|
121
|
-
/** SessionStart sets the attribution write hooks' environment for the session's Bash calls (CLAUDE_ENV_FILE); it records nothing. */
|
|
56
|
+
/** SessionStart sets the attribution write hooks' environment for the session's Bash calls (CLAUDE_ENV_FILE); it records nothing. Also the manifest's `install.extraEvents`. */
|
|
122
57
|
export const CLAUDE_EXTRA_EVENTS = ["SessionStart"];
|
|
123
|
-
function addManaged(settings, command) {
|
|
124
|
-
settings.hooks ??= {};
|
|
125
|
-
for (const event of [...Object.keys(SHARED_EVENT_KINDS), ...CLAUDE_EXTRA_EVENTS]) {
|
|
126
|
-
const group = WITH_MATCHER.has(event) ? { matcher: "*" } : {};
|
|
127
|
-
group.hooks = [{ type: "command", command }];
|
|
128
|
-
(settings.hooks[event] ??= []).push(group);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
const claudeText = (settings) => JSON.stringify(settings, null, 2) + "\n";
|
|
132
|
-
const hasManaged = (settings, event, plat = platform()) => Array.isArray(settings.hooks?.[event]) && settings.hooks[event].some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => isManaged(h, plat)));
|
|
133
58
|
/** The longest transcript line read when looking for one call (a whole brief sits in one line). */
|
|
134
59
|
const REVEAL_LINE_MAX = 8 * 1024 * 1024;
|
|
135
60
|
/**
|
|
136
61
|
* The raw string `field` of the input of the tool_use block `toolUseId` in a Claude Code transcript (JSON lines); undefined when the
|
|
137
62
|
* block or field is not there. Read only, line by line; the caller has already checked the file is a regular file under the profile root.
|
|
138
63
|
*/
|
|
139
|
-
async function claudeFieldText(file, toolUseId, field) {
|
|
64
|
+
export async function claudeFieldText(file, toolUseId, field) {
|
|
140
65
|
const stream = createReadStream(file, { encoding: "utf8" });
|
|
141
66
|
const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
142
67
|
try {
|
|
@@ -167,84 +92,23 @@ async function claudeFieldText(file, toolUseId, field) {
|
|
|
167
92
|
stream.destroy();
|
|
168
93
|
}
|
|
169
94
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
foldLine: claudeLine,
|
|
187
|
-
closing: (cur) => joined(cur?.pending ?? [], CLOSING_MAX),
|
|
188
|
-
},
|
|
189
|
-
// The desktop app's Code tab saves the user's permission approvals here; only the app's own file at the task folder root, not .claude/settings.json (the user's shared project config, which the app does not write).
|
|
190
|
-
hostOwnedFiles: [".claude/settings.local.json"],
|
|
191
|
-
hostOwnedWhat: "the Claude app saving your permission choices",
|
|
192
|
-
sessionTitle: claudeSessionTitle,
|
|
193
|
-
sessionFile: {
|
|
194
|
-
// Claude names its session file in the payload (`transcript_path`); there is no folder layout to search.
|
|
195
|
-
bySessionId: false,
|
|
196
|
-
locate: () => undefined,
|
|
197
|
-
},
|
|
198
|
-
helpers: {
|
|
199
|
-
dirOf: (sessionFile, session) => path.join(path.dirname(sessionFile), session, "subagents"),
|
|
200
|
-
transcriptFile: (agentId) => `agent-${agentId}.jsonl`,
|
|
201
|
-
metaFile: (agentId) => `agent-${agentId}.meta.json`,
|
|
202
|
-
idOfTranscript: (name) => name.slice("agent-".length, -".jsonl".length),
|
|
203
|
-
idOfMeta: (name) => name.slice("agent-".length, -".meta.json".length),
|
|
204
|
-
transcriptName: /^agent-.+\.jsonl$/,
|
|
205
|
-
metaName: /^agent-.+\.meta\.json$/,
|
|
206
|
-
folderName: "subagents",
|
|
207
|
-
// Under the node test runner the `~/.claude` default is refused, so a test cannot read the real transcripts.
|
|
208
|
-
projectsRoot: () => {
|
|
209
|
-
if (!process.env.CLAUDE_CONFIG_DIR && process.env.NODE_TEST_CONTEXT) {
|
|
210
|
-
throw new Error("CLAUDE_CONFIG_DIR is unset under the test runner; refusing to fall back to the real ~/.claude/projects");
|
|
211
|
-
}
|
|
212
|
-
return path.join(process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), ".claude"), "projects");
|
|
213
|
-
},
|
|
214
|
-
},
|
|
215
|
-
coverage: { readCalls: (sessionFile, session) => readClaudeCalls(sessionFile, session) },
|
|
216
|
-
reveal: { fieldText: claudeFieldText },
|
|
217
|
-
install: {
|
|
218
|
-
skillRoot: path.join(".claude", "skills"),
|
|
219
|
-
inBothAlias: true,
|
|
220
|
-
timingLabel: "Claude Code",
|
|
221
|
-
hostFlag: "claude",
|
|
222
|
-
projectDirEnv: "CLAUDE_PROJECT_DIR",
|
|
223
|
-
events: Object.keys(SHARED_EVENT_KINDS),
|
|
224
|
-
afterInstall: "Restart Claude Code so it reads the new settings.",
|
|
225
|
-
configFile: (env, userHome) => path.join(env.CLAUDE_CONFIG_DIR || path.join(userHome, ".claude"), "settings.json"),
|
|
226
|
-
addHooks: (text, file, spec, plat = platform()) => {
|
|
227
|
-
const settings = parseSettings(text, file);
|
|
228
|
-
removeManaged(settings, plat);
|
|
229
|
-
addManaged(settings, spec === undefined ? "" : plat.hookCommand.build(spec));
|
|
230
|
-
return claudeText(settings);
|
|
231
|
-
},
|
|
232
|
-
removeHooks: (text, file, plat = platform()) => {
|
|
233
|
-
const settings = parseSettings(text, file);
|
|
234
|
-
const changed = removeManaged(settings, plat);
|
|
235
|
-
return { text: changed ? claudeText(settings) : text, changed };
|
|
236
|
-
},
|
|
237
|
-
missingEvents: (text, file, plat = platform()) => {
|
|
238
|
-
const settings = parseSettings(text, file);
|
|
239
|
-
return Object.keys(SHARED_EVENT_KINDS).filter((e) => !hasManaged(settings, e, plat));
|
|
240
|
-
},
|
|
241
|
-
},
|
|
242
|
-
shape: {
|
|
243
|
-
PreToolUse: ["session_id", "tool_name", "tool_use_id", "tool_input"],
|
|
244
|
-
PostToolUse: ["session_id", "tool_name", "tool_use_id", "tool_input", "tool_response"],
|
|
245
|
-
PostToolUseFailure: ["session_id", "tool_name", "tool_use_id", "error"],
|
|
246
|
-
Stop: ["session_id"],
|
|
247
|
-
SubagentStop: ["session_id", "agent_id"],
|
|
248
|
-
UserPromptSubmit: ["session_id", "prompt"],
|
|
95
|
+
/** Where a Claude Code session keeps its helpers' own records, beside the session file. */
|
|
96
|
+
export const CLAUDE_HELPERS = {
|
|
97
|
+
dirOf: (sessionFile, session) => path.join(path.dirname(sessionFile), session, "subagents"),
|
|
98
|
+
transcriptFile: (agentId) => `agent-${agentId}.jsonl`,
|
|
99
|
+
metaFile: (agentId) => `agent-${agentId}.meta.json`,
|
|
100
|
+
idOfTranscript: (name) => name.slice("agent-".length, -".jsonl".length),
|
|
101
|
+
idOfMeta: (name) => name.slice("agent-".length, -".meta.json".length),
|
|
102
|
+
transcriptName: /^agent-.+\.jsonl$/,
|
|
103
|
+
metaName: /^agent-.+\.meta\.json$/,
|
|
104
|
+
folderName: "subagents",
|
|
105
|
+
// Under the node test runner the `~/.claude` default is refused, so a test cannot read the real transcripts.
|
|
106
|
+
projectsRoot: () => {
|
|
107
|
+
if (!process.env.CLAUDE_CONFIG_DIR && process.env.NODE_TEST_CONTEXT) {
|
|
108
|
+
throw new Error("CLAUDE_CONFIG_DIR is unset under the test runner; refusing to fall back to the real ~/.claude/projects");
|
|
109
|
+
}
|
|
110
|
+
return path.join(process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), ".claude"), "projects");
|
|
249
111
|
},
|
|
250
112
|
};
|
|
113
|
+
/** The closing words a Claude Code cursor holds. */
|
|
114
|
+
export const claudeClosing = (cur) => joined(cur?.pending ?? [], CLOSING_MAX);
|