pi-crew 0.11.50 → 0.11.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +143 -0
- package/dist/index.mjs +552 -545
- package/package.json +1 -1
- package/src/agents/agent-config.ts +58 -1
- package/src/config/config-validation.ts +18 -0
- package/src/config/env-allowlist-registry.ts +4 -0
- package/src/config/env-vars.ts +4 -0
- package/src/config/sanitize-project-config.ts +55 -0
- package/src/extension/management.ts +9 -0
- package/src/extension/registration/lifecycle-handlers.ts +28 -0
- package/src/extension/registration/subagent-tools.ts +5 -1
- package/src/extension/run-import.ts +40 -6
- package/src/extension/team-tool/api/agent-control.ts +49 -0
- package/src/extension/team-tool/api/heartbeat.ts +48 -1
- package/src/extension/team-tool/api/mailbox.ts +81 -2
- package/src/extension/team-tool/api/read.ts +22 -0
- package/src/extension/team-tool/api/task-claims.ts +134 -3
- package/src/extension/team-tool/cancel.ts +15 -1
- package/src/extension/team-tool/destructive-gate.ts +92 -8
- package/src/extension/team-tool/inspect.ts +8 -2
- package/src/extension/team-tool/lifecycle-actions.ts +9 -2
- package/src/extension/team-tool.ts +128 -27
- package/src/observability/exporters/otlp-exporter.ts +69 -19
- package/src/prompt/message-tool.ts +19 -8
- package/src/prompt/prompt-runtime.ts +160 -51
- package/src/runtime/background-runner.ts +101 -81
- package/src/runtime/broker/crew-broker-child.ts +32 -0
- package/src/runtime/broker/crew-broker-tokens.ts +24 -13
- package/src/runtime/broker/crew-broker.ts +12 -6
- package/src/runtime/broker/protocol/wait-resolve.ts +15 -1
- package/src/runtime/child-pi/child-pi-spawn.ts +17 -0
- package/src/runtime/child-pi/child-pi-steering.ts +8 -1
- package/src/runtime/child-pi/inference-broker.ts +41 -7
- package/src/runtime/child-pi/pi-version.ts +31 -3
- package/src/runtime/child-pi/sandbox.ts +38 -1
- package/src/runtime/dwf-state-store.ts +193 -7
- package/src/runtime/foreground-control.ts +95 -1
- package/src/runtime/goal-workflow/dynamic-workflow-context.ts +48 -7
- package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +82 -6
- package/src/runtime/heartbeat/heartbeat-watcher.ts +32 -11
- package/src/runtime/live-session/live-session-runtime.ts +78 -3
- package/src/runtime/mcp-proxy.ts +65 -6
- package/src/runtime/model/pi-args.ts +16 -15
- package/src/runtime/plan-replan.ts +4 -1
- package/src/runtime/task-runner/child-executor.ts +34 -7
- package/src/runtime/task-runner/hybrid-tier.ts +17 -0
- package/src/runtime/task-runner/live-executor.ts +3 -0
- package/src/runtime/task-runner/post-execution.ts +5 -0
- package/src/runtime/task-runner/pre-execution.ts +13 -6
- package/src/runtime/task-runner.ts +14 -0
- package/src/runtime/team-runner.ts +26 -0
- package/src/runtime/verification/verification-worktree.ts +46 -29
- package/src/runtime/verification/verify-gate-memo.ts +211 -32
- package/src/runtime/verification/verify-gate.ts +266 -14
- package/src/runtime/workspace-lock.ts +95 -21
- package/src/schema/config-schema.ts +12 -2
- package/src/state/coordination/locks.ts +86 -19
- package/src/state/coordination/mailbox.ts +263 -22
- package/src/state/stores/manifest-io.ts +206 -7
- package/src/state/stores/state-store.ts +44 -15
- package/src/state/types.ts +9 -0
- package/src/ui/inline-panel/agent-transcript.ts +151 -11
- package/src/ui/settings-overlay.ts +8 -3
- package/src/ui/theme-discovery.ts +14 -2
- package/src/ui/tool-renderers/index.ts +26 -6
- package/src/utils/safe-terminal-text.ts +60 -0
- package/src/worktree/git-hardening.ts +78 -1
- package/src/worktree/worktree-manager.ts +34 -4
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import * as fs from "node:fs";
|
|
23
23
|
import * as path from "node:path";
|
|
24
24
|
import { withRunLockSync } from "../state/coordination/locks.ts";
|
|
25
|
+
import { signSteeringEntry } from "../state/coordination/mailbox.ts";
|
|
25
26
|
import { appendEvent } from "../state/event-log/event-log.ts";
|
|
26
27
|
import { getCurrentPlanRecord } from "../state/stores/plan-store.ts";
|
|
27
28
|
import { loadRunManifestById, saveRunManifest, saveRunTasks } from "../state/stores/state-store.ts";
|
|
@@ -56,7 +57,9 @@ function appendSteeringAdvisory(manifest: TeamRunManifest, taskId: string): bool
|
|
|
56
57
|
}
|
|
57
58
|
fs.appendFileSync(
|
|
58
59
|
safePath,
|
|
59
|
-
|
|
60
|
+
// w1a sender binding: sign the advisory line (steering file is same-uid
|
|
61
|
+
// writable; worker pollSteering drops unauthenticated lines).
|
|
62
|
+
`${JSON.stringify(signSteeringEntry({ type: "steer", message: WRAP_UP_ADVISORY, ts: new Date().toISOString() }))}\n`,
|
|
60
63
|
"utf-8",
|
|
61
64
|
);
|
|
62
65
|
return true;
|
|
@@ -31,6 +31,7 @@ import { loadConfig } from "../../config/config.ts";
|
|
|
31
31
|
import { getCrewEnv, getCrewEnvInt } from "../../config/env-vars.ts";
|
|
32
32
|
import { errors } from "../../errors.ts";
|
|
33
33
|
import type { MetricRegistry } from "../../observability/metric-registry.ts";
|
|
34
|
+
import { signSteeringEntry } from "../../state/coordination/mailbox.ts";
|
|
34
35
|
import { appendEventAsync, appendEventBuffered } from "../../state/event-log/event-log.ts";
|
|
35
36
|
import { writeArtifact } from "../../state/stores/artifact-store.ts";
|
|
36
37
|
import { upsertOwnershipEntry } from "../../state/stores/ownership-map.ts";
|
|
@@ -86,14 +87,19 @@ async function appendSteeringAsync(steeringDir: string, taskId: string, steers:
|
|
|
86
87
|
try {
|
|
87
88
|
await fs.promises.mkdir(steeringDir, { recursive: true });
|
|
88
89
|
const steeringPath = resolveRealContainedPath(steeringDir, `${taskId}.jsonl`);
|
|
90
|
+
// w1a sender binding: the steering file is same-uid writable — each line
|
|
91
|
+
// carries this process's Ed25519 signature (worker pollSteering drops
|
|
92
|
+
// unauthenticated lines).
|
|
89
93
|
const lines = steers
|
|
90
94
|
.map(
|
|
91
95
|
(msg) =>
|
|
92
|
-
JSON.stringify(
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
96
|
+
JSON.stringify(
|
|
97
|
+
signSteeringEntry({
|
|
98
|
+
type: "steer",
|
|
99
|
+
message: msg,
|
|
100
|
+
ts: new Date().toISOString(),
|
|
101
|
+
}),
|
|
102
|
+
) + "\n",
|
|
97
103
|
)
|
|
98
104
|
.join("");
|
|
99
105
|
await fs.promises.appendFile(steeringPath, lines, "utf-8");
|
|
@@ -633,6 +639,13 @@ export async function runChildProcessTask(ctx: TaskExecutionContext): Promise<Ta
|
|
|
633
639
|
let lastRunProgressPersistedAt = 0;
|
|
634
640
|
let lastTaskProgressPersistedAt = 0;
|
|
635
641
|
let lastRunProgressSummary: ProgressEventSummary | undefined;
|
|
642
|
+
// FIX-2 (live catch, run team_20261030044630): the current attempt's worker
|
|
643
|
+
// pid, pinned by onSpawn below (hoisted to task scope so the
|
|
644
|
+
// persistHeartbeat closure can pin it into task.heartbeat — see the touch
|
|
645
|
+
// below). Reset to undefined at the TOP of each model-fallback attempt:
|
|
646
|
+
// each iteration spawns a fresh worker process, and a dead prior-attempt
|
|
647
|
+
// pid must never masquerade as this attempt's liveness evidence.
|
|
648
|
+
let attemptWorkerPid: number | undefined;
|
|
636
649
|
const persistHeartbeat = (force = false): void => {
|
|
637
650
|
const now = Date.now();
|
|
638
651
|
// Skip disk write if throttled (unless forced).
|
|
@@ -651,9 +664,21 @@ export async function runChildProcessTask(ctx: TaskExecutionContext): Promise<Ta
|
|
|
651
664
|
throw err;
|
|
652
665
|
}
|
|
653
666
|
// Now update in-memory heartbeat so it is always >= persisted state.
|
|
667
|
+
// FIX-2: pin the current attempt's worker pid so the heartbeat-watcher
|
|
668
|
+
// PID-liveness gate (heartbeat?.pid ?? checkpoint?.childPid — it
|
|
669
|
+
// downgrades dead→stale when the worker process is ALIVE) actually has
|
|
670
|
+
// something to read for child-process tasks. In the live run every
|
|
671
|
+
// task.heartbeat had pid:undefined, so a >5min-silent-but-alive worker
|
|
672
|
+
// could not be vindicated. Guarded: only overwrite when a pid is known —
|
|
673
|
+
// an unconditional spread would stamp pid:undefined over an
|
|
674
|
+
// already-pinned pid (call shapes pinned in
|
|
675
|
+
// child-executor-heartbeat-pid.test.ts).
|
|
654
676
|
task = {
|
|
655
677
|
...task,
|
|
656
|
-
heartbeat: touchWorkerHeartbeat(
|
|
678
|
+
heartbeat: touchWorkerHeartbeat(
|
|
679
|
+
task.heartbeat ?? createWorkerHeartbeat(task.id, attemptWorkerPid),
|
|
680
|
+
attemptWorkerPid !== undefined ? { pid: attemptWorkerPid } : {},
|
|
681
|
+
),
|
|
657
682
|
};
|
|
658
683
|
lastHeartbeatPersistedAt = now;
|
|
659
684
|
};
|
|
@@ -789,7 +814,9 @@ export async function runChildProcessTask(ctx: TaskExecutionContext): Promise<Ta
|
|
|
789
814
|
// evidence of an in-flight incarnation; touch (fail-open, bounded:
|
|
790
815
|
// real spawns pin the pid within ms, and the reconciler's ESRCH
|
|
791
816
|
// verdict can never be overridden by a fresh heartbeat).
|
|
792
|
-
let attemptWorkerPid
|
|
817
|
+
// FIX-2: no `let` here — attemptWorkerPid is hoisted to task scope
|
|
818
|
+
// (persistHeartbeat pins it into task.heartbeat); reset per attempt.
|
|
819
|
+
attemptWorkerPid = undefined;
|
|
793
820
|
const heartbeatPulse = startWorkerHeartbeatPulse({
|
|
794
821
|
intervalMs: resolveHeartbeatPulseIntervalMs(),
|
|
795
822
|
isAlive: () => {
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
*/
|
|
47
47
|
|
|
48
48
|
import type { CrewRuntimeConfig } from "../../config/config.ts";
|
|
49
|
+
import { embeddedTierRefusedBySandbox, embeddedTierSandboxRefusalReason } from "../../config/sanitize-project-config.ts";
|
|
49
50
|
import { flushPendingAtomicWrites } from "../../state/atomic-write.ts";
|
|
50
51
|
import { appendEventFireAndForget } from "../../state/event-log/event-log.ts";
|
|
51
52
|
import { loadRunManifestById } from "../../state/stores/state-store.ts";
|
|
@@ -180,6 +181,22 @@ export function planEmbeddedTier(input: PlanEmbeddedTierInput): EmbeddedTierPlan
|
|
|
180
181
|
const threshold = resolveEmbeddedFaultThreshold(policy);
|
|
181
182
|
const env = input.env ?? process.env;
|
|
182
183
|
const { manifest } = input;
|
|
184
|
+
// w4b defense-in-depth wiring (SEC-2026-11 embeddedWorkers.project-tier-routing):
|
|
185
|
+
// a live sandbox posture (PI_CREW_SANDBOX=bwrap) means the user opted into an
|
|
186
|
+
// OS boundary around workers. The embedded tier runs IN-PROCESS with neither
|
|
187
|
+
// the bwrap boundary nor the child-env secret scrub, so routing would void
|
|
188
|
+
// that opt-in. Fail closed: refuse embedded routing (subprocess tier keeps
|
|
189
|
+
// the sandbox), with a visible tier.decision warning.
|
|
190
|
+
if (embeddedTierRefusedBySandbox(env)) {
|
|
191
|
+
appendEventFireAndForget(manifest.eventsPath, {
|
|
192
|
+
type: "tier.decision",
|
|
193
|
+
runId: manifest.runId,
|
|
194
|
+
taskId: input.task.id,
|
|
195
|
+
message: embeddedTierSandboxRefusalReason(env),
|
|
196
|
+
data: { route: "subprocess", to: input.baseRuntimeKind, reason: "sandbox-opt-in" },
|
|
197
|
+
});
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
183
200
|
const resolved = resolveTaskRuntimeKind(input.baseRuntimeKind, input.role, input.isolationPolicy, env, {
|
|
184
201
|
policy,
|
|
185
202
|
faultCount,
|
|
@@ -207,6 +207,9 @@ export async function runLiveTask(input: RunLiveTaskInput): Promise<RunLiveTaskO
|
|
|
207
207
|
if (!isCurrent()) return;
|
|
208
208
|
const now = Date.now();
|
|
209
209
|
if (!force && now - lastHeartbeatPersistedAt < 1000) return;
|
|
210
|
+
// FIX-2 note: no pid at write time — live-session workers run IN this
|
|
211
|
+
// process (no child pid exists); the watcher PID-gate stays unarmed for
|
|
212
|
+
// live-session tasks (their activity stream is the liveness evidence).
|
|
210
213
|
task = {
|
|
211
214
|
...task,
|
|
212
215
|
heartbeat: touchWorkerHeartbeat(task.heartbeat ?? createWorkerHeartbeat(task.id)),
|
|
@@ -386,6 +386,9 @@ export async function finalizeTaskResult(ctx: TaskExecutionContext, execResult:
|
|
|
386
386
|
exitCode: null,
|
|
387
387
|
error: undefined,
|
|
388
388
|
claim: undefined,
|
|
389
|
+
// FIX-2 note: no pid at write time — this terminal touch only marks
|
|
390
|
+
// alive:false on the EXISTING heartbeat (worker already exited); a
|
|
391
|
+
// live pid is pinned at spawn by child-executor's persistHeartbeat.
|
|
389
392
|
heartbeat: touchWorkerHeartbeat(task.heartbeat ?? createWorkerHeartbeat(task.id), { alive: false }),
|
|
390
393
|
terminalEvidence: terminalEvidence.length ? [...(task.terminalEvidence ?? []), ...terminalEvidence] : task.terminalEvidence,
|
|
391
394
|
diagnostics: {
|
|
@@ -880,6 +883,8 @@ export async function finalizeTaskResult(ctx: TaskExecutionContext, execResult:
|
|
|
880
883
|
...(specGate ? { specGate } : {}),
|
|
881
884
|
resultArtifact,
|
|
882
885
|
claim: undefined,
|
|
886
|
+
// FIX-2 note: no pid at write time — terminal touch, worker already
|
|
887
|
+
// exited; the live pid was pinned at spawn (child-executor).
|
|
883
888
|
heartbeat: touchWorkerHeartbeat(task.heartbeat ?? createWorkerHeartbeat(task.id), { alive: false }),
|
|
884
889
|
terminalEvidence: terminalEvidence.length ? [...(task.terminalEvidence ?? []), ...terminalEvidence] : task.terminalEvidence,
|
|
885
890
|
...(logArtifact ? { logArtifact } : {}),
|
|
@@ -272,19 +272,26 @@ export async function prepareTaskExecutionContext(
|
|
|
272
272
|
|
|
273
273
|
// Deterministic pre-step: run script, inject stdout into worker prompt
|
|
274
274
|
let preStepOutput: string | undefined;
|
|
275
|
-
if (input.step.preStepScript && input.step.source !== "builtin"
|
|
276
|
-
// F-02 SECURITY FIX (allowlist): only builtin
|
|
277
|
-
// execute pre-step scripts. Project-sourced AND programmatic
|
|
275
|
+
if (input.step.preStepScript && input.step.source !== "builtin") {
|
|
276
|
+
// F-02 SECURITY FIX (allowlist, w3-dwf-trust tightening): only builtin-sourced
|
|
277
|
+
// workflows may execute pre-step scripts. Project-sourced AND programmatic
|
|
278
278
|
// (source=undefined) steps are denied — a hostile repo clone could embed
|
|
279
279
|
// arbitrary code via preStepScript + execFileSync, and steps constructed
|
|
280
280
|
// without explicit trusted provenance should not auto-trust file
|
|
281
|
-
// execution.
|
|
282
|
-
//
|
|
281
|
+
// execution. The 'user' tier was REMOVED from the allowlist (w3-dwf-trust,
|
|
282
|
+
// 2026-10-29): ~/.pi/agent/workflows is writable by every WRITE-role child
|
|
283
|
+
// worker (same OS uid), so a planted user-tier *.workflow.md carrying a
|
|
284
|
+
// preStepScript previously executed it via execFileSync in this HOST
|
|
285
|
+
// process (F-02 only stripped project scripts at the discover layer).
|
|
286
|
+
// Deny by default; re-introduce via an explicit dispatch-time hash pin if a
|
|
287
|
+
// legitimate user-tier pre-step need appears (see
|
|
288
|
+
// TeamRunManifest.dynamicScriptPin). discover-workflows strips project
|
|
289
|
+
// scripts upstream so legitimate builtin scripts still run.
|
|
283
290
|
appendEventFireAndForget(manifest.eventsPath, {
|
|
284
291
|
type: "hook.pre_step_skipped",
|
|
285
292
|
runId: manifest.runId,
|
|
286
293
|
taskId: task.id,
|
|
287
|
-
message: `preStepScript '${input.step.preStepScript}' skipped: only builtin
|
|
294
|
+
message: `preStepScript '${input.step.preStepScript}' skipped: only builtin-sourced workflows may execute pre-step scripts for security (F-02; user tier tightened in w3-dwf-trust — user config dirs are writable by same-uid workers).`,
|
|
288
295
|
data: { script: input.step.preStepScript, source: input.step.source ?? "unknown" },
|
|
289
296
|
});
|
|
290
297
|
preStepOutput = undefined;
|
|
@@ -182,6 +182,20 @@ export async function runTeamTask(input: TaskRunnerInput): Promise<{ manifest: T
|
|
|
182
182
|
// package.json. Absent (old manifests / goal-loop runs) ⇒ the gate
|
|
183
183
|
// resolves no checks ⇒ INCONCLUSIVE ⇒ verifier spawns (fail-closed).
|
|
184
184
|
...(manifest.verifyGateSpec ? { hostSpec: manifest.verifyGateSpec } : {}),
|
|
185
|
+
// W2 (worktree-verifier-gate-excludes-work): a green gate in THIS
|
|
186
|
+
// task's tree must never certify dependency work it cannot see —
|
|
187
|
+
// probe each dependency task's worktree; uncommitted work there
|
|
188
|
+
// forces the LLM verifier spawn even on a PASS verdict (reason
|
|
189
|
+
// "unverified_worktree_work"). Shared-cwd deps (no worktree) need
|
|
190
|
+
// no probe — their work is inside the gate's own cwd.
|
|
191
|
+
...(ctx.task.dependsOn.length > 0
|
|
192
|
+
? {
|
|
193
|
+
dependencyWorktreeProbes: ctx.task.dependsOn.map((depId) => ({
|
|
194
|
+
taskId: depId,
|
|
195
|
+
worktreePath: ctx.tasks.find((t) => t.id === depId)?.worktree?.path,
|
|
196
|
+
})),
|
|
197
|
+
}
|
|
198
|
+
: {}),
|
|
185
199
|
signal: input.signal,
|
|
186
200
|
classifier: {
|
|
187
201
|
enabled: resolveClassifierEnabled(input.runtimeConfig?.classifierEnabled),
|
|
@@ -158,6 +158,16 @@ function startPerfSampler(manifest: TeamRunManifest, team: TeamConfig, signal?:
|
|
|
158
158
|
{ detached: true, stdio: ["ignore", "ignore", "pipe"], signal },
|
|
159
159
|
);
|
|
160
160
|
// diagnostics: sampler stderr → perf-obs.log (best-effort; never affects the run)
|
|
161
|
+
// Abort-safety (B6 mirror, child-pi.ts taskkill): the sampler is spawned
|
|
162
|
+
// WITH the run AbortSignal (R11-4 teardown-kill) but detached+unref'd, so it
|
|
163
|
+
// can exit BEFORE the signal fires — Node's spawn-signal listener then
|
|
164
|
+
// throws AbortError synchronously AND emits 'error' on the ChildProcess;
|
|
165
|
+
// without a listener that emission is an uncaught exception that kills the
|
|
166
|
+
// host (observed: run-deadline abort ~300ms into a resumed run raced the
|
|
167
|
+
// sampler's exit). The listener keeps abort-after-exit bounded.
|
|
168
|
+
child.on("error", (err: Error) => {
|
|
169
|
+
logInternalError("team-runner.perf-sampler.child-error", err, `runId=${manifest.runId}`, "warn");
|
|
170
|
+
});
|
|
161
171
|
child.stderr?.on("data", (d: Buffer) => {
|
|
162
172
|
try {
|
|
163
173
|
fs.appendFileSync(logPath, String(d));
|
|
@@ -382,6 +392,22 @@ export async function executeTeamRun(input: ExecuteTeamRunInput): Promise<{ mani
|
|
|
382
392
|
{ allowTerminalExit: input.isResume === true },
|
|
383
393
|
);
|
|
384
394
|
|
|
395
|
+
// Manifest-derived re-arm (resume-disarms-run-budget-enforcement fix): a caller
|
|
396
|
+
// that reconstructs the input without budget fields (handleResume static-path
|
|
397
|
+
// re-entry) must not silently disarm the operator's persisted spend cap —
|
|
398
|
+
// enforceRunBudget gates solely on ctx.input.budgetTotal (budget-enforcement.ts)
|
|
399
|
+
// and the manifest budget is persisted input→manifest only, so persistence
|
|
400
|
+
// alone never re-arms enforcement on a later execution. Seed any missing input
|
|
401
|
+
// budget fields from the loaded manifest BEFORE the persist block so EVERY
|
|
402
|
+
// execution of the same run keeps its declared bounds regardless of caller
|
|
403
|
+
// diligence. Caller-supplied values (dispatch paths forward params.budget*,
|
|
404
|
+
// detached re-entry forwards manifest.budget*) always win — `??=` never
|
|
405
|
+
// overrides an explicitly forwarded field.
|
|
406
|
+
input.budgetTotal ??= manifest.budgetTotal;
|
|
407
|
+
input.budgetWarning ??= manifest.budgetWarning;
|
|
408
|
+
input.budgetAbort ??= manifest.budgetAbort;
|
|
409
|
+
input.budgetUnlimited ??= manifest.budgetUnlimited;
|
|
410
|
+
|
|
385
411
|
// Persist budget fields on the manifest so all subsequent saveRunManifest
|
|
386
412
|
// calls (there are many in executeTeamRunCore) preserve the budget config.
|
|
387
413
|
// Without this, the spread in updateRunStatus and other transformations
|
|
@@ -26,6 +26,7 @@ import * as fs from "node:fs";
|
|
|
26
26
|
import * as os from "node:os";
|
|
27
27
|
import * as path from "node:path";
|
|
28
28
|
import { getCrewEnv } from "../../config/env-vars.ts";
|
|
29
|
+
import { assertWorktreePointerTrusted, buildGitSafeEnv, hardenGitArgs } from "../../worktree/git-hardening.ts";
|
|
29
30
|
|
|
30
31
|
export interface VerificationWorktree {
|
|
31
32
|
/** Absolute path to the pristine worktree directory. */
|
|
@@ -42,6 +43,36 @@ export function isWorktreeSandboxEnabled(): boolean {
|
|
|
42
43
|
return v === "1" || v === "true";
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
/**
|
|
47
|
+
* MED-1 / R-A7 (uniformity, w9-n4): the ONLY execFileSync("git", …) site in
|
|
48
|
+
* this module — every git invocation routes through the same composition
|
|
49
|
+
* worktree-manager.ts applies via its git() helper (worktree-manager.ts:57-67):
|
|
50
|
+
* - hardenGitArgs — `-c core.fsmonitor=false -c core.hooksPath= -c
|
|
51
|
+
* core.attributesFile=` prefix neutralizing config-reachable helper
|
|
52
|
+
* execution (audit PoC: raw `git status --porcelain` at a repo whose
|
|
53
|
+
* config — own or via a hijacked linked-worktree gitdir — sets
|
|
54
|
+
* core.fsmonitor spawns the helper in THIS process; hardened argv does not);
|
|
55
|
+
* - buildGitSafeEnv — allowlist-sanitized env instead of full host-env
|
|
56
|
+
* inheritance (also strips env-injected config: GIT_CONFIG_COUNT etc.);
|
|
57
|
+
* - assertWorktreePointerTrusted (R-A3) — fail-closed gitdir-pointer trust
|
|
58
|
+
* check paid before EVERY command; no-op for main-repo / non-git cwd,
|
|
59
|
+
* throws `worktree corrupted: …` inside a linked worktree whose `.git`
|
|
60
|
+
* pointer no longer matches the git registry. The assert runs OUTSIDE the
|
|
61
|
+
* execFile call so callers keep their existing throw handling: the sandbox
|
|
62
|
+
* precondition check reports `available:false` and cleanup stays best-effort.
|
|
63
|
+
*/
|
|
64
|
+
function hardenedVerificationGit(cwd: string, args: string[], timeout: number): string {
|
|
65
|
+
assertWorktreePointerTrusted(cwd);
|
|
66
|
+
return execFileSync("git", hardenGitArgs(args), {
|
|
67
|
+
cwd,
|
|
68
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
69
|
+
encoding: "utf-8",
|
|
70
|
+
timeout,
|
|
71
|
+
env: buildGitSafeEnv("en_US.UTF-8"),
|
|
72
|
+
windowsHide: true,
|
|
73
|
+
}).trim();
|
|
74
|
+
}
|
|
75
|
+
|
|
45
76
|
/**
|
|
46
77
|
* Detect whether the worktree sandbox is AVAILABLE at `cwd`:
|
|
47
78
|
* - opt-in env var set
|
|
@@ -62,24 +93,14 @@ export function checkWorktreeSandboxAvailable(cwd: string): { available: true; c
|
|
|
62
93
|
try {
|
|
63
94
|
// Is cwd inside a git repo? `git rev-parse --show-toplevel` errors out
|
|
64
95
|
// (non-zero exit) when not in a repo. execFileSync throws on non-zero.
|
|
65
|
-
const toplevel =
|
|
66
|
-
cwd,
|
|
67
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
68
|
-
encoding: "utf-8",
|
|
69
|
-
timeout: 5000,
|
|
70
|
-
}).trim();
|
|
96
|
+
const toplevel = hardenedVerificationGit(cwd, ["rev-parse", "--show-toplevel"], 5000);
|
|
71
97
|
if (!toplevel)
|
|
72
98
|
return {
|
|
73
99
|
available: false,
|
|
74
100
|
reason: "git rev-parse returned empty toplevel",
|
|
75
101
|
};
|
|
76
102
|
// Current commit SHA (this is what T_snap will pin to).
|
|
77
|
-
const commitSha =
|
|
78
|
-
cwd,
|
|
79
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
80
|
-
encoding: "utf-8",
|
|
81
|
-
timeout: 5000,
|
|
82
|
-
}).trim();
|
|
103
|
+
const commitSha = hardenedVerificationGit(cwd, ["rev-parse", "HEAD"], 5000);
|
|
83
104
|
if (!commitSha)
|
|
84
105
|
return {
|
|
85
106
|
available: false,
|
|
@@ -90,12 +111,7 @@ export function checkWorktreeSandboxAvailable(cwd: string): { available: true; c
|
|
|
90
111
|
// the worktree would NOT contain the in-progress edits (T_snap would
|
|
91
112
|
// pin to a stale commit). Better to fall back + warn than silently
|
|
92
113
|
// verify against the wrong code.
|
|
93
|
-
const status =
|
|
94
|
-
cwd,
|
|
95
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
96
|
-
encoding: "utf-8",
|
|
97
|
-
timeout: 5000,
|
|
98
|
-
}).trim();
|
|
114
|
+
const status = hardenedVerificationGit(cwd, ["status", "--porcelain"], 5000);
|
|
99
115
|
if (status.length > 0)
|
|
100
116
|
return {
|
|
101
117
|
available: false,
|
|
@@ -132,16 +148,15 @@ export function prepareVerificationWorktree(cwd: string, commitSha: string): Ver
|
|
|
132
148
|
if (cleaned) return;
|
|
133
149
|
cleaned = true;
|
|
134
150
|
// Remove the worktree (force = proceed even if it has untracked files).
|
|
151
|
+
// Runs at the trusted main-repo `cwd` — same placement as worktree-manager
|
|
152
|
+
// (git(repoRoot, ["worktree", "remove", "--force", …])): the R-A3 assert is
|
|
153
|
+
// a no-op there and stays fail-closed if `cwd` itself is a hijacked worktree.
|
|
135
154
|
try {
|
|
136
|
-
|
|
155
|
+
hardenedVerificationGit(cwd, ["worktree", "remove", "--force", worktreePath], 5000);
|
|
137
156
|
} catch {
|
|
138
157
|
// Fall back to `git worktree prune` if remove fails (already gone).
|
|
139
158
|
try {
|
|
140
|
-
|
|
141
|
-
cwd,
|
|
142
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
143
|
-
timeout: 5000,
|
|
144
|
-
});
|
|
159
|
+
hardenedVerificationGit(cwd, ["worktree", "prune"], 5000);
|
|
145
160
|
} catch {
|
|
146
161
|
/* best-effort */
|
|
147
162
|
}
|
|
@@ -154,11 +169,13 @@ export function prepareVerificationWorktree(cwd: string, commitSha: string): Ver
|
|
|
154
169
|
}
|
|
155
170
|
};
|
|
156
171
|
try {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
172
|
+
// `worktree add` CREATES the new worktree: git itself writes its `.git`
|
|
173
|
+
// pointer in this very call, so there is no pre-existing worker-writable
|
|
174
|
+
// pointer at `worktreePath` for assertWorktreePointerTrusted to verify
|
|
175
|
+
// (its precondition does not exist yet). The R-A3 assert therefore applies
|
|
176
|
+
// to `cwd` only — the same placement as worktree-manager's createTaskWorktree
|
|
177
|
+
// (git() helper at the trusted repoRoot cwd). Timeouts/stdio unchanged.
|
|
178
|
+
hardenedVerificationGit(cwd, ["worktree", "add", "--detach", worktreePath, commitSha], 30_000);
|
|
162
179
|
return { worktreePath, commitSha, cleanup };
|
|
163
180
|
} catch (error) {
|
|
164
181
|
cleanup();
|