@loucompanion/forge-bridge 0.1.4-dev.ccffca94938b → 0.1.4-dev.deb7f72e7930
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 +87 -1
- package/dist/bridge/bridge-chat-provider-command.d.ts +4 -1
- package/dist/bridge/bridge-chat-provider-command.js +14 -19
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.service.d.ts +16 -12
- package/dist/bridge/bridge.service.js +131 -243
- package/dist/bridge/bridge.types.d.ts +5 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +11 -1
- package/dist/cleanup/cleanup.service.js +80 -62
- package/dist/cleanup/cleanup.types.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.js +30 -9
- package/dist/cli/cli.help.js +56 -12
- package/dist/cli/cli.service.d.ts +3 -10
- package/dist/cli/cli.service.js +10 -171
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +2 -0
- package/dist/cli/local-config.js +7 -1
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +46 -1
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-load-governor.d.ts +2 -0
- package/dist/runtime/host-load-ledger-lock.js +6 -4
- package/dist/runtime/host-load-runtime-settings.js +4 -2
- package/dist/runtime/host-runtime-contract.d.ts +12 -0
- package/dist/runtime/host-runtime-contract.js +29 -1
- package/dist/runtime/host-runtime-lease.js +10 -50
- package/dist/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/runner-settings.d.ts +4 -0
- package/dist/runtime/runner-settings.js +22 -0
- package/dist/sandbox/host-capacity-broker.d.ts +3 -1
- package/dist/sandbox/host-capacity-broker.js +4 -2
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +36 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.js +2 -6
- package/dist/session/managed-attempt-tools.d.ts +0 -7
- package/dist/session/managed-attempt-tools.js +45 -77
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/phase-completion.artifacts.js +2 -1
- package/dist/session/phase-completion.d.ts +8 -0
- package/dist/session/phase-completion.js +1 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.runtime.d.ts +0 -8
- package/dist/session/phase-completion.runtime.js +43 -197
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-process.js +10 -10
- package/dist/session/pre-publication-step-execution.d.ts +2 -1
- package/dist/session/pre-publication-step-execution.js +6 -5
- package/dist/session/pre-publication-validation.d.ts +7 -3
- package/dist/session/pre-publication-validation.js +32 -30
- package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
- package/dist/session/provider-cli/claude-background-work.js +4 -3
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
- package/dist/session/provider-cli/pre-publication-repair.js +33 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
- package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
- package/dist/session/provider-cli/provider-cli.process.js +4 -94
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.service.js +27 -43
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
- package/dist/session/sandbox-host-capacity-gate.js +34 -15
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +62 -56
- package/dist/session/session.types.js +1 -1
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +13 -1
- package/dist/shared/process/host-process-supervisor.js +66 -14
- package/dist/shared/provider-capabilities.js +9 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +34 -0
- package/dist/worktree/worktree-origin-sync.js +127 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +49 -0
- package/dist/worktree/worktree-wip.js +182 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +27 -5
- package/dist/worktree/worktree.service.js +106 -181
- package/dist/worktree/worktree.types.d.ts +31 -0
- package/package.json +1 -1
|
@@ -2,7 +2,7 @@ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "./session-
|
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
3
|
import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
|
|
4
4
|
import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
|
|
5
|
-
import { GitWorktreeService } from "../worktree/worktree.service.js";
|
|
5
|
+
import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree } from "../worktree/worktree.service.js";
|
|
6
6
|
import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
|
|
7
7
|
import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
|
|
8
8
|
import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
|
|
@@ -190,6 +190,7 @@ export class BridgeSessionService {
|
|
|
190
190
|
let worktree = null;
|
|
191
191
|
let hostSingletonKeys = null;
|
|
192
192
|
let hostLease = null;
|
|
193
|
+
let succeeded = false;
|
|
193
194
|
try {
|
|
194
195
|
if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
|
|
195
196
|
const capacity = this.hostRuntime.snapshot?.() ?? null;
|
|
@@ -265,6 +266,7 @@ export class BridgeSessionService {
|
|
|
265
266
|
warmPathOverrides: dispatch.warmPathOverrides,
|
|
266
267
|
applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
|
|
267
268
|
preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
|
|
269
|
+
sessionId: dispatch.session.id,
|
|
268
270
|
hostLoadOwner: {
|
|
269
271
|
dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
|
|
270
272
|
priority: runtimeAdmissionPriority(dispatch),
|
|
@@ -285,6 +287,7 @@ export class BridgeSessionService {
|
|
|
285
287
|
: `Prepared worktree ${worktree.branchName}.`,
|
|
286
288
|
eventType: dispatch.session.resumedFromSessionId ? "worktree_reattached" : "worktree_prepared"
|
|
287
289
|
});
|
|
290
|
+
await emitWorktreePreparedEvents(worktree, emit);
|
|
288
291
|
if ((worktree.hydratedPriorPhaseArtifactCount ?? 0) > 0) {
|
|
289
292
|
await emit({
|
|
290
293
|
role: "runner",
|
|
@@ -454,6 +457,7 @@ export class BridgeSessionService {
|
|
|
454
457
|
});
|
|
455
458
|
throwIfAborted(signal);
|
|
456
459
|
const draftArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
|
|
460
|
+
succeeded = true;
|
|
457
461
|
return redactRunOnceResultPacket({
|
|
458
462
|
schemaVersion: 2,
|
|
459
463
|
exitCode: 0,
|
|
@@ -508,6 +512,7 @@ export class BridgeSessionService {
|
|
|
508
512
|
}
|
|
509
513
|
throwIfAborted(signal);
|
|
510
514
|
const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
|
|
515
|
+
succeeded = true;
|
|
511
516
|
return redactRunOnceResultPacket({
|
|
512
517
|
schemaVersion: 2,
|
|
513
518
|
exitCode: 0,
|
|
@@ -521,70 +526,75 @@ export class BridgeSessionService {
|
|
|
521
526
|
}, redactionSecrets);
|
|
522
527
|
}
|
|
523
528
|
finally {
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
sampleCount: providerMemory.sampleCount,
|
|
536
|
-
source: providerMemory.source,
|
|
537
|
-
containers: [{
|
|
538
|
-
role: "agent",
|
|
539
|
-
peakMemoryBytes: providerMemory.peakMemoryBytes,
|
|
540
|
-
}],
|
|
541
|
-
}),
|
|
542
|
-
}).catch(() => undefined);
|
|
543
|
-
}
|
|
544
|
-
const teardownAt = new Date().toISOString();
|
|
529
|
+
await this.releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle);
|
|
530
|
+
if (worktree) {
|
|
531
|
+
await settleWorktree(this.worktrees, worktree, sessionWipOutcome(signal, events, succeeded), signal, emitLifecycle);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
/** Reports the provider's peak memory and releases the attempt's host runtime lease. */
|
|
536
|
+
async releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle) {
|
|
537
|
+
if (hostLease && dispatch.sandbox) {
|
|
538
|
+
const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
|
|
539
|
+
if (providerMemory) {
|
|
545
540
|
await emitLifecycle({
|
|
546
541
|
role: "runner",
|
|
547
542
|
kind: "checkpoint",
|
|
548
|
-
content: `
|
|
549
|
-
eventType: "
|
|
550
|
-
occurredAt:
|
|
543
|
+
content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
|
|
544
|
+
eventType: "sandbox_peak_memory_observed",
|
|
545
|
+
occurredAt: providerMemory.observedAt,
|
|
546
|
+
data: JSON.stringify({
|
|
547
|
+
peakMemoryBytes: providerMemory.peakMemoryBytes,
|
|
548
|
+
sampleCount: providerMemory.sampleCount,
|
|
549
|
+
source: providerMemory.source,
|
|
550
|
+
containers: [{
|
|
551
|
+
role: "agent",
|
|
552
|
+
peakMemoryBytes: providerMemory.peakMemoryBytes,
|
|
553
|
+
}],
|
|
554
|
+
}),
|
|
551
555
|
}).catch(() => undefined);
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
await emitLifecycle({
|
|
565
|
-
role: "runner",
|
|
566
|
-
kind: "checkpoint",
|
|
567
|
-
content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
|
|
568
|
-
eventType: "sandbox_teardown_completed",
|
|
569
|
-
occurredAt: released.releasedAt,
|
|
570
|
-
}).catch(() => undefined);
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
catch (error) {
|
|
556
|
+
}
|
|
557
|
+
const teardownAt = new Date().toISOString();
|
|
558
|
+
await emitLifecycle({
|
|
559
|
+
role: "runner",
|
|
560
|
+
kind: "checkpoint",
|
|
561
|
+
content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
|
|
562
|
+
eventType: "sandbox_teardown_started",
|
|
563
|
+
occurredAt: teardownAt,
|
|
564
|
+
}).catch(() => undefined);
|
|
565
|
+
try {
|
|
566
|
+
const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
|
|
567
|
+
if (!released) {
|
|
574
568
|
await emitLifecycle({
|
|
575
569
|
role: "runner",
|
|
576
570
|
kind: "error",
|
|
577
|
-
content:
|
|
571
|
+
content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
|
|
578
572
|
eventType: "teardown_failed",
|
|
579
573
|
occurredAt: new Date().toISOString(),
|
|
580
574
|
}).catch(() => undefined);
|
|
581
575
|
}
|
|
576
|
+
else {
|
|
577
|
+
await emitLifecycle({
|
|
578
|
+
role: "runner",
|
|
579
|
+
kind: "checkpoint",
|
|
580
|
+
content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
|
|
581
|
+
eventType: "sandbox_teardown_completed",
|
|
582
|
+
occurredAt: released.releasedAt,
|
|
583
|
+
}).catch(() => undefined);
|
|
584
|
+
}
|
|
582
585
|
}
|
|
583
|
-
|
|
584
|
-
await
|
|
586
|
+
catch (error) {
|
|
587
|
+
await emitLifecycle({
|
|
588
|
+
role: "runner",
|
|
589
|
+
kind: "error",
|
|
590
|
+
content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
|
|
591
|
+
eventType: "teardown_failed",
|
|
592
|
+
occurredAt: new Date().toISOString(),
|
|
593
|
+
}).catch(() => undefined);
|
|
585
594
|
}
|
|
586
|
-
|
|
587
|
-
|
|
595
|
+
}
|
|
596
|
+
if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
|
|
597
|
+
await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
|
|
588
598
|
}
|
|
589
599
|
}
|
|
590
600
|
}
|
|
@@ -594,10 +604,6 @@ function failureMessage(error) {
|
|
|
594
604
|
function formatMemoryBytes(bytes) {
|
|
595
605
|
return `${(bytes / (1024 ** 2)).toFixed(bytes >= 1024 ** 3 ? 0 : 1)} MiB`;
|
|
596
606
|
}
|
|
597
|
-
function isPauseCancellation(signal) {
|
|
598
|
-
return signal?.aborted === true
|
|
599
|
-
&& String(signal.reason ?? "").trim().toLowerCase() === "session pause requested";
|
|
600
|
-
}
|
|
601
607
|
function readinessProbeDispatch(request) {
|
|
602
608
|
return {
|
|
603
609
|
schemaVersion: 2,
|
|
@@ -481,7 +481,7 @@ function unvalidatedFailureFactsForCode(code, source) {
|
|
|
481
481
|
if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
|
|
482
482
|
return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
|
|
483
483
|
}
|
|
484
|
-
if (
|
|
484
|
+
if (["comment_repair_changed_files_mismatch", "runner_result_sidecar_malformed"].includes(code)) {
|
|
485
485
|
return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
|
|
486
486
|
}
|
|
487
487
|
if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare const maximumIntegrityJsonBytes: number;
|
|
2
|
+
/** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
|
|
3
|
+
export declare class JsonShapeError extends Error {
|
|
4
|
+
readonly reason: string;
|
|
5
|
+
constructor(reason: string);
|
|
6
|
+
}
|
|
7
|
+
export declare const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
|
|
8
|
+
/**
|
|
9
|
+
* Checks a bounded JSON text and calls `onString` with every decoded string token (property names
|
|
10
|
+
* and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
|
|
11
|
+
*/
|
|
12
|
+
export declare function inspectJsonText(value: string, onString?: (decoded: string) => void): void;
|
|
13
|
+
export declare function decodeJsonStringToken(value: string, openingQuoteIndex: number): {
|
|
14
|
+
readonly decoded: string;
|
|
15
|
+
readonly nextIndex: number;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
|
|
19
|
+
* plain text that does not start like JSON, or binary content that is not named *.json.
|
|
20
|
+
*/
|
|
21
|
+
export declare function sidecarJsonShapeProblem(content: Uint8Array, path: string, onString?: (decoded: string) => void): string | null;
|
|
22
|
+
/** The instruction an agent gets when it records a sidecar that fails the shape check. */
|
|
23
|
+
export declare function sidecarJsonRepairInstruction(path: string, reason: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
|
|
26
|
+
* hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
|
|
27
|
+
*/
|
|
28
|
+
export declare function decodeJsonEscapesLeniently(value: string): string;
|
|
29
|
+
export declare function looksLikeJson(value: string, path: string): boolean;
|
|
30
|
+
export declare function isJsonWhitespace(code: number): boolean;
|
|
31
|
+
export declare function isJsonPunctuation(code: number): boolean;
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { TextDecoder } from "node:util";
|
|
2
|
+
// One set of JSON shape rules for result sidecars. The end-of-run secret check and the QA gate
|
|
3
|
+
// tools that record sidecars during the run both use it, so the agent is told about a malformed
|
|
4
|
+
// sidecar while it can still rewrite the file, and the end-of-run check never disagrees with it.
|
|
5
|
+
//
|
|
6
|
+
// Content sniffing is deliberate: any sidecar whose text starts like JSON ("{", "[" or '"') is
|
|
7
|
+
// held to strict JSON, whatever its file name, so JSON escapes cannot hide secret material from
|
|
8
|
+
// the byte scan. Only a parseable document can be checked token by token.
|
|
9
|
+
export const maximumIntegrityJsonBytes = 8 * 1024 * 1024;
|
|
10
|
+
const maximumIntegrityJsonDepth = 128;
|
|
11
|
+
const maximumIntegrityJsonTokens = 262_144;
|
|
12
|
+
const jsonEscapePattern = /\\(?:u([0-9a-fA-F]{4})|(["\\/bfnrt]))/gu;
|
|
13
|
+
const simpleJsonEscapes = {
|
|
14
|
+
"\"": "\"", "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t",
|
|
15
|
+
};
|
|
16
|
+
/** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
|
|
17
|
+
export class JsonShapeError extends Error {
|
|
18
|
+
reason;
|
|
19
|
+
constructor(reason) {
|
|
20
|
+
super(reason);
|
|
21
|
+
this.reason = reason;
|
|
22
|
+
this.name = "JsonShapeError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
|
|
26
|
+
/**
|
|
27
|
+
* Checks a bounded JSON text and calls `onString` with every decoded string token (property names
|
|
28
|
+
* and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
|
|
29
|
+
*/
|
|
30
|
+
export function inspectJsonText(value, onString) {
|
|
31
|
+
if (Buffer.byteLength(value, "utf8") > maximumIntegrityJsonBytes)
|
|
32
|
+
throw new JsonShapeError(oversizedJsonReason);
|
|
33
|
+
if (value.trim().length === 0)
|
|
34
|
+
throw new JsonShapeError("the file is empty");
|
|
35
|
+
const containers = [];
|
|
36
|
+
let tokenCount = 0;
|
|
37
|
+
let index = 0;
|
|
38
|
+
while (index < value.length) {
|
|
39
|
+
const code = value.charCodeAt(index);
|
|
40
|
+
if (isJsonWhitespace(code) || code === 0x2c || code === 0x3a) {
|
|
41
|
+
index += 1;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
tokenCount += 1;
|
|
45
|
+
if (tokenCount > maximumIntegrityJsonTokens) {
|
|
46
|
+
throw new JsonShapeError(`it has more than ${maximumIntegrityJsonTokens} JSON tokens`);
|
|
47
|
+
}
|
|
48
|
+
index = inspectJsonToken(value, index, containers, onString);
|
|
49
|
+
}
|
|
50
|
+
if (containers.length !== 0)
|
|
51
|
+
throw new JsonShapeError("a bracket or brace is never closed");
|
|
52
|
+
assertJsonParses(value);
|
|
53
|
+
}
|
|
54
|
+
function inspectJsonToken(value, index, containers, onString) {
|
|
55
|
+
const code = value.charCodeAt(index);
|
|
56
|
+
if (code === 0x22) {
|
|
57
|
+
const token = decodeJsonStringToken(value, index);
|
|
58
|
+
onString?.(token.decoded);
|
|
59
|
+
return token.nextIndex;
|
|
60
|
+
}
|
|
61
|
+
if (code === 0x7b || code === 0x5b) {
|
|
62
|
+
containers.push(code);
|
|
63
|
+
if (containers.length > maximumIntegrityJsonDepth) {
|
|
64
|
+
throw new JsonShapeError(`it nests deeper than ${maximumIntegrityJsonDepth} levels`);
|
|
65
|
+
}
|
|
66
|
+
return index + 1;
|
|
67
|
+
}
|
|
68
|
+
if (code === 0x7d || code === 0x5d) {
|
|
69
|
+
if (containers.pop() !== (code === 0x7d ? 0x7b : 0x5b)) {
|
|
70
|
+
throw new JsonShapeError(`an unmatched closing bracket or brace ${locationOf(value, index)}`);
|
|
71
|
+
}
|
|
72
|
+
return index + 1;
|
|
73
|
+
}
|
|
74
|
+
let end = index + 1;
|
|
75
|
+
while (end < value.length && !isJsonWhitespace(value.charCodeAt(end)) && !isJsonPunctuation(value.charCodeAt(end))) {
|
|
76
|
+
end += 1;
|
|
77
|
+
}
|
|
78
|
+
return end;
|
|
79
|
+
}
|
|
80
|
+
function assertJsonParses(value) {
|
|
81
|
+
try {
|
|
82
|
+
JSON.parse(value);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
// The parser's message can quote the offending text; keep only its position.
|
|
86
|
+
const message = error instanceof Error ? error.message : "";
|
|
87
|
+
const position = /\bposition (\d+)/u.exec(message);
|
|
88
|
+
const location = position ? ` ${locationOf(value, Number(position[1]))}` : "";
|
|
89
|
+
throw new JsonShapeError(message.includes("after JSON")
|
|
90
|
+
? `unexpected text after the JSON value${location}`
|
|
91
|
+
: `invalid JSON syntax${location}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export function decodeJsonStringToken(value, openingQuoteIndex) {
|
|
95
|
+
const chunks = [];
|
|
96
|
+
let segmentStart = openingQuoteIndex + 1;
|
|
97
|
+
let index = segmentStart;
|
|
98
|
+
while (index < value.length) {
|
|
99
|
+
const code = value.charCodeAt(index);
|
|
100
|
+
if (code === 0x22) {
|
|
101
|
+
chunks.push(value.slice(segmentStart, index));
|
|
102
|
+
const decoded = chunks.join("");
|
|
103
|
+
if (!isWellFormedUnicode(decoded)) {
|
|
104
|
+
throw new JsonShapeError(`a string has an unpaired Unicode surrogate ${locationOf(value, openingQuoteIndex)}`);
|
|
105
|
+
}
|
|
106
|
+
return { decoded, nextIndex: index + 1 };
|
|
107
|
+
}
|
|
108
|
+
if (code < 0x20) {
|
|
109
|
+
throw new JsonShapeError(`a string contains a raw control character ${locationOf(value, index)}`);
|
|
110
|
+
}
|
|
111
|
+
if (code !== 0x5c) {
|
|
112
|
+
index += 1;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
chunks.push(value.slice(segmentStart, index));
|
|
116
|
+
const escape = decodeJsonEscape(value, index);
|
|
117
|
+
chunks.push(escape.decoded);
|
|
118
|
+
index = escape.nextIndex;
|
|
119
|
+
segmentStart = index;
|
|
120
|
+
}
|
|
121
|
+
throw new JsonShapeError(`a string is never closed ${locationOf(value, openingQuoteIndex)}`);
|
|
122
|
+
}
|
|
123
|
+
function decodeJsonEscape(value, backslashIndex) {
|
|
124
|
+
const escaped = value[backslashIndex + 1];
|
|
125
|
+
const simple = escaped === undefined ? undefined : simpleJsonEscapes[escaped];
|
|
126
|
+
if (simple !== undefined)
|
|
127
|
+
return { decoded: simple, nextIndex: backslashIndex + 2 };
|
|
128
|
+
const hex = value.slice(backslashIndex + 2, backslashIndex + 6);
|
|
129
|
+
if (escaped !== "u" || !/^[0-9a-fA-F]{4}$/u.test(hex)) {
|
|
130
|
+
throw new JsonShapeError(`a string has an invalid escape sequence ${locationOf(value, backslashIndex)}`);
|
|
131
|
+
}
|
|
132
|
+
return { decoded: String.fromCharCode(Number.parseInt(hex, 16)), nextIndex: backslashIndex + 6 };
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
|
|
136
|
+
* plain text that does not start like JSON, or binary content that is not named *.json.
|
|
137
|
+
*/
|
|
138
|
+
export function sidecarJsonShapeProblem(content, path, onString) {
|
|
139
|
+
let decoded;
|
|
140
|
+
try {
|
|
141
|
+
decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// Sniff the bytes anyway (invalid sequences decode to U+FFFD, which is not whitespace), so a
|
|
145
|
+
// file that starts like JSON cannot dodge the strict check with a stray invalid byte.
|
|
146
|
+
return looksLikeJson(Buffer.from(content).toString("utf8"), path) ? "the file is not valid UTF-8" : null;
|
|
147
|
+
}
|
|
148
|
+
if (!looksLikeJson(decoded, path))
|
|
149
|
+
return null;
|
|
150
|
+
if (content.length >= 3 && content[0] === 0xef && content[1] === 0xbb && content[2] === 0xbf) {
|
|
151
|
+
return "the file starts with a UTF-8 byte-order mark";
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
inspectJsonText(decoded, onString);
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (error instanceof JsonShapeError)
|
|
159
|
+
return error.reason;
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** The instruction an agent gets when it records a sidecar that fails the shape check. */
|
|
164
|
+
export function sidecarJsonRepairInstruction(path, reason) {
|
|
165
|
+
const fix = isJsonFileName(path)
|
|
166
|
+
? "Rewrite it as valid JSON (UTF-8, no byte-order mark), or save plain-text output under a name that does not end in .json"
|
|
167
|
+
: "Rewrite it as valid JSON, or as plain text that does not start with \"[\", \"{\" or a double quote (for example, put a title line first)";
|
|
168
|
+
return `${path} looks like JSON but is not valid JSON (${reason}). Forge rejects sidecars it cannot fully inspect. `
|
|
169
|
+
+ `${fix}, then resubmit with the file's new bytes and content_hash.`;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
|
|
173
|
+
* hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
|
|
174
|
+
*/
|
|
175
|
+
export function decodeJsonEscapesLeniently(value) {
|
|
176
|
+
return value.replace(jsonEscapePattern, (_match, hex, simple) => hex !== undefined ? String.fromCharCode(Number.parseInt(hex, 16)) : simpleJsonEscapes[simple ?? ""] ?? "");
|
|
177
|
+
}
|
|
178
|
+
export function looksLikeJson(value, path) {
|
|
179
|
+
if (isJsonFileName(path))
|
|
180
|
+
return true;
|
|
181
|
+
const candidate = value.trimStart().replace(/^\uFEFF/u, "").trimStart();
|
|
182
|
+
return candidate.startsWith("{") || candidate.startsWith("[") || candidate.startsWith("\"");
|
|
183
|
+
}
|
|
184
|
+
function isJsonFileName(path) {
|
|
185
|
+
return path.toLowerCase().endsWith(".json");
|
|
186
|
+
}
|
|
187
|
+
function locationOf(value, index) {
|
|
188
|
+
let line = 1;
|
|
189
|
+
let lineStart = 0;
|
|
190
|
+
for (let cursor = value.indexOf("\n"); cursor >= 0 && cursor < index; cursor = value.indexOf("\n", cursor + 1)) {
|
|
191
|
+
line += 1;
|
|
192
|
+
lineStart = cursor + 1;
|
|
193
|
+
}
|
|
194
|
+
return `at line ${line}, column ${index - lineStart + 1}`;
|
|
195
|
+
}
|
|
196
|
+
function isWellFormedUnicode(value) {
|
|
197
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
198
|
+
const code = value.charCodeAt(index);
|
|
199
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
200
|
+
const next = value.charCodeAt(index + 1);
|
|
201
|
+
if (!(next >= 0xdc00 && next <= 0xdfff))
|
|
202
|
+
return false;
|
|
203
|
+
index += 1;
|
|
204
|
+
}
|
|
205
|
+
else if (code >= 0xdc00 && code <= 0xdfff) {
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
export function isJsonWhitespace(code) {
|
|
212
|
+
return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
|
|
213
|
+
}
|
|
214
|
+
export function isJsonPunctuation(code) {
|
|
215
|
+
return code === 0x7b || code === 0x7d || code === 0x5b || code === 0x5d
|
|
216
|
+
|| code === 0x2c || code === 0x3a || code === 0x22;
|
|
217
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { BigIntStats } from "node:fs";
|
|
2
|
+
export type FileIdentity = Pick<BigIntStats, "dev" | "ino">;
|
|
3
|
+
export declare function sameFileIdentity(left: FileIdentity, right: FileIdentity): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Whether a path now names a different file than before. A filesystem that reports no
|
|
6
|
+
* identity (a zero device or id) cannot show a change, so none is claimed for it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function fileIdentityChanged(before: FileIdentity, after: FileIdentity): boolean;
|
|
9
|
+
/** The identity as text, for keys and records. */
|
|
10
|
+
export declare function fileIdentityKey(identity: FileIdentity): string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function sameFileIdentity(left, right) {
|
|
2
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Whether a path now names a different file than before. A filesystem that reports no
|
|
6
|
+
* identity (a zero device or id) cannot show a change, so none is claimed for it.
|
|
7
|
+
*/
|
|
8
|
+
export function fileIdentityChanged(before, after) {
|
|
9
|
+
const known = before.dev !== 0n && before.ino !== 0n && after.dev !== 0n && after.ino !== 0n;
|
|
10
|
+
return known && !sameFileIdentity(before, after);
|
|
11
|
+
}
|
|
12
|
+
/** The identity as text, for keys and records. */
|
|
13
|
+
export function fileIdentityKey(identity) {
|
|
14
|
+
return `${identity.dev}:${identity.ino}`;
|
|
15
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface ReplaceFileOptions {
|
|
2
|
+
readonly deadlineMs?: number;
|
|
3
|
+
/** Test support: the rename to retry. */
|
|
4
|
+
readonly rename?: (from: string, to: string) => Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
/** Renames `temporaryPath` over `targetPath`, waiting out a reader that holds the target open. */
|
|
7
|
+
export declare function replaceFile(temporaryPath: string, targetPath: string, options?: ReplaceFileOptions): Promise<void>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { monotonicNowMs } from "../time/monotonic.js";
|
|
3
|
+
// Windows refuses to rename over a file any other handle has open (EPERM,
|
|
4
|
+
// EBUSY, or EACCES), even one opened to share delete, which is how Node opens
|
|
5
|
+
// every file. A receipt that agents and Forge poll is open for a moment many
|
|
6
|
+
// times a second, and an antivirus scan can hold it longer; fixed-interval
|
|
7
|
+
// retries can also fall into step with a poller of the same period. Replacing
|
|
8
|
+
// it therefore retries with growing, jittered delays until a deadline, so a
|
|
9
|
+
// reader can delay a replace but never fail it.
|
|
10
|
+
const replaceRetryCodes = new Set(["EACCES", "EBUSY", "EPERM"]);
|
|
11
|
+
const defaultReplaceDeadlineMs = 15_000;
|
|
12
|
+
const firstRetryDelayMs = 5;
|
|
13
|
+
const maximumRetryDelayMs = 250;
|
|
14
|
+
/** Renames `temporaryPath` over `targetPath`, waiting out a reader that holds the target open. */
|
|
15
|
+
export async function replaceFile(temporaryPath, targetPath, options = {}) {
|
|
16
|
+
const rename = options.rename ?? fs.rename;
|
|
17
|
+
const deadline = monotonicNowMs() + (options.deadlineMs ?? defaultReplaceDeadlineMs);
|
|
18
|
+
for (let attempt = 0;; attempt += 1) {
|
|
19
|
+
try {
|
|
20
|
+
await rename(temporaryPath, targetPath);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
const code = error?.code;
|
|
25
|
+
const remainingMs = deadline - monotonicNowMs();
|
|
26
|
+
if (!code || !replaceRetryCodes.has(code) || remainingMs <= 0)
|
|
27
|
+
throw error;
|
|
28
|
+
const ceilingMs = Math.min(maximumRetryDelayMs, firstRetryDelayMs * 2 ** Math.min(attempt, 6));
|
|
29
|
+
const delayMs = Math.min(remainingMs, ceilingMs / 2 + Math.random() * ceilingMs / 2);
|
|
30
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -1,12 +1,23 @@
|
|
|
1
|
-
import type { HostProcessSupervisorMetadata } from "./host-process-supervisor.js";
|
|
1
|
+
import type { HostProcessSupervisorMetadata, WindowsSupervisorJobGone } from "./host-process-supervisor.js";
|
|
2
|
+
export { waitForWindowsSupervisorJobGone, type WindowsSupervisorJobGone } from "./host-process-supervisor.js";
|
|
2
3
|
export type HostProcessRecoveryOutcome = "absent" | "terminated" | "pid_reused" | "unverifiable";
|
|
3
4
|
export interface HostProcessRecovery {
|
|
4
5
|
recover(metadata: HostProcessSupervisorMetadata): Promise<HostProcessRecoveryOutcome>;
|
|
5
6
|
}
|
|
6
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Exact, birth-marker-fenced recovery for a process tree left by an old bridge.
|
|
9
|
+
*
|
|
10
|
+
* On Windows the recorded root is the job supervisor, which holds the only handle to a
|
|
11
|
+
* kill-on-close Job Object holding the whole tree. The root's exit only starts that job's
|
|
12
|
+
* teardown: Windows reports a process gone once its exit code is set, before its handles
|
|
13
|
+
* are closed, and the members are stopped after that. So a Windows tree is reported gone
|
|
14
|
+
* only once its Job Object no longer exists, which is when no member is left.
|
|
15
|
+
*/
|
|
7
16
|
export declare class ExactHostProcessRecovery implements HostProcessRecovery {
|
|
8
17
|
private readonly platform;
|
|
9
18
|
private readonly graceMs;
|
|
10
|
-
|
|
19
|
+
private readonly windowsJobGone;
|
|
20
|
+
constructor(platform?: NodeJS.Platform, graceMs?: number, windowsJobGone?: WindowsSupervisorJobGone);
|
|
11
21
|
recover(metadata: HostProcessSupervisorMetadata): Promise<HostProcessRecoveryOutcome>;
|
|
22
|
+
private stopRoot;
|
|
12
23
|
}
|
|
@@ -1,14 +1,34 @@
|
|
|
1
|
-
import { captureHostProcessIdentity } from "./host-process-supervisor.js";
|
|
1
|
+
import { captureHostProcessIdentity, waitForWindowsSupervisorJobGone } from "./host-process-supervisor.js";
|
|
2
2
|
import { monotonicNowMs } from "../time/monotonic.js";
|
|
3
|
-
|
|
3
|
+
export { waitForWindowsSupervisorJobGone } from "./host-process-supervisor.js";
|
|
4
|
+
/**
|
|
5
|
+
* Exact, birth-marker-fenced recovery for a process tree left by an old bridge.
|
|
6
|
+
*
|
|
7
|
+
* On Windows the recorded root is the job supervisor, which holds the only handle to a
|
|
8
|
+
* kill-on-close Job Object holding the whole tree. The root's exit only starts that job's
|
|
9
|
+
* teardown: Windows reports a process gone once its exit code is set, before its handles
|
|
10
|
+
* are closed, and the members are stopped after that. So a Windows tree is reported gone
|
|
11
|
+
* only once its Job Object no longer exists, which is when no member is left.
|
|
12
|
+
*/
|
|
4
13
|
export class ExactHostProcessRecovery {
|
|
5
14
|
platform;
|
|
6
15
|
graceMs;
|
|
7
|
-
|
|
16
|
+
windowsJobGone;
|
|
17
|
+
constructor(platform = process.platform, graceMs = 2_000, windowsJobGone = waitForWindowsSupervisorJobGone) {
|
|
8
18
|
this.platform = platform;
|
|
9
19
|
this.graceMs = graceMs;
|
|
20
|
+
this.windowsJobGone = windowsJobGone;
|
|
10
21
|
}
|
|
11
22
|
async recover(metadata) {
|
|
23
|
+
const outcome = await this.stopRoot(metadata);
|
|
24
|
+
if (outcome === "unverifiable" || this.platform !== "win32" || metadata.strategy !== "windows_job_object")
|
|
25
|
+
return outcome;
|
|
26
|
+
if (!await this.windowsJobGone(metadata.supervisorId, this.graceMs)) {
|
|
27
|
+
throw new Error(`host_process_recovery_degraded: the Job Object of supervisor ${metadata.supervisorId} still holds processes after its root stopped.`);
|
|
28
|
+
}
|
|
29
|
+
return outcome;
|
|
30
|
+
}
|
|
31
|
+
async stopRoot(metadata) {
|
|
12
32
|
if (!processExists(metadata.rootPid))
|
|
13
33
|
return "absent";
|
|
14
34
|
if (!metadata.rootIdentity)
|
|
@@ -56,5 +56,17 @@ export declare function persistHostProcessSupervisorMetadata(launch: HostProcess
|
|
|
56
56
|
* at an unrelated process.
|
|
57
57
|
*/
|
|
58
58
|
export declare function captureHostProcessIdentity(pid: number, platform?: NodeJS.Platform): string | null;
|
|
59
|
-
export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number): Promise<void>;
|
|
59
|
+
export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number, windowsJobGone?: WindowsSupervisorJobGone): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Resolves true once a Windows job supervisor's Job Object no longer exists, false when it
|
|
62
|
+
* still does at the timeout or cannot be checked.
|
|
63
|
+
*/
|
|
64
|
+
export type WindowsSupervisorJobGone = (supervisorId: string, timeoutMs: number) => Promise<boolean>;
|
|
65
|
+
/**
|
|
66
|
+
* Polls for the job supervisor's named Job Object (runtime/windows-job-supervisor.ps1 names
|
|
67
|
+
* it Local\Forge-<supervisorId>). A job object exists while any handle or member process
|
|
68
|
+
* holds it, and the supervisor's handle closed with it, so its absence means no member is
|
|
69
|
+
* left. Any answer but "not found" (an unreadable job, a failed check) is not proof.
|
|
70
|
+
*/
|
|
71
|
+
export declare const waitForWindowsSupervisorJobGone: WindowsSupervisorJobGone;
|
|
60
72
|
export declare function windowsPowerShellPath(): string;
|