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-adapter.js
CHANGED
|
@@ -7,7 +7,7 @@ import { chmod, copyFile, mkdir, readdir, readFile, rename, rm, stat, writeFile
|
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { cleanId, evidenceSince, readLauncher } from "./agent-transcripts.js";
|
|
9
9
|
import { isPatchTool, isWithheldSection } from "./patch-secrets.js";
|
|
10
|
-
import { EVIDENCE_SLACK_MS, creditWithEvidence, guardKit, isInternalAgentCall, isLauncherTool, isWaitTool, launcherMayCredit, neverRan, runsOnAfterResult, samePath, toolMayCredit, isShellTool, toolNeverWrites, waitsOnHelpers, writeTargetsOf, editTargetsOf, reportedEditsOf } from "./credit-guard.js";
|
|
10
|
+
import { EVIDENCE_SLACK_MS, creditWithEvidence, guardKit, isInternalAgentCall, isLauncherTool, isWaitTool, launcherMayCredit, shellDialectOf, neverRan, runsOnAfterResult, samePath, toolMayCredit, isShellTool, toolNeverWrites, waitsOnHelpers, writeTargetsOf, editTargetsOf, reportedEditsOf } from "./credit-guard.js";
|
|
11
11
|
import { withFileLock } from "./file-lock.js";
|
|
12
12
|
import { claimedFor, claimedLayer, cutShortReason, MOVED_WHILE_READ } from "./connector/claimed.js";
|
|
13
13
|
import { connectorClaimsFor, fileConnectorIdentity } from "./connector/installed-match.js";
|
|
@@ -22,7 +22,7 @@ import { foldFolder, isInsideFolded, resolveFolder as realish } from "./registry
|
|
|
22
22
|
import { sha256Stream } from "./fingerprint.js";
|
|
23
23
|
import { ensureStoreDir, mbText, removeEmptyStoreDir, removePreviews, STATE_FILE_CAP_BYTES, storeDirOf, storedShas, TASK_STORE_CAP_BYTES } from "./states.js";
|
|
24
24
|
import { openLedger, TOOL_FAILED, TOOL_NOT_RUN } from "./ledger.js";
|
|
25
|
-
import { profileOf } from "./hosts/index.js";
|
|
25
|
+
import { findProfile, profileOf, projectDirVars } from "./hosts/index.js";
|
|
26
26
|
import { exitFailureText } from "./timeline/rollout-failures.js";
|
|
27
27
|
import { assertNormalized, normalize } from "./normalize.js";
|
|
28
28
|
import { advance, advanceForward, claimAtPre, READ_BUDGET_MS, claimRequest, closingClaim, cut, CLOSING_MAX, lookup, newCursor, none, reasonOf, spend, validCursor } from "./narration.js";
|
|
@@ -35,7 +35,7 @@ import { cannotHaveWritten, fsProbe, hooksProven, isReadOnlyCommand, writeScope
|
|
|
35
35
|
import { commandNamesFile, textNamesBase } from "./attribution/names.js";
|
|
36
36
|
import { rootsFile } from "./attribution/tag.js";
|
|
37
37
|
import { creditBasisOf, hostReportedEdit } from "./attribution/basis.js";
|
|
38
|
-
import { reconstructAll, RECONSTRUCT_MAX_BYTES } from "./attribution/reconstruct.js";
|
|
38
|
+
import { reconstructAll, RECONSTRUCT_MAX_BYTES, revertEdits } from "./attribution/reconstruct.js";
|
|
39
39
|
/**
|
|
40
40
|
* Host-hook adapter. Claude Code and Codex call it from PreToolUse, PostToolUse, PostToolUseFailure and
|
|
41
41
|
* Stop hooks; each call is a short-lived process, so everything it knows lives in `<home>/hooks/<key>/`: a
|
|
@@ -248,7 +248,7 @@ const ERROR_TEXT_MAX = 2000;
|
|
|
248
248
|
const FAILED_NO_TEXT = "The host reported a failure and sent no error text.";
|
|
249
249
|
/** A background launch of an agent is not a job that writes files: its work arrives through the agent's own hooked calls. */
|
|
250
250
|
/** A call whose only work is waiting on helpers (Codex `wait_agent`, Copilot `read_agent` with `wait: true`); it writes nothing, so it never shares a helper's credit. */
|
|
251
|
-
const isWaitCall = (c) => c.waits === true || isWaitTool(c.tool);
|
|
251
|
+
const isWaitCall = (c, host) => c.waits === true || isWaitTool(c.tool, host);
|
|
252
252
|
/** Most prompts a session keeps for a round; older ones are counted, not kept. */
|
|
253
253
|
const PROMPTS_KEPT = 3;
|
|
254
254
|
/** Sessions whose held prompts and called marks are kept; the session with the oldest held prompt goes first. */
|
|
@@ -272,17 +272,17 @@ export const TAIL_NOTE = "found after the call that names it ended; credited to
|
|
|
272
272
|
*/
|
|
273
273
|
function assertTaskFolder(folder) {
|
|
274
274
|
if (!path.isAbsolute(folder)) {
|
|
275
|
-
throw new Error(`task folder "${folder}" is relative; pass an absolute path in --folder or
|
|
275
|
+
throw new Error(`task folder "${folder}" is relative; pass an absolute path in --folder or ${projectDirVars().join(" or ")}`);
|
|
276
276
|
}
|
|
277
277
|
let stat;
|
|
278
278
|
try {
|
|
279
279
|
stat = statSync(folder);
|
|
280
280
|
}
|
|
281
281
|
catch {
|
|
282
|
-
throw new Error(`task folder ${folder} does not exist; check --folder or
|
|
282
|
+
throw new Error(`task folder ${folder} does not exist; check --folder or ${projectDirVars().join(" or ")}`);
|
|
283
283
|
}
|
|
284
284
|
if (!stat.isDirectory())
|
|
285
|
-
throw new Error(`task folder ${folder} is not a directory; check --folder or
|
|
285
|
+
throw new Error(`task folder ${folder} is not a directory; check --folder or ${projectDirVars().join(" or ")}`);
|
|
286
286
|
}
|
|
287
287
|
/**
|
|
288
288
|
* A hook task's client, one per session: `<host>-hook:<folder>?session=<id>`. A resumed session keeps its id, so it stays in its task.
|
|
@@ -298,8 +298,10 @@ const stateKeyOf = (client) => createHash("sha256").update(client).digest("hex")
|
|
|
298
298
|
export async function handleHook(payload, options) {
|
|
299
299
|
return handleEvent(normalize(options.host, payload), options);
|
|
300
300
|
}
|
|
301
|
-
export async function handleEvent(
|
|
302
|
-
assertNormalized(
|
|
301
|
+
export async function handleEvent(given, options) {
|
|
302
|
+
assertNormalized(given);
|
|
303
|
+
// A shell event of a per-action harness is a shell call's Pre or Post; everything after reads it as one (the failure, if any, is on the event).
|
|
304
|
+
const ev = given.kind === "shell-pre" ? { ...given, kind: "tool-pre" } : given.kind === "shell-post" ? { ...given, kind: "tool-post" } : given;
|
|
303
305
|
const { home } = options;
|
|
304
306
|
const host = ev.host;
|
|
305
307
|
assertTaskFolder(options.folder);
|
|
@@ -326,9 +328,19 @@ export async function handleEvent(ev, options) {
|
|
|
326
328
|
ctx.loadWriteEvidence();
|
|
327
329
|
let submit = false;
|
|
328
330
|
ctx.bindCall();
|
|
331
|
+
ctx.distinctCall(given.kind === "shell-pre");
|
|
332
|
+
if (ev.kind === "tool-pre" || ev.kind === "tool-post" || ev.kind === "tool-failure" || ev.kind === "stop" || ev.kind === "subagent-stop" || ev.kind === "prompt" || ev.kind === "file-edit")
|
|
333
|
+
await ctx.startSession();
|
|
329
334
|
switch (ev.kind) {
|
|
330
335
|
case "tool-pre":
|
|
331
|
-
|
|
336
|
+
// The same call reported by two events (a tool Pre and a shell Pre sharing one id) is opened once.
|
|
337
|
+
if (given.kind === "shell-pre")
|
|
338
|
+
await ctx.actionPre();
|
|
339
|
+
else if (!ctx.joinsActionCall())
|
|
340
|
+
await ctx.pre();
|
|
341
|
+
break;
|
|
342
|
+
case "file-edit":
|
|
343
|
+
await ctx.fileEdit();
|
|
332
344
|
break;
|
|
333
345
|
case "tool-post":
|
|
334
346
|
case "tool-failure":
|
|
@@ -357,7 +369,7 @@ export async function handleEvent(ev, options) {
|
|
|
357
369
|
try {
|
|
358
370
|
const keptTask = tasks.currentTaskId(client);
|
|
359
371
|
if (keptTask !== undefined)
|
|
360
|
-
await keepCallValues(home, keptTask, { call: ev.toolUseId, tool: ev.toolName, input: ev.toolInput, response: ev.toolResponse ?? (ev.failure === undefined ? undefined : { error: ev.failure.raw }) });
|
|
372
|
+
await keepCallValues(home, keptTask, { call: ctx.callId ?? ev.toolUseId, tool: ev.toolName, input: ev.toolInput, response: ev.toolResponse ?? (ev.failure === undefined ? undefined : { error: ev.failure.raw }) });
|
|
361
373
|
}
|
|
362
374
|
catch {
|
|
363
375
|
// the call is recorded without its values; the hook's own work goes on
|
|
@@ -458,6 +470,8 @@ class Context {
|
|
|
458
470
|
#stopSweptNothing = false;
|
|
459
471
|
/** A new state was written to the store in this event, so the per-task cap is checked. */
|
|
460
472
|
#storedNew = false;
|
|
473
|
+
/** The folder's first event is a reported edit: the edited file's state before it, rebuilt from the edit's old text, which the baseline records in place of the file's bytes now. */
|
|
474
|
+
#rebuilt;
|
|
461
475
|
#tmpN = 0;
|
|
462
476
|
/** Files whose write evidence a sweep used in this event, dropped from the state before it is saved. */
|
|
463
477
|
#evidenceUsed = new Set();
|
|
@@ -521,6 +535,58 @@ class Context {
|
|
|
521
535
|
if (id !== undefined)
|
|
522
536
|
this.#ev = { ...this.#ev, toolUseId: id };
|
|
523
537
|
}
|
|
538
|
+
/** The call id this event is handled under (the one the host sent, or the one `bindCall` or `distinctCall` gave it). */
|
|
539
|
+
get callId() {
|
|
540
|
+
return this.#ev.toolUseId || undefined;
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* One id, one call, within a session. Some hosts send the id of a call that has ended again for the next call (Cursor gives a Read and
|
|
544
|
+
* the Write after it in one step the same id). A Pre whose id names a call of the same session already closed or expired, or still open
|
|
545
|
+
* for another tool, starts a new call: it takes the id with an occurrence suffix (`<id>-r2`, `-r3`, ...), and the Post, failure or file
|
|
546
|
+
* edit of that session that follows under the sent id is that new call's. Not a host rule: any harness's events go through it. An id never
|
|
547
|
+
* sent again, or sent again by another session, is left as it is (as before).
|
|
548
|
+
* A shell Pre that shares the id of the tool Pre of the same call (`shellAction`) is that call, never a new one.
|
|
549
|
+
*/
|
|
550
|
+
distinctCall(shellAction) {
|
|
551
|
+
const kind = this.#ev.kind;
|
|
552
|
+
const sent = this.#ev.toolUseId;
|
|
553
|
+
if (!sent || (kind !== "tool-pre" && kind !== "tool-post" && kind !== "tool-failure" && kind !== "file-edit"))
|
|
554
|
+
return;
|
|
555
|
+
const state = this.#state;
|
|
556
|
+
const session = this.#ev.session;
|
|
557
|
+
const mapped = state.reused?.[sent];
|
|
558
|
+
const given = mapped !== undefined && this.#sessionOfCall(mapped) === session ? mapped : undefined;
|
|
559
|
+
if (kind !== "tool-pre") {
|
|
560
|
+
if (given === undefined)
|
|
561
|
+
return;
|
|
562
|
+
// The call first sent under the id still open for this tool, while the newer one is for another: the event is the first call's.
|
|
563
|
+
const first = state.open[sent];
|
|
564
|
+
if (first !== undefined && first.tool === (this.#ev.toolName ?? "") && state.open[given]?.tool !== first.tool)
|
|
565
|
+
return;
|
|
566
|
+
this.#ev = { ...this.#ev, toolUseId: given };
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
const current = given ?? sent;
|
|
570
|
+
const open = state.open[current];
|
|
571
|
+
const ended = open === undefined && (state.closed.includes(current) || state.expired.includes(current)) && this.#sessionOfCall(current) === session;
|
|
572
|
+
const otherTool = open !== undefined && !shellAction && open.fromAction !== true && open.session === session && open.tool !== (this.#ev.toolName ?? "");
|
|
573
|
+
if (!ended && !otherTool) {
|
|
574
|
+
if (given !== undefined)
|
|
575
|
+
this.#ev = { ...this.#ev, toolUseId: given };
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
const taken = (id) => id in state.open || state.closed.includes(id) || state.expired.includes(id);
|
|
579
|
+
let n = 2;
|
|
580
|
+
while (taken(`${sent}-r${n}`))
|
|
581
|
+
n++;
|
|
582
|
+
const id = `${sent}-r${n}`;
|
|
583
|
+
const reused = (state.reused ??= {});
|
|
584
|
+
delete reused[sent];
|
|
585
|
+
reused[sent] = id;
|
|
586
|
+
for (const old of Object.keys(reused).slice(0, -CLOSED_KEEP))
|
|
587
|
+
delete reused[old];
|
|
588
|
+
this.#ev = { ...this.#ev, toolUseId: id };
|
|
589
|
+
}
|
|
524
590
|
/**
|
|
525
591
|
* Every open call of `session` that still holds a synthetic id (oldest first) takes the real id of the unclaimed request
|
|
526
592
|
* for its tool and arguments, if the file holds one now. Run at every Pre, Post and failure before a step is written, so no step
|
|
@@ -569,6 +635,38 @@ class Context {
|
|
|
569
635
|
if (f.unreadable !== undefined)
|
|
570
636
|
move(f.unreadable.calls);
|
|
571
637
|
}
|
|
638
|
+
/**
|
|
639
|
+
* A session's first event: the folder is looked at now, before the session's task can open, so the task starts from the folder as it
|
|
640
|
+
* stands when tracking began. A folder never looked at gets its starting copy. A folder looked at earlier (another session, an earlier
|
|
641
|
+
* stretch of tracking) is swept now, so what changed while this session was not tracked is credited as any sweep credits it (to the
|
|
642
|
+
* calls open, or to nobody) and never reaches this session's task as a change of its own: its starting copy is taken from the fresh states.
|
|
643
|
+
*/
|
|
644
|
+
async startSession() {
|
|
645
|
+
const session = this.#ev.session;
|
|
646
|
+
if (!this.#split || typeof session !== "string" || session === "" || this.#opts.heldReplay === true)
|
|
647
|
+
return;
|
|
648
|
+
const marks = (this.#state.sessionStarts ??= {});
|
|
649
|
+
if (session in marks)
|
|
650
|
+
return;
|
|
651
|
+
// Seen already by an earlier build (work, an open call, a held prompt): its task keeps the earlier rule.
|
|
652
|
+
if (this.#sessionHasWork(session) || Object.values(this.#state.open).some((c) => c.session === session) || session in this.#state.held)
|
|
653
|
+
return;
|
|
654
|
+
const from = this.#state.stepSeq;
|
|
655
|
+
if (!this.#state.init)
|
|
656
|
+
await this.#baseline();
|
|
657
|
+
else {
|
|
658
|
+
this.#expire();
|
|
659
|
+
const changed = await this.#sweep();
|
|
660
|
+
const open = this.#openCalls();
|
|
661
|
+
if (open.length > 0)
|
|
662
|
+
this.#credit(changed, open);
|
|
663
|
+
else
|
|
664
|
+
this.#unclaimed(changed, open);
|
|
665
|
+
}
|
|
666
|
+
marks[session] = { from, at: this.#state.stepSeq };
|
|
667
|
+
for (const old of Object.keys(marks).slice(0, -SESSIONS_KEPT))
|
|
668
|
+
delete marks[old];
|
|
669
|
+
}
|
|
572
670
|
/** Called by handleHook as the event starts, so lock wait and ledger open count as adapter time. */
|
|
573
671
|
markStart(mark) {
|
|
574
672
|
this.#startedAt = mark;
|
|
@@ -912,11 +1010,15 @@ class Context {
|
|
|
912
1010
|
this.#drop(client, `${keep.length - opsCap} earlier calls and prompts of this session were dropped before its task opened (only the newest ${opsCap} are kept)`);
|
|
913
1011
|
continue;
|
|
914
1012
|
}
|
|
915
|
-
// The task begins with the folder's starting copy (the one taken at the first event, else the files as they stood before this change)
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
const
|
|
919
|
-
|
|
1013
|
+
// The task begins with the folder's starting copy (the one taken at the first event, else the files as they stood before this change)
|
|
1014
|
+
// and what changed unowned since. What the look at this session's own first event found had changed while nobody was tracking the
|
|
1015
|
+
// folder is not the session's: it is folded into a starting copy taken from the fresh states, and an older held copy is stale.
|
|
1016
|
+
const mark = Object.entries(state.sessionStarts ?? {}).find(([s]) => this.#clientOf(s) === client)?.[1];
|
|
1017
|
+
const caught = mark === undefined ? [] : pending.unowned.filter((x) => x.seq > mark.from && x.seq <= mark.at);
|
|
1018
|
+
const unowned = pending.unowned.filter((x) => !caught.includes(x));
|
|
1019
|
+
const held = (pending.starts ?? []).filter((x) => caught.length === 0 || x.seq > mark.from);
|
|
1020
|
+
const start = held.length > 0 ? held : [this.#startStep([...unowned, ...steps])].flatMap((x) => (x === undefined ? [] : [x]));
|
|
1021
|
+
steps = [...start, ...unowned, ...steps];
|
|
920
1022
|
taskId = await this.#openTask(client, steps);
|
|
921
1023
|
ops = [...(parked[client] ?? []).filter((p) => !ops.some((o) => o.key === p.key)), ...ops];
|
|
922
1024
|
delete parked[client];
|
|
@@ -951,13 +1053,24 @@ class Context {
|
|
|
951
1053
|
else if (notes.length === 20)
|
|
952
1054
|
notes.push("more drops followed and are not listed");
|
|
953
1055
|
}
|
|
954
|
-
/**
|
|
1056
|
+
/**
|
|
1057
|
+
* The clients of this folder (the folder-only one included) that have an open task now. A session that ran `cocheck track stop`
|
|
1058
|
+
* is left out until it starts again (its own event is that start): its task collects nothing more, so a change nobody's agent made
|
|
1059
|
+
* after the stop goes to the sessions still tracking, or waits for the next task to open, or is never seen when nobody tracks.
|
|
1060
|
+
*/
|
|
955
1061
|
#openClients() {
|
|
956
1062
|
const out = new Set();
|
|
1063
|
+
const own = this.#split ? this.#clientOf(this.#ev.session) : undefined;
|
|
957
1064
|
for (const id of this.#ledger.tasksForFamily(this.#folderClient)) {
|
|
958
1065
|
const client = this.#ledger.taskClient(id);
|
|
959
|
-
if (typeof client
|
|
960
|
-
|
|
1066
|
+
if (typeof client !== "string" || out.has(client))
|
|
1067
|
+
continue;
|
|
1068
|
+
const current = this.#tasks.currentTaskId(client);
|
|
1069
|
+
if (current === undefined)
|
|
1070
|
+
continue;
|
|
1071
|
+
if (client !== own && this.#ledger.trackingStoppedLast(current))
|
|
1072
|
+
continue;
|
|
1073
|
+
out.add(client);
|
|
961
1074
|
}
|
|
962
1075
|
return [...out];
|
|
963
1076
|
}
|
|
@@ -1312,7 +1425,7 @@ class Context {
|
|
|
1312
1425
|
// An apply_patch header names its file whole, spaces included; the word scan above cuts it at each space, so the pieces (a folder the call
|
|
1313
1426
|
// never touched, a path made relative to the cwd) are dropped and the header's own path is taken instead. A Windows header (`C:\Users\...`)
|
|
1314
1427
|
// is taken whole too: the word scan reads each backslash as a shell escape, so the path it records names no real file.
|
|
1315
|
-
for (const h of writeTargetsOf(this.#ev.toolName, input)) {
|
|
1428
|
+
for (const h of writeTargetsOf(this.#ev.toolName, input, this.#ev.host)) {
|
|
1316
1429
|
if (!/[\s\\]/.test(h) || !(pathKit().isAbs(h) || h.startsWith("~/")))
|
|
1317
1430
|
continue;
|
|
1318
1431
|
const pieces = new Set(h.split(/\s+/).map((w) => w.replace(/[.,:;]+$/, "")));
|
|
@@ -1583,6 +1696,9 @@ class Context {
|
|
|
1583
1696
|
if (books.length === 0)
|
|
1584
1697
|
await this.#tasks.touch(this.#client, [...listing.whole, ...listing.hashOnly.keys(), ...listing.secret][0] ?? this.#folder);
|
|
1585
1698
|
}
|
|
1699
|
+
// A session's first look runs before its event is handled: a reported edit that is that event rebuilds its file's before-state here.
|
|
1700
|
+
if (this.#rebuilt === undefined && this.#ev.kind === "file-edit")
|
|
1701
|
+
this.#rebuilt = this.#rebuildBefore();
|
|
1586
1702
|
const changes = [];
|
|
1587
1703
|
for (const file of [...listing.whole, ...listing.hashOnly.keys(), ...listing.secret].sort()) {
|
|
1588
1704
|
const note = listing.hashOnly.get(file);
|
|
@@ -1595,16 +1711,27 @@ class Context {
|
|
|
1595
1711
|
continue; // gone since the listing
|
|
1596
1712
|
}
|
|
1597
1713
|
try {
|
|
1598
|
-
const
|
|
1714
|
+
const kit = pathKit();
|
|
1715
|
+
const rebuilt = this.#rebuilt !== undefined && note === undefined && !secret && (kit.same(this.#rebuilt.file, file) || kit.same(realish(this.#rebuilt.file), realish(file))) ? this.#rebuilt.bytes : undefined;
|
|
1716
|
+
const staged = await this.#capture(file, st, note !== undefined, secret, rebuilt);
|
|
1717
|
+
const asRebuilt = rebuilt !== undefined && staged.kept === "whole" && staged.secret !== true;
|
|
1599
1718
|
this.#state.files[file] = { copy: staged.copy, sha: staged.sha, size: staged.size, mtimeNs: staged.mtimeNs, ino: staged.ino, ctimeNs: staged.ctimeNs, first: staged.sha, kept: staged.kept, ...(staged.secret ? { secret: true } : {}) };
|
|
1719
|
+
if (asRebuilt) {
|
|
1720
|
+
// Not the bytes on disk: no stat matches it, so the next sweep reads the file and finds the edit.
|
|
1721
|
+
const t = this.#state.files[file];
|
|
1722
|
+
delete t.mtimeNs;
|
|
1723
|
+
delete t.ino;
|
|
1724
|
+
delete t.ctimeNs;
|
|
1725
|
+
(this.#state.rebuilt ??= []).push(staged.sha);
|
|
1726
|
+
}
|
|
1600
1727
|
changes.push({
|
|
1601
1728
|
path: file,
|
|
1602
1729
|
sha: staged.sha,
|
|
1603
1730
|
prev: null,
|
|
1604
1731
|
size: staged.size,
|
|
1605
1732
|
kept: staged.kept,
|
|
1606
|
-
mtimeNs: staged.mtimeNs,
|
|
1607
|
-
note: secret ? `A secret file is in the folder: ${this.#rel(file)}; only its hash and size are kept` : staged.secret ? this.#noted(file, "", true, staged.secretWhy) : [note ?? staged.hashReason, this.#sizeNote(staged.size)].filter((x) => x).join("; "),
|
|
1733
|
+
...(asRebuilt ? {} : { mtimeNs: staged.mtimeNs }),
|
|
1734
|
+
note: secret ? `A secret file is in the folder: ${this.#rel(file)}; only its hash and size are kept` : staged.secret ? this.#noted(file, "", true, staged.secretWhy) : [asRebuilt ? "the state before the agent's first reported edit, rebuilt from that edit's old text" : undefined, note ?? staged.hashReason, this.#sizeNote(staged.size)].filter((x) => x).join("; "),
|
|
1608
1735
|
});
|
|
1609
1736
|
if (this.#claimed(file))
|
|
1610
1737
|
this.#remember(file, staged.sha, "the start of the task");
|
|
@@ -1748,7 +1875,7 @@ class Context {
|
|
|
1748
1875
|
* `hashOnly` keeps no bytes: the state is the file's fingerprint (a file past the scan caps). `secret` keeps no bytes either and
|
|
1749
1876
|
* reads the file only to hash it (its SHA-256), for a secret file by name.
|
|
1750
1877
|
*/
|
|
1751
|
-
async #capture(file, st, hashOnly, secret = false) {
|
|
1878
|
+
async #capture(file, st, hashOnly, secret = false, bytes) {
|
|
1752
1879
|
const stat0 = { mtimeNs: String(st.mtimeNs), ino: String(st.ino), ctimeNs: String(st.ctimeNs) };
|
|
1753
1880
|
if (secret) {
|
|
1754
1881
|
const sha = await sha256Stream(file);
|
|
@@ -1769,11 +1896,12 @@ class Context {
|
|
|
1769
1896
|
// A claimed file is stat'ed on both sides of the read. Bytes read while the file moved (a writer still writing,
|
|
1770
1897
|
// whatever the format) are not one state of it, so they are cut short: kept and credited, never a diff base, read again next sweep.
|
|
1771
1898
|
const claimed = this.#claimed(file);
|
|
1772
|
-
const before = claimed ? await stat(file, { bigint: true }).catch(() => undefined) : undefined;
|
|
1773
|
-
const plain = await readFile(file);
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
const
|
|
1899
|
+
const before = claimed && bytes === undefined ? await stat(file, { bigint: true }).catch(() => undefined) : undefined;
|
|
1900
|
+
const plain = bytes === undefined ? await readFile(file) : Buffer.from(bytes);
|
|
1901
|
+
if (bytes === undefined)
|
|
1902
|
+
this.#opts.fault?.(`capture-read:${file}`);
|
|
1903
|
+
const after = claimed && bytes === undefined ? await stat(file, { bigint: true }).catch(() => undefined) : undefined;
|
|
1904
|
+
const moved = claimed && bytes === undefined && (before === undefined || after === undefined || before.size !== after.size || before.mtimeNs !== after.mtimeNs || after.size !== BigInt(plain.length));
|
|
1777
1905
|
const sha = sha256Hex(plain);
|
|
1778
1906
|
const size = plain.length;
|
|
1779
1907
|
// A secret is also what the text holds: a value a gitleaks rule finds makes the file a secret, kept as its hash only, never stored.
|
|
@@ -2063,7 +2191,7 @@ class Context {
|
|
|
2063
2191
|
#settleEvidence() {
|
|
2064
2192
|
const byFile = new Map();
|
|
2065
2193
|
for (const [id, call] of Object.entries(this.#state.open)) {
|
|
2066
|
-
if (call.ended !== undefined || call.transcript === undefined || toolNeverWrites(call.tool))
|
|
2194
|
+
if (call.ended !== undefined || call.transcript === undefined || toolNeverWrites(call.tool, this.#ev.host))
|
|
2067
2195
|
continue;
|
|
2068
2196
|
const entry = byFile.get(call.transcript.file) ?? { from: call.transcript.from, ids: [] };
|
|
2069
2197
|
entry.from = Math.min(entry.from, call.transcript.from);
|
|
@@ -2077,7 +2205,7 @@ class Context {
|
|
|
2077
2205
|
const call = this.#state.open[id];
|
|
2078
2206
|
// the next read goes on from here: what was read holds no end for this call (the result is never before its Pre)
|
|
2079
2207
|
call.transcript = { file, from: Math.max(call.transcript.from, next) };
|
|
2080
|
-
if (ev === undefined || (runsOnAfterResult(call) && !neverRan(ev)))
|
|
2208
|
+
if (ev === undefined || (runsOnAfterResult(call, this.#ev.host) && !neverRan(ev)))
|
|
2081
2209
|
continue;
|
|
2082
2210
|
call.ended = ev;
|
|
2083
2211
|
if (!neverRan(ev))
|
|
@@ -2098,14 +2226,14 @@ class Context {
|
|
|
2098
2226
|
return;
|
|
2099
2227
|
const threads = new Map();
|
|
2100
2228
|
for (const [id, call] of Object.entries(this.#state.open)) {
|
|
2101
|
-
if (!isShellTool(call.tool) || call.command === "")
|
|
2229
|
+
if (!isShellTool(call.tool, this.#ev.host) || call.command === "")
|
|
2102
2230
|
continue;
|
|
2103
2231
|
const key = `${call.session}\u0000${call.agentId ?? ""}`;
|
|
2104
2232
|
threads.set(key, [...(threads.get(key) ?? []), id]);
|
|
2105
2233
|
}
|
|
2106
2234
|
for (const ids of threads.values()) {
|
|
2107
2235
|
const first = this.#state.open[ids[0]];
|
|
2108
|
-
const rollout = first.agentId === undefined ? sf.locate(first.session, first.at, this.#opts.
|
|
2236
|
+
const rollout = first.agentId === undefined ? sf.locate(first.session, first.at, this.#opts.sessionsDir) : sf.locateHelper?.(first.session, first.agentId, first.at, this.#opts.sessionsDir);
|
|
2109
2237
|
const refused = rollout === undefined ? undefined : sf.refusedCommands(rollout);
|
|
2110
2238
|
if (refused === undefined || refused.length === 0)
|
|
2111
2239
|
continue;
|
|
@@ -2174,7 +2302,7 @@ class Context {
|
|
|
2174
2302
|
}
|
|
2175
2303
|
/** A call whose command may leave an app running past its result stays a suspect after its Post (see `tails`). */
|
|
2176
2304
|
#keepTail(id, call) {
|
|
2177
|
-
if (!runsOnAfterResult(call) || !Number.isFinite(call.at))
|
|
2305
|
+
if (!runsOnAfterResult(call, this.#ev.host) || !Number.isFinite(call.at))
|
|
2178
2306
|
return;
|
|
2179
2307
|
const kept = (this.#state.tails ??= {});
|
|
2180
2308
|
delete kept[id];
|
|
@@ -2357,13 +2485,13 @@ class Context {
|
|
|
2357
2485
|
* absolute cwd). With outside watching off no outside path is kept, so a scope that writes outside the folder is kept as unknown.
|
|
2358
2486
|
*/
|
|
2359
2487
|
#scopeNow() {
|
|
2360
|
-
if (!isShellTool(this.#ev.toolName))
|
|
2488
|
+
if (!isShellTool(this.#ev.toolName, this.#ev.host))
|
|
2361
2489
|
return {};
|
|
2362
2490
|
const raw = this.#ev.toolInput?.command;
|
|
2363
2491
|
if (typeof raw !== "string")
|
|
2364
2492
|
return {};
|
|
2365
2493
|
// A PowerShell tool's command is read as PowerShell (win32 only, a bounded set of forms; unknown elsewhere, never excluded)
|
|
2366
|
-
const shell =
|
|
2494
|
+
const shell = shellDialectOf(this.#ev.toolName, this.#ev.host) === "powershell" ? "powershell" : undefined;
|
|
2367
2495
|
// a helper's payload cwd is the main thread's, not its shell's: its relative paths count only after a cd to an absolute path
|
|
2368
2496
|
const cwd = cleanId(this.#ev.agentId) === undefined && this.#ev.cwd && this.#guardKit.isAbs(this.#ev.cwd) ? this.#ev.cwd : null;
|
|
2369
2497
|
const scope = writeScope(raw, cwd, { pre: (this.#probe ??= fsProbe(process.env, this.#guardKit)), kit: this.#guardKit, ...(shell ? { shell } : {}) });
|
|
@@ -2417,7 +2545,7 @@ class Context {
|
|
|
2417
2545
|
return true;
|
|
2418
2546
|
if (callText === undefined)
|
|
2419
2547
|
return false;
|
|
2420
|
-
const rollout = c.agentId === undefined ? sf.locate(c.session, this.#now(), this.#opts.
|
|
2548
|
+
const rollout = c.agentId === undefined ? sf.locate(c.session, this.#now(), this.#opts.sessionsDir) : sf.locateHelper?.(c.session, c.agentId, this.#now(), this.#opts.sessionsDir);
|
|
2421
2549
|
const text = rollout === undefined ? undefined : callText(rollout)?.get(id);
|
|
2422
2550
|
return text !== undefined && textNamesBase(text, base);
|
|
2423
2551
|
});
|
|
@@ -2425,7 +2553,7 @@ class Context {
|
|
|
2425
2553
|
// nothing), and a call the tag evidence names as a writer of the file is never dropped for a name.
|
|
2426
2554
|
if (callText === undefined) {
|
|
2427
2555
|
const tagged = this.#state.writeEvidence?.byPath[file]?.calls ?? [];
|
|
2428
|
-
const keep = named.length === 1 && ids.every((id) => isShellTool(this.#state.open[id]?.tool) && (id === named[0] || !tagged.includes(id)));
|
|
2556
|
+
const keep = named.length === 1 && ids.every((id) => isShellTool(this.#state.open[id]?.tool, this.#ev.host) && (id === named[0] || !tagged.includes(id)));
|
|
2429
2557
|
return keep ? named : ids;
|
|
2430
2558
|
}
|
|
2431
2559
|
return named.length > 0 ? named : ids;
|
|
@@ -2450,6 +2578,12 @@ class Context {
|
|
|
2450
2578
|
#hostEdit(rec, credited, origin) {
|
|
2451
2579
|
if (origin === undefined || this.#phase() !== "Post" || this.#failure() !== null)
|
|
2452
2580
|
return false;
|
|
2581
|
+
// An outsider harness (loaded from the person's own folder) never proves a change: its credit stays inferred.
|
|
2582
|
+
if (findProfile(this.#ev.host)?.trust === "outsider")
|
|
2583
|
+
return false;
|
|
2584
|
+
// A before-state rebuilt from a reported edit's own old text would replay to the after-state by construction: it proves nothing.
|
|
2585
|
+
if (rec.prev !== null && (this.#state.rebuilt ?? []).includes(rec.prev))
|
|
2586
|
+
return false;
|
|
2453
2587
|
const file = rec.path;
|
|
2454
2588
|
const kit = pathKit();
|
|
2455
2589
|
const sha256 = (x) => createHash("sha256").update(x).digest("hex");
|
|
@@ -2515,7 +2649,7 @@ class Context {
|
|
|
2515
2649
|
// A read-only shell form never takes write credit, whatever else was open (its command was parsed with no redirect, writing pipe or in-place flag)
|
|
2516
2650
|
if (c?.readOnly === true)
|
|
2517
2651
|
return true;
|
|
2518
|
-
if (!c || !isShellTool(c.tool) || c.scope === undefined || !c.scope.known)
|
|
2652
|
+
if (!c || !isShellTool(c.tool, this.#ev.host) || c.scope === undefined || !c.scope.known)
|
|
2519
2653
|
return false;
|
|
2520
2654
|
const unobserved = this.#state.writeEvidence?.unobserved ?? [];
|
|
2521
2655
|
const facts = {
|
|
@@ -2542,11 +2676,11 @@ class Context {
|
|
|
2542
2676
|
const c = this.#state.open[id];
|
|
2543
2677
|
if (!c)
|
|
2544
2678
|
return undefined;
|
|
2545
|
-
const mayWrite = !isLauncherTool(c.tool) && !isWaitCall(c) && this.#mayCredit(id, file, undefined);
|
|
2679
|
+
const mayWrite = !isLauncherTool(c.tool, this.#ev.host) && !isWaitCall(c, this.#ev.host) && this.#mayCredit(id, file, undefined);
|
|
2546
2680
|
// "logged nothing" counts only for a call whose children provably carried the hook
|
|
2547
2681
|
// per process: as many start records as the command starts hooked interpreters, of each kind
|
|
2548
2682
|
const hooked = c.scope !== undefined && hooksProven(c.scope, c.hookStarts ?? []);
|
|
2549
|
-
return { tool: c.tool, tagged: c.tagged === true, command: c.command, mayWrite, hooked };
|
|
2683
|
+
return { tool: c.tool, host: this.#ev.host, tagged: c.tagged === true, command: c.command, mayWrite, hooked };
|
|
2550
2684
|
};
|
|
2551
2685
|
const writers = strictWriters(file, candidates, hit.calls, facts, new Set(st.unobserved ?? []));
|
|
2552
2686
|
if (writers === undefined)
|
|
@@ -2578,10 +2712,10 @@ class Context {
|
|
|
2578
2712
|
if (call.ended !== undefined && (neverRan(call.ended) || !this.#endingNow.has(id)))
|
|
2579
2713
|
return false;
|
|
2580
2714
|
// A launch is no suspect at a sweep where a call of the agent it launched is open
|
|
2581
|
-
if (!launcherMayCredit(call.tool, Object.values(this.#state.open).some((c) => c.launchToolUseId === id || (c.linkedLaunch === true && c.session === call.session))))
|
|
2715
|
+
if (!launcherMayCredit(call.tool, Object.values(this.#state.open).some((c) => c.launchToolUseId === id || (c.linkedLaunch === true && c.session === call.session)), this.#ev.host))
|
|
2582
2716
|
return false;
|
|
2583
2717
|
const fp = call.toolLabel?.fields?.file_path;
|
|
2584
|
-
return toolMayCredit(call.tool, typeof fp === "string" ? fp : null, file, (a, b) => samePath(a, b, true, this.#guardKit), this.#guardKit);
|
|
2718
|
+
return toolMayCredit(call.tool, typeof fp === "string" ? fp : null, file, (a, b) => samePath(a, b, true, this.#guardKit), this.#guardKit, this.#ev.host);
|
|
2585
2719
|
}
|
|
2586
2720
|
/** Keeps a call's carried entries bounded: one per file (its first step, every note, a copy claim), however many sweeps found it. */
|
|
2587
2721
|
#foldPending(id) {
|
|
@@ -2627,14 +2761,103 @@ class Context {
|
|
|
2627
2761
|
return all;
|
|
2628
2762
|
return all.filter((id) => {
|
|
2629
2763
|
const c = this.#state.open[id];
|
|
2630
|
-
return !(c.agentId === undefined && isWaitCall(c));
|
|
2764
|
+
return !(c.agentId === undefined && isWaitCall(c, this.#ev.host));
|
|
2631
2765
|
});
|
|
2632
2766
|
}
|
|
2633
|
-
|
|
2767
|
+
/** True when this Pre names a call a per-action event of the same session already opened: it is that call. */
|
|
2768
|
+
joinsActionCall() {
|
|
2769
|
+
const id = this.#ev.toolUseId;
|
|
2770
|
+
const open = id ? this.#state.open[id] : undefined;
|
|
2771
|
+
return open !== undefined && open.fromAction === true && open.session === this.#ev.session;
|
|
2772
|
+
}
|
|
2773
|
+
/** A `shell-pre`: the Pre of a shell-class call, unless a call of this id and session is already open (then it is that call). */
|
|
2774
|
+
async actionPre() {
|
|
2775
|
+
const id = this.#ev.toolUseId;
|
|
2776
|
+
const open = id ? this.#state.open[id] : undefined;
|
|
2777
|
+
if (open !== undefined && open.session === this.#ev.session)
|
|
2778
|
+
return;
|
|
2779
|
+
await this.pre(true, true);
|
|
2780
|
+
}
|
|
2781
|
+
/**
|
|
2782
|
+
* A `file-edit`: a file change the host reports after making it. With the id of a call of this session that is open, the edit is that
|
|
2783
|
+
* call's own report: its edits join the call, whose Post proves them like a Write or Edit call's. Otherwise it is a call of its own (the id
|
|
2784
|
+
* the host sent, or one made up) opened and closed here: the change since the last event is credited to the calls open, this one among them,
|
|
2785
|
+
* and proven only by replaying the reported edit on the recorded state. The change is found by the sweep, so it is never credited to another session's call alone.
|
|
2786
|
+
*/
|
|
2787
|
+
async fileEdit() {
|
|
2788
|
+
const id = this.#ev.toolUseId;
|
|
2789
|
+
const open = id ? this.#state.open[id] : undefined;
|
|
2790
|
+
if (open !== undefined && id && open.session === this.#ev.session) {
|
|
2791
|
+
await this.#baseline();
|
|
2792
|
+
const mine = this.#writeIntent();
|
|
2793
|
+
open.writes = [...new Set([...(open.writes ?? []), ...(mine.writes ?? [])])];
|
|
2794
|
+
open.edits = [...new Set([...(open.edits ?? []), ...(mine.edits ?? [])])];
|
|
2795
|
+
const have = new Set((open.reported ?? []).map((r) => r.path));
|
|
2796
|
+
const added = (mine.reported ?? []).filter((r) => !have.has(r.path));
|
|
2797
|
+
if (added.length > 0)
|
|
2798
|
+
open.reported = [...(open.reported ?? []), ...added];
|
|
2799
|
+
if (open.writes.length === 0)
|
|
2800
|
+
delete open.writes;
|
|
2801
|
+
if (open.edits.length === 0)
|
|
2802
|
+
delete open.edits;
|
|
2803
|
+
return;
|
|
2804
|
+
}
|
|
2805
|
+
const taken = id !== undefined && id !== "" && (id in this.#state.open || this.#state.closed.includes(id) || this.#state.expired.includes(id));
|
|
2806
|
+
const own = id === undefined || id === "" || taken ? `file-edit-${++this.#state.seq}` : id;
|
|
2807
|
+
this.#ev = { ...this.#ev, toolUseId: own, synthetic: own !== id, kind: "tool-pre" };
|
|
2808
|
+
// The edit is the first event in the folder: the file already holds the new text. Its state before is the edit undone, so the baseline holds
|
|
2809
|
+
// that and the sweep at this Post shows the change. A before-state that cannot be rebuilt exactly is not guessed.
|
|
2810
|
+
if (!this.#state.init)
|
|
2811
|
+
this.#rebuilt = this.#rebuildBefore();
|
|
2812
|
+
await this.pre(false, true);
|
|
2813
|
+
// The session has no task yet: this edit may be the first thing the hook sees in the folder, already made, so the sweep has nothing to diff it
|
|
2814
|
+
// against. The agent still made it: its op opens the session's task rather than waiting parked, and the change is never left to "outside the agents".
|
|
2815
|
+
const opensTask = !this.#sessionHasWork(this.#ev.session);
|
|
2816
|
+
const firstOp = this.#state.outbox.length;
|
|
2817
|
+
this.#ev = { ...this.#ev, kind: "tool-post" };
|
|
2818
|
+
await this.post();
|
|
2819
|
+
if (opensTask) {
|
|
2820
|
+
const input = this.#ev.toolInput;
|
|
2821
|
+
const file = typeof input?.file_path === "string" && input.file_path !== "" ? this.#rel(input.file_path) : undefined;
|
|
2822
|
+
for (const op of this.#state.outbox.slice(firstOp)) {
|
|
2823
|
+
if (!op.key.startsWith(`${own}#`))
|
|
2824
|
+
continue;
|
|
2825
|
+
op.opens = true;
|
|
2826
|
+
// The op names the file the harness said it edited (never its content).
|
|
2827
|
+
if (file !== undefined)
|
|
2828
|
+
op.args = { ...op.args, namedFiles: [...new Set([...(Array.isArray(op.args.namedFiles) ? op.args.namedFiles : []), file])] };
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
/** The reported edit's file as it was before the edit (see `revertEdits`), for a text file inside the folder; undefined when it cannot be rebuilt exactly. */
|
|
2833
|
+
#rebuildBefore() {
|
|
2834
|
+
const input = this.#ev.toolInput;
|
|
2835
|
+
if (typeof input?.file_path !== "string" || input.file_path === "" || !Array.isArray(input.edits))
|
|
2836
|
+
return undefined;
|
|
2837
|
+
const file = path.resolve(this.#folder, input.file_path);
|
|
2838
|
+
const edits = input.edits.map((e) => (typeof e === "object" && e !== null ? { old: e.old_string, new: e.new_string } : {}));
|
|
2839
|
+
if (!edits.every((e) => typeof e.old === "string" && typeof e.new === "string"))
|
|
2840
|
+
return undefined;
|
|
2841
|
+
try {
|
|
2842
|
+
const st = statSync(file);
|
|
2843
|
+
if (!st.isFile() || st.size > RECONSTRUCT_MAX_BYTES)
|
|
2844
|
+
return undefined;
|
|
2845
|
+
const now = readFileSync(file);
|
|
2846
|
+
const text = now.toString("utf8");
|
|
2847
|
+
if (!Buffer.from(text, "utf8").equals(now))
|
|
2848
|
+
return undefined; // not UTF-8 text: the edit's strings cannot be placed in it
|
|
2849
|
+
const before = revertEdits(text, edits);
|
|
2850
|
+
return before === undefined ? undefined : { file, bytes: Buffer.from(before, "utf8") };
|
|
2851
|
+
}
|
|
2852
|
+
catch {
|
|
2853
|
+
return undefined;
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
async pre(sweepFirst = true, fromAction = false) {
|
|
2634
2857
|
await this.#baseline();
|
|
2635
2858
|
this.#expire();
|
|
2636
2859
|
await this.#baselineOutside();
|
|
2637
|
-
if (this.#opts.heldReplay !== true) {
|
|
2860
|
+
if (this.#opts.heldReplay !== true && sweepFirst) {
|
|
2638
2861
|
const changed = await this.#sweep();
|
|
2639
2862
|
const open = this.#openCalls();
|
|
2640
2863
|
// Calls are running: they share what moved, as at a Post. No call open: nobody made it, it is a hand edit.
|
|
@@ -2648,7 +2871,7 @@ class Context {
|
|
|
2648
2871
|
return;
|
|
2649
2872
|
// This session's next call opens, so its app tails end (after this Pre's sweep, which they may still be credited at).
|
|
2650
2873
|
this.#endTails(cleanId(this.#ev.session), null);
|
|
2651
|
-
const call = { ...this.#callNow(), startSeq: ++this.#state.seq, ...this.#transcriptAt(), ...(this.#opts.taggedCall === true ? { tagged: true } : {}), ...this.#scopeNow() };
|
|
2874
|
+
const call = { ...this.#callNow(), startSeq: ++this.#state.seq, ...this.#transcriptAt(), ...(this.#opts.taggedCall === true ? { tagged: true } : {}), ...this.#scopeNow(), ...(fromAction ? { fromAction: true } : {}) };
|
|
2652
2875
|
// Claude Code writes the call's words to the transcript before its Pre; Codex writes the item after the call, so it is read at Post.
|
|
2653
2876
|
if (this.#ev.narratesBeforeCall)
|
|
2654
2877
|
this.#narrate(id, call, true);
|
|
@@ -2732,8 +2955,8 @@ class Context {
|
|
|
2732
2955
|
const session = this.#ev.session;
|
|
2733
2956
|
if (!this.#ev.sessionFileBySessionId || typeof session !== "string")
|
|
2734
2957
|
return undefined;
|
|
2735
|
-
// The host's own folder layout names the file; `
|
|
2736
|
-
return profileOf(this.#ev.host).sessionFile.locate(session, this.#now(), this.#opts.
|
|
2958
|
+
// The host's own folder layout names the file; `sessionsDir` points a test at a temp tree.
|
|
2959
|
+
return profileOf(this.#ev.host).sessionFile.locate(session, this.#now(), this.#opts.sessionsDir);
|
|
2737
2960
|
}
|
|
2738
2961
|
/**
|
|
2739
2962
|
* The session's place in the host's file, read up to the file's current end; undefined when there is no file. Never throws.
|
|
@@ -2745,7 +2968,7 @@ class Context {
|
|
|
2745
2968
|
const session = this.#ev.session;
|
|
2746
2969
|
let file = this.#sessionFile();
|
|
2747
2970
|
if (agentId !== undefined) {
|
|
2748
|
-
file = this.#ev.helperTranscriptPath ?? (typeof session === "string" ? profileOf(this.#ev.host).sessionFile.locateHelper?.(session, agentId, this.#now(), this.#opts.
|
|
2971
|
+
file = this.#ev.helperTranscriptPath ?? (typeof session === "string" ? profileOf(this.#ev.host).sessionFile.locateHelper?.(session, agentId, this.#now(), this.#opts.sessionsDir) : undefined);
|
|
2749
2972
|
if (file === undefined || !lstatSync(file).isFile())
|
|
2750
2973
|
return undefined;
|
|
2751
2974
|
}
|
|
@@ -2795,7 +3018,7 @@ class Context {
|
|
|
2795
3018
|
const earlier = Object.values(this.#state.open).find((c) => c.session === this.#ev.session && c.agentId === agentId && c.launchToolUseId !== undefined);
|
|
2796
3019
|
if (earlier !== undefined)
|
|
2797
3020
|
return earlier.launchToolUseId;
|
|
2798
|
-
const launches = Object.entries(this.#state.open).filter(([, c]) => c.session === this.#ev.session && c.agentId === undefined && isLauncherTool(c.tool));
|
|
3021
|
+
const launches = Object.entries(this.#state.open).filter(([, c]) => c.session === this.#ev.session && c.agentId === undefined && isLauncherTool(c.tool, this.#ev.host));
|
|
2799
3022
|
// The helper's first prompt matched exactly one launch; its args key finds that launch among those open, even with several open.
|
|
2800
3023
|
if (this.#ev.launchKey !== undefined) {
|
|
2801
3024
|
const named = launches.filter(([, c]) => c.argsKey === this.#ev.launchKey);
|
|
@@ -2809,6 +3032,7 @@ class Context {
|
|
|
2809
3032
|
const input = (this.#ev.toolInput ?? {});
|
|
2810
3033
|
// A connector's command and description are input values, which are not stored.
|
|
2811
3034
|
const own = !isMcpTool(this.#ev.toolName);
|
|
3035
|
+
const callReason = profileOf(this.#ev.host).fields.callReason;
|
|
2812
3036
|
const agentId = cleanId(this.#ev.agentId);
|
|
2813
3037
|
const agentType = cleanId(this.#ev.agentType, true);
|
|
2814
3038
|
const launchToolUseId = agentId === undefined ? undefined : agentLauncher(this.#ev.host, this.#ev.transcriptPath, this.#ev.session, agentId) ?? this.#openLauncherOf(agentId);
|
|
@@ -2819,13 +3043,13 @@ class Context {
|
|
|
2819
3043
|
session: this.#ev.session,
|
|
2820
3044
|
...(agentId === undefined ? {} : { agentId, ...(agentType === undefined ? {} : { agentType }), ...(launchToolUseId === undefined ? {} : { launchToolUseId }), ...(this.#ev.launchKey !== undefined && launchToolUseId !== undefined ? { linkedLaunch: true } : {}) }),
|
|
2821
3045
|
command: this.#redact(own && typeof input.command === "string" ? input.command : ""),
|
|
2822
|
-
description: this.#redact(own && typeof input
|
|
3046
|
+
description: this.#redact(own && callReason !== undefined && typeof input[callReason] === "string" ? input[callReason] : ""),
|
|
2823
3047
|
toolLabel: this.#label(),
|
|
2824
3048
|
...this.#turnPrompt(agentId),
|
|
2825
3049
|
at: this.#now(),
|
|
2826
3050
|
...this.#reach(),
|
|
2827
3051
|
...(input.run_in_background === true ? { background: true } : {}),
|
|
2828
|
-
...(waitsOnHelpers(this.#ev.toolName, input) ? { waits: true } : {}),
|
|
3052
|
+
...(waitsOnHelpers(this.#ev.toolName, input, this.#ev.host) ? { waits: true } : {}),
|
|
2829
3053
|
...this.#writeIntent(),
|
|
2830
3054
|
};
|
|
2831
3055
|
}
|
|
@@ -2837,20 +3061,20 @@ class Context {
|
|
|
2837
3061
|
#writeIntent() {
|
|
2838
3062
|
const input = this.#ev.toolInput;
|
|
2839
3063
|
const rel = (p) => path.resolve(this.#cwd(), p);
|
|
2840
|
-
const writes = [...new Set(writeTargetsOf(this.#ev.toolName, input).filter((p) => !p.startsWith("~")).map(rel).filter((p) => !this.#isOutside(p) && !isDeliveryPath(this.#folder, p) && !isHomePath(this.#opts.home, p)))];
|
|
3064
|
+
const writes = [...new Set(writeTargetsOf(this.#ev.toolName, input, this.#ev.host).filter((p) => !p.startsWith("~")).map(rel).filter((p) => !this.#isOutside(p) && !isDeliveryPath(this.#folder, p) && !isHomePath(this.#opts.home, p)))];
|
|
2841
3065
|
const command = typeof input === "object" && input !== null ? input.command : undefined;
|
|
2842
|
-
const readOnly = isShellTool(this.#ev.toolName) && typeof command === "string" && isReadOnlyCommand(command);
|
|
2843
|
-
const edits = editTargetsOf(this.#ev.toolName, input, (p) => pathKit().isAbs(p), rel)?.filter((p) => !this.#isOutside(p) && !isDeliveryPath(this.#folder, p) && !isHomePath(this.#opts.home, p));
|
|
2844
|
-
const reported = edits === undefined ? [] : reportedEditsOf(this.#ev.toolName, input, (p) => pathKit().isAbs(p), (t) => createHash("sha256").update(t, "utf8").digest("hex"), rel).filter((c) => !this.#isOutside(c.path) && !isDeliveryPath(this.#folder, c.path) && !isHomePath(this.#opts.home, c.path));
|
|
3066
|
+
const readOnly = isShellTool(this.#ev.toolName, this.#ev.host) && typeof command === "string" && isReadOnlyCommand(command);
|
|
3067
|
+
const edits = editTargetsOf(this.#ev.toolName, input, (p) => pathKit().isAbs(p), rel, this.#ev.host)?.filter((p) => !this.#isOutside(p) && !isDeliveryPath(this.#folder, p) && !isHomePath(this.#opts.home, p));
|
|
3068
|
+
const reported = edits === undefined ? [] : reportedEditsOf(this.#ev.toolName, input, (p) => pathKit().isAbs(p), (t) => createHash("sha256").update(t, "utf8").digest("hex"), rel, this.#ev.host).filter((c) => !this.#isOutside(c.path) && !isDeliveryPath(this.#folder, c.path) && !isHomePath(this.#opts.home, c.path));
|
|
2845
3069
|
// The input is already scrubbed at the entry (normalize.ts): a withheld section has no replay, so that file keeps inferred credit.
|
|
2846
3070
|
const kept = reported.filter((c) => !(c.sections ?? []).some((s) => isWithheldSection(s.lines)));
|
|
2847
3071
|
const cwd = this.#ev.cwd;
|
|
2848
|
-
const patchRead = isPatchTool(this.#ev.toolName)
|
|
3072
|
+
const patchRead = isPatchTool(this.#ev.toolName, this.#ev.host)
|
|
2849
3073
|
? {
|
|
2850
3074
|
input: input === undefined ? "none" : input === null ? "null" : Array.isArray(input) ? "array" : typeof input,
|
|
2851
3075
|
quoted: typeof input === "string" && /^\s*"/.test(input),
|
|
2852
3076
|
cwd: cwd === undefined || cwd === "" ? "absent" : /^[A-Za-z]:\\/.test(cwd) ? "drive-backslash" : /^[A-Za-z]:\//.test(cwd) ? "drive-slash" : cwd.startsWith("/") ? "posix" : /^\\\\/.test(cwd) ? "unc" : "other",
|
|
2853
|
-
named: writeTargetsOf(this.#ev.toolName, input).length,
|
|
3077
|
+
named: writeTargetsOf(this.#ev.toolName, input, this.#ev.host).length,
|
|
2854
3078
|
inside: (edits ?? []).length,
|
|
2855
3079
|
reported: kept.length,
|
|
2856
3080
|
}
|
|
@@ -2900,7 +3124,7 @@ class Context {
|
|
|
2900
3124
|
}
|
|
2901
3125
|
/** The call's safe label; with outside watching off, paths outside the folder and path-like words are masked first. */
|
|
2902
3126
|
#label() {
|
|
2903
|
-
const text = (s) => (this.#ev.toolName
|
|
3127
|
+
const text = (s) => (shellDialectOf(this.#ev.toolName, this.#ev.host) === "bash" ? this.#redact(s) : this.#redactWords(s));
|
|
2904
3128
|
const mask = (p) => {
|
|
2905
3129
|
if (this.#on())
|
|
2906
3130
|
return p;
|
|
@@ -2961,7 +3185,7 @@ class Context {
|
|
|
2961
3185
|
if (rewrote.length > 0)
|
|
2962
3186
|
call.sameBytes = [...new Set([...(call.sameBytes ?? []), ...rewrote])].sort();
|
|
2963
3187
|
this.#narrate(id, call);
|
|
2964
|
-
if (call.background && !isLauncherTool(call.tool)) {
|
|
3188
|
+
if (call.background && !isLauncherTool(call.tool, this.#ev.host)) {
|
|
2965
3189
|
// The job outlives its Post: keep it open, with what this Post found, so its later writes are joint with it.
|
|
2966
3190
|
appendAll((this.#state.pending[id] ??= []), own);
|
|
2967
3191
|
this.#foldPending(id);
|
|
@@ -2995,7 +3219,7 @@ class Context {
|
|
|
2995
3219
|
const agent = call === undefined ? cleanId(ev.agentId) : call.agentId;
|
|
2996
3220
|
// The call's own start time places the rollout's day folder; the clock is read only when there is no open call (reading it moves a test clock).
|
|
2997
3221
|
const at = call?.at ?? this.#now();
|
|
2998
|
-
const rollout = agent === undefined ? sf.locate(session, at, this.#opts.
|
|
3222
|
+
const rollout = agent === undefined ? sf.locate(session, at, this.#opts.sessionsDir) : sf.locateHelper?.(session, agent, at, this.#opts.sessionsDir);
|
|
2999
3223
|
const hit = rollout === undefined ? undefined : sf.callExit(rollout)?.get(id);
|
|
3000
3224
|
if (hit === undefined)
|
|
3001
3225
|
return ev;
|
|
@@ -3390,7 +3614,7 @@ function opKeyOf(argsJson) {
|
|
|
3390
3614
|
return undefined;
|
|
3391
3615
|
}
|
|
3392
3616
|
/**
|
|
3393
|
-
* The named-file miss rate for a task (criterion 3 of the probe): of the calls that changed a
|
|
3617
|
+
* The named-file miss rate for a task (criterion 3 of the probe): of the calls that changed a file
|
|
3394
3618
|
* themselves, how many changed one their input did not name. Overlap-attributed changes belong to no call
|
|
3395
3619
|
* alone and are left out. Not a gate; it sizes how much rests on the diff rather than on the call's own words.
|
|
3396
3620
|
*/
|