pi-crew 0.11.23 → 0.11.25
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 +72 -0
- package/README.md +2 -2
- package/agents/designer.md +23 -0
- package/agents/explorer.md +3 -3
- package/agents/librarian.md +3 -3
- package/agents/orchestrator.md +17 -0
- package/dist/index.mjs +567 -555
- package/{workflows/chain.workflow.md → docs/chain-workflow.md} +8 -0
- package/docs/dynamic-workflows.md +37 -2
- package/docs/publishing.md +34 -5
- package/docs/troubleshooting.md +50 -2
- package/docs/usage.md +7 -2
- package/install.mjs +2 -1
- package/package.json +6 -4
- package/skills/read-only-explorer/SKILL.md +15 -5
- package/skills/real-test-pi-crew/SKILL.md +7 -7
- package/src/agents/discover-agents.ts +8 -2
- package/src/config/config-validation.ts +61 -1
- package/src/config/config.ts +90 -5
- package/src/config/env-allowlist-registry.ts +5 -0
- package/src/config/env-vars.ts +23 -13
- package/src/config/role-tools.ts +14 -11
- package/src/config/types.ts +4 -1
- package/src/extension/crew-cleanup.ts +6 -0
- package/src/extension/management.ts +7 -0
- package/src/extension/project-init.ts +19 -1
- package/src/extension/register.ts +83 -30
- package/src/extension/registration/artifact-cleanup.ts +52 -11
- package/src/extension/registration/commands/manage.ts +9 -2
- package/src/extension/registration/hook-registration.ts +3 -0
- package/src/extension/registration/lazy-configurers.ts +2 -0
- package/src/extension/registration/lifecycle-handlers.ts +79 -18
- package/src/extension/registration/render-loop.ts +27 -2
- package/src/extension/registration/tool-loop-guard.ts +5 -3
- package/src/extension/registration/verify-gate-tool.ts +7 -3
- package/src/extension/run-index.ts +24 -1
- package/src/extension/team-tool/api/read.ts +12 -3
- package/src/extension/team-tool/cancel.ts +11 -0
- package/src/extension/team-tool/config-patch.ts +56 -11
- package/src/extension/team-tool/destructive-gate.ts +268 -0
- package/src/extension/team-tool/dispatch/manage.ts +9 -1
- package/src/extension/team-tool/goal-wrap.ts +11 -1
- package/src/extension/team-tool/goal.ts +13 -1
- package/src/extension/team-tool/handle-schedule.ts +38 -4
- package/src/extension/team-tool/handle-settings.ts +76 -6
- package/src/extension/team-tool/health-monitor.ts +14 -2
- package/src/extension/team-tool/lifecycle-actions.ts +28 -10
- package/src/extension/team-tool/respond.ts +12 -5
- package/src/extension/team-tool/run-deadline.ts +29 -2
- package/src/extension/team-tool/run.ts +11 -0
- package/src/extension/team-tool/status.ts +64 -8
- package/src/extension/team-tool/workflow-manage.ts +5 -1
- package/src/extension/team-tool.ts +13 -0
- package/src/i18n.ts +18 -14
- package/src/observability/exporters/otlp-exporter.ts +11 -1
- package/src/prompt/inbox-poll.ts +14 -2
- package/src/prompt/message-tool.ts +1 -1
- package/src/prompt/prompt-runtime.ts +127 -21
- package/src/prompt/scratchpad-lifecycle.ts +14 -13
- package/src/prompt/surface-worker.ts +35 -9
- package/src/runtime/broker/crew-broker-client.ts +7 -0
- package/src/runtime/broker/crew-broker.ts +216 -242
- package/src/runtime/broker/delegate/delegate-abort.ts +118 -0
- package/src/runtime/broker/delegate/delegate-event.ts +3 -1
- package/src/runtime/broker/delegate/delegate-finalize.ts +179 -0
- package/src/runtime/broker/protocol/connection-state.ts +159 -1
- package/src/runtime/broker/protocol/events-replay.ts +50 -10
- package/src/runtime/broker/protocol/wait-resolve.ts +71 -5
- package/src/runtime/budget-enforcement.ts +26 -6
- package/src/runtime/chain-parser.ts +5 -3
- package/src/runtime/chain-runner.ts +41 -22
- package/src/runtime/child-pi/child-pi-constants.ts +9 -0
- package/src/runtime/child-pi/child-pi-rpc.ts +72 -7
- package/src/runtime/child-pi/child-pi-streams.ts +19 -3
- package/src/runtime/child-pi/mock-fixtures.ts +12 -5
- package/src/runtime/child-pi/postmortem-registry.ts +8 -2
- package/src/runtime/classifier/ambient-noise-gate.ts +5 -1
- package/src/runtime/compaction/tool-output-pruner.ts +28 -5
- package/src/runtime/crew-agent-records.ts +67 -4
- package/src/runtime/custom-tools/submit-result-tool.ts +17 -0
- package/src/runtime/deadletter.ts +5 -1
- package/src/runtime/delegate-spawn.ts +61 -8
- package/src/runtime/dispatch-batch.ts +61 -14
- package/src/runtime/effectiveness.ts +55 -4
- package/src/runtime/finalize-run.ts +12 -1
- package/src/runtime/goal-workflow/dynamic-workflow-context.ts +12 -3
- package/src/runtime/goal-workflow/goal-evaluator.ts +30 -5
- package/src/runtime/goal-workflow/goal-loop-runner.ts +60 -3
- package/src/runtime/live-session/live-agent-control.ts +123 -20
- package/src/runtime/live-session/live-agent-manager.ts +114 -15
- package/src/runtime/live-session/live-session-runtime.ts +75 -83
- package/src/runtime/live-session/usage-bridge.ts +66 -2
- package/src/runtime/mcp-proxy.ts +10 -0
- package/src/runtime/model/model-fallback.ts +74 -9
- package/src/runtime/model/pi-args.ts +3 -3
- package/src/runtime/model/runtime-policy.ts +22 -6
- package/src/runtime/model/runtime-resolver.ts +11 -5
- package/src/runtime/orphan-worker-registry.ts +64 -24
- package/src/runtime/pi-spawn.ts +4 -1
- package/src/runtime/process/orphan-reaper.ts +143 -0
- package/src/runtime/process-status.ts +38 -16
- package/src/runtime/recovery/crash-recovery.ts +35 -2
- package/src/runtime/resilient-edit.ts +170 -93
- package/src/runtime/role-permission.ts +3 -1
- package/src/runtime/run-tracker.ts +9 -1
- package/src/runtime/sanitize/worker-text.ts +98 -0
- package/src/runtime/scheduling/batch-barrier.ts +42 -5
- package/src/runtime/scheduling/run-coalesced-task-group.ts +82 -28
- package/src/runtime/scheduling/scheduler.ts +74 -29
- package/src/runtime/spawn-policy.ts +190 -8
- package/src/runtime/stale-reconciler.ts +77 -6
- package/src/runtime/subagent-manager.ts +29 -0
- package/src/runtime/surface/herdr-provider.ts +85 -2
- package/src/runtime/surface/launch-script.ts +7 -1
- package/src/runtime/surface/resolve-surface.ts +4 -1
- package/src/runtime/surface/tmux-provider.ts +32 -2
- package/src/runtime/task-output-context.ts +58 -11
- package/src/runtime/task-runner/child-executor.ts +3 -2
- package/src/runtime/task-runner/post-execution.ts +144 -0
- package/src/runtime/task-runner/prompt-builder.ts +41 -8
- package/src/runtime/task-runner.ts +16 -3
- package/src/runtime/verification/classifier-pre-gate.ts +27 -6
- package/src/runtime/verification/verify-gate.ts +153 -30
- package/src/runtime/workspace-lock.ts +52 -4
- package/src/state/atomic-write.ts +73 -4
- package/src/state/contracts.ts +9 -0
- package/src/state/coordination/mailbox.ts +40 -11
- package/src/state/coordination/process-lock.ts +50 -0
- package/src/state/event-log/cursor.ts +10 -1
- package/src/state/event-log/event-log-rotation.ts +54 -8
- package/src/state/event-log/poison-marker.ts +16 -1
- package/src/state/event-log/worker-atomic-writer.ts +5 -0
- package/src/state/stores/active-run-registry.ts +56 -5
- package/src/state/stores/artifact-store.ts +181 -6
- package/src/state/stores/manifest-io.ts +126 -8
- package/src/state/stores/ownership-map.ts +26 -7
- package/src/state/stores/plan-store.ts +30 -1
- package/src/state/stores/sqlite-run-state.ts +91 -1
- package/src/state/stores/state-store.ts +30 -31
- package/src/state/types.ts +18 -0
- package/src/state/usage.ts +41 -0
- package/src/ui/dashboard-panes/agents-pane.ts +4 -3
- package/src/ui/dashboard-panes/plan-pane.ts +5 -3
- package/src/ui/dashboard-panes/transcript-pane.ts +2 -1
- package/src/ui/overlays/mailbox-detail-overlay.ts +5 -3
- package/src/ui/run-dashboard.ts +9 -7
- package/src/ui/run-snapshot-cache.ts +3 -2
- package/src/ui/settings-overlay.ts +87 -11
- package/src/ui/theme-discovery.ts +26 -7
- package/src/ui/transcript-viewer.ts +5 -3
- package/src/utils/internal-error.ts +5 -1
- package/src/utils/timer-limits.ts +30 -0
- package/src/utils/token-counter.ts +47 -0
- package/src/utils/visual.ts +84 -0
- package/src/workflows/discover-workflows.ts +9 -1
- package/src/worktree/worktree-manager.ts +128 -18
|
@@ -385,7 +385,7 @@ export type AskToolDefinition = ToolDefinition<typeof AskParams, AskDetails>;
|
|
|
385
385
|
* reads the injected env object, never a raw process.env.PI_CREW_* member,
|
|
386
386
|
* so the check:env-vars gate stays green). */
|
|
387
387
|
export function shouldRegisterAskTool(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
388
|
-
return
|
|
388
|
+
return getCrewEnv(PI_CREW_ASK_ENABLED_ENV, env) === "1";
|
|
389
389
|
}
|
|
390
390
|
|
|
391
391
|
// ── T3/R5 (ADR-5 2026-08-17-governed-nesting §1): worker-side `delegate` tool ──
|
|
@@ -408,6 +408,65 @@ export function shouldRegisterAskTool(env: NodeJS.ProcessEnv = process.env): boo
|
|
|
408
408
|
|
|
409
409
|
const PI_CREW_DELEGATE_ENABLED_ENV = "PI_CREW_DELEGATE_ENABLED";
|
|
410
410
|
export const DELEGATE_TIMED_OUT_RESULT = "[delegate timed out]";
|
|
411
|
+
|
|
412
|
+
// ── R9-F1 (2026-10-17): delegate-result recovery across parent turn-restarts ──
|
|
413
|
+
// A parent session can restart mid-turn (pi-core seam): the delegate poll loop
|
|
414
|
+
// dies with it, the grandchild later COMPLETES durably into the task inbox,
|
|
415
|
+
// and nothing ever re-reads that message — the report is silently lost
|
|
416
|
+
// (runtime-proven: run event seq 209/216/281/431, mailbox msg_b0297f83).
|
|
417
|
+
// Conservative, seam-level mitigation (the pi-core trigger is external):
|
|
418
|
+
// - every in-flight subId is tracked in `inFlightDelegateSubIds`;
|
|
419
|
+
// - whenever a delegate poll loop (re)starts, the inbox is scanned ONCE for
|
|
420
|
+
// results of still-pending subIds that have no delivered result yet and
|
|
421
|
+
// they are re-injected into `recoveredDelegateResults` (logged as
|
|
422
|
+
// `delegate.result.recovered`) so the owning loop's next iteration — or a
|
|
423
|
+
// RESTARTED loop for the same subId — surfaces it without re-deriving it;
|
|
424
|
+
// - the timed-out notice points at the durable copy in the task inbox.
|
|
425
|
+
// `no double-count`: a recovered message is consumed exactly once (deleted
|
|
426
|
+
// from the map on delivery) and the inbox stays append-only ground truth.
|
|
427
|
+
const inFlightDelegateSubIds = new Set<string>();
|
|
428
|
+
const recoveredDelegateResults = new Map<string, MailboxMessage>();
|
|
429
|
+
const RECOVERED_DELEGATE_RESULTS_MAX = 64;
|
|
430
|
+
|
|
431
|
+
/** R9-F1: scan the task inbox for completed results of still-pending subIds.
|
|
432
|
+
* Pure w.r.t. its inputs (injectable reader for tests); mutates the module
|
|
433
|
+
* recovery map + logs one `delegate.result.recovered` internal event per
|
|
434
|
+
* recovered subId. Returns the recovered messages keyed by subId. */
|
|
435
|
+
export function recoverPendingDelegateResults(
|
|
436
|
+
manifest: TeamRunManifest,
|
|
437
|
+
pendingSubIds: ReadonlySet<string>,
|
|
438
|
+
readInbox: (m: TeamRunManifest) => MailboxMessage[] = (m) => readAllMailboxMessages(m, "inbox"),
|
|
439
|
+
): Map<string, MailboxMessage> {
|
|
440
|
+
const recovered = new Map<string, MailboxMessage>();
|
|
441
|
+
if (pendingSubIds.size === 0) return recovered;
|
|
442
|
+
let messages: MailboxMessage[];
|
|
443
|
+
try {
|
|
444
|
+
messages = readInbox(manifest);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
logInternalError("prompt-runtime.delegate-recovery-inbox-read", error instanceof Error ? error : new Error(String(error)), "warn");
|
|
447
|
+
return recovered;
|
|
448
|
+
}
|
|
449
|
+
for (const message of messages) {
|
|
450
|
+
const from = message.from ?? "";
|
|
451
|
+
if (!from.startsWith("delegate:")) continue;
|
|
452
|
+
const subId = from.slice("delegate:".length);
|
|
453
|
+
if (!pendingSubIds.has(subId)) continue;
|
|
454
|
+
if (recoveredDelegateResults.has(subId)) continue; // already recovered — no double-count
|
|
455
|
+
recoveredDelegateResults.set(subId, message);
|
|
456
|
+
while (recoveredDelegateResults.size > RECOVERED_DELEGATE_RESULTS_MAX) {
|
|
457
|
+
const oldest = recoveredDelegateResults.keys().next().value;
|
|
458
|
+
if (oldest === undefined) break;
|
|
459
|
+
recoveredDelegateResults.delete(oldest);
|
|
460
|
+
}
|
|
461
|
+
recovered.set(subId, message);
|
|
462
|
+
logInternalError(
|
|
463
|
+
"delegate.result.recovered",
|
|
464
|
+
new Error(`recovered completed delegate result from task inbox after a parent turn-restart (subId=${subId})`),
|
|
465
|
+
"warn",
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
return recovered;
|
|
469
|
+
}
|
|
411
470
|
/** P3-11: poll slack past the server deadline — the server timer fires first
|
|
412
471
|
* and writes the fenced (timed out) result; the client checks a bit longer
|
|
413
472
|
* so the outcome lands in-tool instead of lingering unread in the inbox. */
|
|
@@ -492,11 +551,33 @@ export function createDelegateTool(deps: DelegateToolDeps = {}): DelegateToolDef
|
|
|
492
551
|
const socketPath = get(PI_CREW_BROKER_SOCKET_ASK_ENV);
|
|
493
552
|
const token = get(PI_CREW_BROKER_TOKEN_ASK_ENV);
|
|
494
553
|
const runId = get(PI_CREW_BROKER_RUN_ID_ASK_ENV);
|
|
554
|
+
// delegate-auth: name the ACTUALLY-missing vars and distinguish the two
|
|
555
|
+
// no-creds shapes instead of a catch-all that blames all four:
|
|
556
|
+
// (a) identity present + socket/token absent — nested-host run: the
|
|
557
|
+
// spawning host is itself a child session, and child sessions
|
|
558
|
+
// never install a broker (issueForChild is root-session-only,
|
|
559
|
+
// lifecycle-handlers), so NO broker exists for this runId at any
|
|
560
|
+
// depth. (A root-spawned depth-2 worker DOES carry creds, so the
|
|
561
|
+
// old "depth-2 worker" label was wrong for this case.)
|
|
562
|
+
// (b) identity vars absent too — scaffold, mock, or partially-wired
|
|
563
|
+
// spawn; list exactly which vars are missing.
|
|
564
|
+
const missingVars: string[] = [];
|
|
565
|
+
if (!taskId) missingVars.push("PI_CREW_TASK_ID/PI_CREW_BROKER_TASK_ID");
|
|
566
|
+
if (!stateRoot) missingVars.push(PI_CREW_STATE_ROOT_ENV);
|
|
567
|
+
if (!runId) missingVars.push(PI_CREW_BROKER_RUN_ID_ASK_ENV);
|
|
568
|
+
if (!socketPath) missingVars.push(PI_CREW_BROKER_SOCKET_ASK_ENV);
|
|
569
|
+
if (!token) missingVars.push(PI_CREW_BROKER_TOKEN_ASK_ENV);
|
|
570
|
+
// direct-truthiness guard keeps TS narrowing for the client construction
|
|
571
|
+
// below (the missingVars[] indirection alone defeats control-flow analysis).
|
|
495
572
|
if (!taskId || !stateRoot || !socketPath || !token || !runId) {
|
|
573
|
+
const reason =
|
|
574
|
+
!socketPath && !token && taskId && stateRoot && runId
|
|
575
|
+
? "PI_CREW_BROKER_SOCKET / PI_CREW_BROKER_TOKEN absent while task-id/run-id/state-root are set — nested-host run: this worker's host is itself a child session, which never installs a broker, so no broker exists for this run"
|
|
576
|
+
: `${missingVars.join(" / ")} absent — scaffold, mock, or partially-wired spawn`;
|
|
496
577
|
return notice(
|
|
497
578
|
"unavailable",
|
|
498
579
|
"no-broker",
|
|
499
|
-
|
|
580
|
+
`[delegate] unavailable: no broker connection (${reason}) — do the work yourself; do not call delegate again.`,
|
|
500
581
|
);
|
|
501
582
|
}
|
|
502
583
|
const client = deps.makeBrokerClient
|
|
@@ -540,24 +621,40 @@ export function createDelegateTool(deps: DelegateToolDeps = {}): DelegateToolDef
|
|
|
540
621
|
const fromTag = `delegate:${subId}`;
|
|
541
622
|
let terminal: "completed" | "timed-out" | "aborted" = "timed-out";
|
|
542
623
|
let result: MailboxMessage | undefined;
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
624
|
+
// R9-F1: register the subId as in-flight and, at every loop (re)start,
|
|
625
|
+
// re-inject results of still-pending subIds that a previous (restarted)
|
|
626
|
+
// turn never delivered — they become visible to THIS loop's reads.
|
|
627
|
+
inFlightDelegateSubIds.add(subId);
|
|
628
|
+
try {
|
|
629
|
+
recoverPendingDelegateResults(manifest, inFlightDelegateSubIds);
|
|
630
|
+
while (true) {
|
|
631
|
+
if (signal?.aborted) {
|
|
632
|
+
terminal = "aborted";
|
|
633
|
+
break;
|
|
634
|
+
}
|
|
635
|
+
// Consume a recovered result FIRST (exactly once — map delete), then
|
|
636
|
+
// fall through to the durable inbox read (append-only ground truth).
|
|
637
|
+
result = recoveredDelegateResults.get(subId);
|
|
638
|
+
if (result) recoveredDelegateResults.delete(subId);
|
|
639
|
+
if (!result) {
|
|
640
|
+
try {
|
|
641
|
+
result = readAllMailboxMessages(manifest, "inbox").find(
|
|
642
|
+
(m) => m.from === fromTag && (m.taskId === undefined || m.taskId === taskId),
|
|
643
|
+
);
|
|
644
|
+
} catch {
|
|
645
|
+
/* transient read error — keep polling */
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
if (result) {
|
|
649
|
+
terminal = "completed";
|
|
650
|
+
break;
|
|
651
|
+
}
|
|
652
|
+
if (now() >= deadline) break;
|
|
653
|
+
await sleep(effectiveSteeringInterval(hasLiveControlRealtimeListeners()));
|
|
558
654
|
}
|
|
559
|
-
|
|
560
|
-
|
|
655
|
+
} finally {
|
|
656
|
+
inFlightDelegateSubIds.delete(subId);
|
|
657
|
+
recoveredDelegateResults.delete(subId);
|
|
561
658
|
}
|
|
562
659
|
const waitedMs = now() - startedAt;
|
|
563
660
|
if (terminal === "completed" && result) {
|
|
@@ -574,8 +671,17 @@ export function createDelegateTool(deps: DelegateToolDeps = {}): DelegateToolDef
|
|
|
574
671
|
details: { status: "aborted", grandchildTaskRef: subId, waitedMs },
|
|
575
672
|
};
|
|
576
673
|
}
|
|
674
|
+
// R9-F1: recovery hint — the grandchild can still complete AFTER this
|
|
675
|
+
// timeout (and after a parent turn-restart the tool result itself can be
|
|
676
|
+
// lost); the durable copy lands in the task inbox. Point the model at it
|
|
677
|
+
// instead of silently redoing the delegated work.
|
|
577
678
|
return {
|
|
578
|
-
content: [
|
|
679
|
+
content: [
|
|
680
|
+
{
|
|
681
|
+
type: "text" as const,
|
|
682
|
+
text: `${DELEGATE_TIMED_OUT_RESULT} — the grandchild may still complete; its result lands durably in the task inbox (from=delegate:${subId}) — check the task inbox / lastResult before redoing the work, or ask the leader to relay it.`,
|
|
683
|
+
},
|
|
684
|
+
],
|
|
579
685
|
details: { status: "timed-out", grandchildTaskRef: subId, waitedMs },
|
|
580
686
|
};
|
|
581
687
|
} finally {
|
|
@@ -590,7 +696,7 @@ export function createDelegateTool(deps: DelegateToolDeps = {}): DelegateToolDef
|
|
|
590
696
|
* for EVERY role. Broker admission re-checks depth+slot from the task
|
|
591
697
|
* RECORD — the env is UX/hygiene, not the security boundary). */
|
|
592
698
|
export function shouldRegisterDelegateTool(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
593
|
-
return
|
|
699
|
+
return getCrewEnv(PI_CREW_DELEGATE_ENABLED_ENV, env) === "1";
|
|
594
700
|
}
|
|
595
701
|
|
|
596
702
|
/** Task 5 (§15.2): fence a sibling/group inbox message before it reaches the
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
import * as fs from "node:fs";
|
|
31
31
|
import * as path from "node:path";
|
|
32
32
|
import { type Static, Type } from "@sinclair/typebox";
|
|
33
|
+
import { getCrewEnv } from "../config/env-vars.ts";
|
|
33
34
|
import { defineTool, type ExtensionAPI, type ToolDefinition } from "../extension/pi-api.ts";
|
|
34
35
|
import { EngineManager, type ExecuteResult } from "../runtime/scratchpad/engine.ts";
|
|
35
36
|
import { appendEventBuffered, appendEventFireAndForget } from "../state/event-log/event-log.ts";
|
|
@@ -77,8 +78,8 @@ function emitScratchpadMetric(
|
|
|
77
78
|
data: Record<string, unknown>,
|
|
78
79
|
appendEvent: typeof appendEventFireAndForget = appendEventFireAndForget,
|
|
79
80
|
): void {
|
|
80
|
-
const eventsPath = env
|
|
81
|
-
const runId = env
|
|
81
|
+
const eventsPath = getCrewEnv(PI_CREW_EVENTS_PATH_ENV, env);
|
|
82
|
+
const runId = getCrewEnv(PI_CREW_RUN_ID_ENV, env);
|
|
82
83
|
if (!eventsPath || !runId) return;
|
|
83
84
|
// Fire-and-forget semantics (H1): a throwing writer (sync or async) must
|
|
84
85
|
// never break the cell. The real appendEventFireAndForget already catches
|
|
@@ -87,7 +88,7 @@ function emitScratchpadMetric(
|
|
|
87
88
|
appendEventBuffered(eventsPath, {
|
|
88
89
|
type,
|
|
89
90
|
runId,
|
|
90
|
-
taskId:
|
|
91
|
+
taskId: getCrewEnv(PI_CREW_TASK_ID_ENV, env),
|
|
91
92
|
data,
|
|
92
93
|
}).catch((e) => logInternalError("scratchpad_lifecycle.buffered", e, `type=${type}`));
|
|
93
94
|
} catch {
|
|
@@ -224,10 +225,10 @@ export interface SnapshotEnvValidation {
|
|
|
224
225
|
* write to a guessed location.
|
|
225
226
|
*/
|
|
226
227
|
export function validateSnapshotEnv(env: NodeJS.ProcessEnv = process.env): SnapshotEnvValidation {
|
|
227
|
-
const taskId = env
|
|
228
|
-
const artifactsRoot = env
|
|
229
|
-
const snapshotPath = env
|
|
230
|
-
const attempt =
|
|
228
|
+
const taskId = getCrewEnv(PI_CREW_TASK_ID_ENV, env);
|
|
229
|
+
const artifactsRoot = getCrewEnv(PI_CREW_ARTIFACTS_ROOT_ENV, env);
|
|
230
|
+
const snapshotPath = getCrewEnv(PI_CREW_SCRATCHPAD_SNAPSHOT_ENV, env);
|
|
231
|
+
const attempt = getCrewEnv(PI_CREW_ATTEMPT_ENV, env) ?? "0";
|
|
231
232
|
|
|
232
233
|
if (!taskId) return { valid: false, reason: `missing ${PI_CREW_TASK_ID_ENV}`, attempt };
|
|
233
234
|
if (!artifactsRoot) return { valid: false, reason: `missing ${PI_CREW_ARTIFACTS_ROOT_ENV}`, attempt };
|
|
@@ -277,8 +278,8 @@ export interface RestoreEnvValidation {
|
|
|
277
278
|
* no restore, empty namespace, execute continues, message never leaks paths.
|
|
278
279
|
*/
|
|
279
280
|
export function validateRestoreEnv(env: NodeJS.ProcessEnv = process.env, restorePath: string): RestoreEnvValidation {
|
|
280
|
-
const taskId = env
|
|
281
|
-
const artifactsRoot = env
|
|
281
|
+
const taskId = getCrewEnv(PI_CREW_TASK_ID_ENV, env);
|
|
282
|
+
const artifactsRoot = getCrewEnv(PI_CREW_ARTIFACTS_ROOT_ENV, env);
|
|
282
283
|
if (!taskId) return { valid: false, reason: `missing ${PI_CREW_TASK_ID_ENV}` };
|
|
283
284
|
if (!artifactsRoot) return { valid: false, reason: `missing ${PI_CREW_ARTIFACTS_ROOT_ENV}` };
|
|
284
285
|
try {
|
|
@@ -299,7 +300,7 @@ export function validateRestoreEnv(env: NodeJS.ProcessEnv = process.env, restore
|
|
|
299
300
|
if (st.isSymbolicLink() || !st.isFile()) return { valid: false, reason: "restore-path-not-regular-file" };
|
|
300
301
|
if (st.size > SNAPSHOT_MAX_BYTES) return { valid: false, reason: "restore-path-over-cap" };
|
|
301
302
|
// (4) mtime pin (swap-detection hint — forgeable, never authn).
|
|
302
|
-
const pinned = env
|
|
303
|
+
const pinned = getCrewEnv(PI_CREW_SCRATCHPAD_RESTORE_MTIME_ENV, env);
|
|
303
304
|
if (pinned) {
|
|
304
305
|
const pinnedMs = Number.parseFloat(pinned);
|
|
305
306
|
if (Number.isFinite(pinnedMs) && Math.abs(st.mtimeMs - pinnedMs) > RESTORE_MTIME_TOLERANCE_MS) {
|
|
@@ -483,7 +484,7 @@ export function createExecuteTool(engine: EngineManager, deps: Partial<Scratchpa
|
|
|
483
484
|
async execute(_toolCallId, params, signal, _onUpdate, _ctx) {
|
|
484
485
|
const env = deps.env ?? process.env;
|
|
485
486
|
// 1. Dormant check (lớp 2 — defense in depth behind the registration gate).
|
|
486
|
-
if (
|
|
487
|
+
if (getCrewEnv(PI_CREW_SCRATCHPAD_ENV, env) !== "1") {
|
|
487
488
|
throw new Error("scratchpad is dormant");
|
|
488
489
|
}
|
|
489
490
|
// 2. F12: terminal shutdown state — a distinct system error, not "wedged".
|
|
@@ -650,7 +651,7 @@ export function registerScratchpadLifecycle(pi: ExtensionAPI, options: Scratchpa
|
|
|
650
651
|
// Reset first: each register is a fresh worker session (a session reload
|
|
651
652
|
// re-arms restore via the env — NIT-2a, module-scope is intentional).
|
|
652
653
|
const env = options.env ?? process.env;
|
|
653
|
-
const restorePath = env
|
|
654
|
+
const restorePath = getCrewEnv(PI_CREW_SCRATCHPAD_RESTORE_ENV, env);
|
|
654
655
|
if (restorePath) {
|
|
655
656
|
const m = restorePath.match(/\.attempt-(\d+)\.snapshot\.json$/);
|
|
656
657
|
restorePending = { path: restorePath, attempt: m ? Number.parseInt(m[1], 10) : 0 };
|
|
@@ -676,5 +677,5 @@ export function registerScratchpadLifecycle(pi: ExtensionAPI, options: Scratchpa
|
|
|
676
677
|
* the single source of truth per F15.
|
|
677
678
|
*/
|
|
678
679
|
export function shouldRegisterScratchpadTool(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
679
|
-
return
|
|
680
|
+
return getCrewEnv(PI_CREW_SCRATCHPAD_ENV, env) === "1" && getCrewEnv(PI_CREW_KIND_ENV, env) === "subagent";
|
|
680
681
|
}
|
|
@@ -121,6 +121,40 @@ export function shouldAutoExit(signals: AutoExitSignals): boolean {
|
|
|
121
121
|
|
|
122
122
|
// ── parent liveness ───────────────────────────────────────────────────────
|
|
123
123
|
|
|
124
|
+
/**
|
|
125
|
+
* Default `/proc/<pid>/stat` reader for {@link parentAlive}.
|
|
126
|
+
*
|
|
127
|
+
* R19-M1 (deep-review round 19): the R7-P1 tolerance (a THROWING reader with no
|
|
128
|
+
* recorded start time ⇒ alive-with-caveat) was UNREACHABLE in production because
|
|
129
|
+
* the default reader caught its own error and returned `undefined` — which
|
|
130
|
+
* `parentAlive` reads as “no entry ⇒ parent is dead”. On macOS (no procfs) every
|
|
131
|
+
* healthy surface worker therefore self-terminated at the first 5 s guard tick
|
|
132
|
+
* (`terminate("worker.parent-lost")`), and the R7-P1 pin only held for injected
|
|
133
|
+
* readers.
|
|
134
|
+
*
|
|
135
|
+
* The platform distinction is the whole point:
|
|
136
|
+
* - Linux with procfs: ENOENT is the DEAD signal (unchanged — keeps Linux
|
|
137
|
+
* dead-pid detection exact); any other errno (EACCES/EPERM) is “unreadable”
|
|
138
|
+
* and is surfaced as a throw so the tolerance applies.
|
|
139
|
+
* - No procfs (macOS / Windows / a Linux container without /proc): the file can
|
|
140
|
+
* never exist, so “cannot read” must NOT be reported as “dead”. Throw —
|
|
141
|
+
* `parentAlive` then keeps the worker alive and the host watchdog is the
|
|
142
|
+
* backstop (a false “alive” is recoverable; a false “dead” kills work).
|
|
143
|
+
*
|
|
144
|
+
* `platform` is injectable so the macOS path is testable on every CI OS.
|
|
145
|
+
*/
|
|
146
|
+
export function defaultProcStatReader(pid: number, platform: string = process.platform): string | undefined {
|
|
147
|
+
if (platform !== "linux" || !fs.existsSync("/proc/self/stat")) {
|
|
148
|
+
throw new Error(`procfs unavailable on ${platform}: cannot read /proc/${pid}/stat`);
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
return fs.readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") return undefined;
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
124
158
|
/**
|
|
125
159
|
* Pure parent-liveness decision.
|
|
126
160
|
* - stat unreadable → parent is GONE (/proc ENOENT means dead on Linux).
|
|
@@ -132,15 +166,7 @@ export function shouldAutoExit(signals: AutoExitSignals): boolean {
|
|
|
132
166
|
*/
|
|
133
167
|
export function parentAlive(pid: number, expectedStartTime: string | undefined, readStat?: (pid: number) => string | undefined): boolean {
|
|
134
168
|
if (!Number.isFinite(pid) || pid <= 0) return false;
|
|
135
|
-
const reader =
|
|
136
|
-
readStat ??
|
|
137
|
-
((p: number): string | undefined => {
|
|
138
|
-
try {
|
|
139
|
-
return fs.readFileSync(`/proc/${p}/stat`, "utf8");
|
|
140
|
-
} catch {
|
|
141
|
-
return undefined;
|
|
142
|
-
}
|
|
143
|
-
});
|
|
169
|
+
const reader = readStat ?? ((p: number): string | undefined => defaultProcStatReader(p));
|
|
144
170
|
let stat: string | undefined;
|
|
145
171
|
let readerThrew = false;
|
|
146
172
|
try {
|
|
@@ -223,6 +223,13 @@ export class CrewBrokerClient {
|
|
|
223
223
|
Math.max(1, Math.floor(timeoutMs)),
|
|
224
224
|
);
|
|
225
225
|
if (entry) entry.timer = requestTimer;
|
|
226
|
+
// R2-L-A3 (2026-10-17): unref the per-request timer (mirror the hello/
|
|
227
|
+
// backoff timers at :466-474) — a stranded in-flight request must not
|
|
228
|
+
// hold a finishing child's event loop open for up to timeoutMs. The
|
|
229
|
+
// typeof guard keeps injected test timer fakes (no unref) working.
|
|
230
|
+
if (requestTimer && typeof (requestTimer as { unref?: () => void }).unref === "function") {
|
|
231
|
+
(requestTimer as { unref?: () => void }).unref?.();
|
|
232
|
+
}
|
|
226
233
|
try {
|
|
227
234
|
const frame = encodeBrokerFrame({ id, method, params });
|
|
228
235
|
// Write may emit EPIPE etc. We don't await drain here — the response
|