@loucompanion/forge-bridge 0.2.1-dev.573a8a5fa582 → 0.2.1-dev.7171bf414613

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.
Files changed (121) hide show
  1. package/README.md +38 -2
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +62 -92
  6. package/dist/bridge/bridge.types.d.ts +6 -0
  7. package/dist/bridge/default-session-service.d.ts +13 -0
  8. package/dist/bridge/default-session-service.js +22 -0
  9. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  10. package/dist/bridge/dispatch-offer-policy.js +58 -0
  11. package/dist/cleanup/cleanup-wip.js +3 -3
  12. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  13. package/dist/cleanup/forge-owned-paths.js +9 -0
  14. package/dist/cli/cli.help.js +1 -1
  15. package/dist/cli/cli.service.js +3 -3
  16. package/dist/cli/local-config.d.ts +2 -0
  17. package/dist/cli/local-config.js +3 -0
  18. package/dist/runtime/host-load-capacity.d.ts +198 -0
  19. package/dist/runtime/host-load-capacity.js +353 -0
  20. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  21. package/dist/runtime/host-load-child-environment.js +35 -1
  22. package/dist/runtime/host-load-governor-config.d.ts +23 -2
  23. package/dist/runtime/host-load-governor-config.js +20 -2
  24. package/dist/runtime/host-load-governor.d.ts +81 -1
  25. package/dist/runtime/host-load-governor.js +184 -15
  26. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  27. package/dist/runtime/host-load-live-test-slots.js +193 -0
  28. package/dist/runtime/host-load-sampler.d.ts +17 -0
  29. package/dist/runtime/host-load-sampler.js +24 -0
  30. package/dist/runtime/host-load-step-run.d.ts +37 -3
  31. package/dist/runtime/host-load-step-run.js +63 -7
  32. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  33. package/dist/runtime/host-load-test-slot.js +19 -7
  34. package/dist/sandbox/runtime.d.ts +1 -2
  35. package/dist/sandbox/runtime.js +7 -13
  36. package/dist/sandbox/sandbox-input.d.ts +22 -0
  37. package/dist/sandbox/sandbox-input.js +49 -0
  38. package/dist/sandbox/workspace.service.js +15 -2
  39. package/dist/session/managed-attempt-tools.js +6 -29
  40. package/dist/session/managed-build-receipt.d.ts +3 -1
  41. package/dist/session/managed-build-receipt.js +5 -2
  42. package/dist/session/managed-command-environment.d.ts +8 -0
  43. package/dist/session/managed-command-environment.js +28 -0
  44. package/dist/session/managed-command-host-load.d.ts +10 -5
  45. package/dist/session/managed-command-host-load.js +18 -14
  46. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  47. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  48. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  49. package/dist/session/phase-completion.artifacts.js +63 -165
  50. package/dist/session/phase-completion.d.ts +25 -2
  51. package/dist/session/phase-completion.helpers.js +5 -53
  52. package/dist/session/phase-completion.js +15 -32
  53. package/dist/session/phase-completion.mcp-args.js +69 -2
  54. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  55. package/dist/session/phase-completion.phase-aliases.js +43 -0
  56. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  57. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  58. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  59. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  60. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  61. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  62. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  63. package/dist/session/phase-completion.pr-review.js +294 -0
  64. package/dist/session/phase-completion.prompts.d.ts +1 -1
  65. package/dist/session/phase-completion.prompts.js +14 -0
  66. package/dist/session/phase-completion.runtime.js +9 -3
  67. package/dist/session/phase-completion.schemas.js +12 -2
  68. package/dist/session/phase-completion.validation.d.ts +1 -0
  69. package/dist/session/phase-completion.validation.js +9 -1
  70. package/dist/session/pr-review-diff-base.d.ts +18 -0
  71. package/dist/session/pr-review-diff-base.js +45 -0
  72. package/dist/session/pr-review-placement.d.ts +50 -0
  73. package/dist/session/pr-review-placement.js +91 -0
  74. package/dist/session/pre-publication-change-set.d.ts +62 -0
  75. package/dist/session/pre-publication-change-set.js +166 -0
  76. package/dist/session/pre-publication-host-load.js +6 -5
  77. package/dist/session/pre-publication-process.js +3 -2
  78. package/dist/session/pre-publication-validation.d.ts +2 -1
  79. package/dist/session/pre-publication-validation.js +31 -36
  80. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  81. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  82. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  83. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  84. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  85. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  86. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  87. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  88. package/dist/session/provider-cli/pre-publication-repair.js +7 -3
  89. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  90. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  91. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  92. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  93. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  94. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -13
  95. package/dist/session/provider-cli/provider-cli.prompts.js +123 -107
  96. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  97. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  98. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  99. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  100. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  101. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  102. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  103. package/dist/session/provider-cli/provider-cli.service.js +24 -139
  104. package/dist/session/sandbox-host-capacity-gate.js +28 -6
  105. package/dist/session/session.parse-helpers.d.ts +10 -0
  106. package/dist/session/session.parse-helpers.js +84 -0
  107. package/dist/session/session.runtime-refresh.d.ts +46 -0
  108. package/dist/session/session.runtime-refresh.js +116 -0
  109. package/dist/session/session.service.d.ts +2 -1
  110. package/dist/session/session.service.js +40 -95
  111. package/dist/session/session.types.d.ts +4 -0
  112. package/dist/session/session.types.js +7 -77
  113. package/dist/session/session.types.pr-review.d.ts +59 -0
  114. package/dist/session/session.types.pr-review.js +53 -0
  115. package/dist/version.d.ts +1 -1
  116. package/dist/version.js +1 -1
  117. package/dist/worktree/artifact-injector.js +24 -0
  118. package/dist/worktree/worktree.service.d.ts +22 -0
  119. package/dist/worktree/worktree.service.js +116 -12
  120. package/dist/worktree/worktree.types.d.ts +7 -0
  121. package/package.json +1 -1
@@ -0,0 +1,61 @@
1
+ import { type HostLiveReading, type HostLiveTestSlots } from "./host-load-capacity.js";
2
+ import type { HostLoadGovernorSource } from "./host-load-sampler.js";
3
+ import { type HostLoadOwnerLiveness } from "./host-load-token-ledger.js";
4
+ /** What hostLiveReadings reads the sampler's history with. */
5
+ export interface HostLiveReadingContext {
6
+ readonly load: HostLoadGovernorSource;
7
+ /** Every CPU on the host: hostCpuPercent's denominator. */
8
+ readonly logicalCpus: number;
9
+ readonly sampleStaleMs: number;
10
+ /** Wall clock, for the staleness of the latest sample. */
11
+ readonly nowMs: number;
12
+ /** The bridge cgroup's anonymous memory with no heavy step running; null when unknown. */
13
+ readonly idleOwnMemoryBytes: number | null;
14
+ }
15
+ /** The sampler's fresh history as host readings; a stale history adds nothing. */
16
+ export declare function hostLiveReadings(context: HostLiveReadingContext): HostLiveReading[];
17
+ export declare function liveTestSlotsDirectory(stateRoot: string): string;
18
+ /** A lowered count is rewritten this often while it holds; readers drop one older than the TTL. */
19
+ export declare const liveTestSlotsRefreshMs = 30000;
20
+ export declare const liveTestSlotsTtlMs = 90000;
21
+ /**
22
+ * This governor's lowered count, shared with every governor on the state root, and theirs read
23
+ * back. Each governor writes a file of its own (no two processes write one file); it is
24
+ * written while the count is lowered (when it changes, and every refresh period while the
25
+ * controller takes in fresh readings) and removed once the count is back. A file whose writer
26
+ * stopped refreshing it lapses after the TTL: a writer whose sampler went quiet stops
27
+ * refreshing, so a reduction nothing confirms any more does not hold every governor back.
28
+ * A reader skips a file another host wrote and removes one whose writer is gone. Times are
29
+ * wall-clock: they are compared across processes.
30
+ */
31
+ export declare class LiveTestSlotsBoard {
32
+ private readonly directory;
33
+ private readonly fileName;
34
+ private readonly now;
35
+ private readonly liveness;
36
+ private readonly hostname;
37
+ private published;
38
+ /** When a pass last took in a fresh reading for this governor's count. */
39
+ private freshAtMs;
40
+ private writing;
41
+ constructor(stateRoot: string, options?: LiveTestSlotsBoardOptions);
42
+ /**
43
+ * Publishes this governor's own count (never one it adopted from another). `freshReading` says
44
+ * whether the pass behind it took in a new reading: an unchanged count is rewritten only while
45
+ * one came in within the TTL, so it lapses once the sampler goes quiet.
46
+ */
47
+ publish(own: HostLiveTestSlots, configured: number, freshReading: boolean): void;
48
+ /** The lowest count another governor on this state root has in force; null when none is lowered. */
49
+ lowest(): Promise<HostLiveTestSlots | null>;
50
+ /** Settles once every publish so far is on disk (tests). */
51
+ flushed(): Promise<void>;
52
+ private enqueue;
53
+ }
54
+ export interface LiveTestSlotsBoardOptions {
55
+ /** Wall clock (tests). */
56
+ readonly now?: () => number;
57
+ /** Whether a writer process still runs; the ledger's OS check by default. */
58
+ readonly liveness?: HostLoadOwnerLiveness;
59
+ /** This host's name; os.hostname() by default. */
60
+ readonly hostname?: string;
61
+ }
@@ -0,0 +1,193 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { reportsAvailableMemory } from "./host-load-capacity.js";
6
+ import { currentHostLoadTokenOwner, processHostLoadOwnerLiveness, } from "./host-load-token-ledger.js";
7
+ /** The sampler's fresh history as host readings; a stale history adds nothing. */
8
+ export function hostLiveReadings(context) {
9
+ const { load } = context;
10
+ const latest = load.current();
11
+ const latestAtMs = latest ? Date.parse(latest.sampledAt) : Number.NaN;
12
+ if (!latest || !Number.isFinite(latestAtMs) || context.nowMs - latestAtMs > context.sampleStaleMs)
13
+ return [];
14
+ const history = load.recent();
15
+ const samples = history.at(-1)?.sampledAt === latest.sampledAt ? history : [...history, latest];
16
+ // Each sample's own attribution, which counts Docker sandboxes as Forge's own CPU too.
17
+ const attributions = new Map();
18
+ for (const attribution of load.recentCpuAttributions?.() ?? [])
19
+ attributions.set(attribution.sampledAt, attribution);
20
+ const latestAttribution = load.cpuAttribution?.() ?? null;
21
+ if (latestAttribution)
22
+ attributions.set(latestAttribution.sampledAt, latestAttribution);
23
+ // macOS reports free pages only, which reads most of its memory as in use.
24
+ const memoryReadable = reportsAvailableMemory(load.facts()?.platform ?? process.platform);
25
+ return samples.flatMap(sample => {
26
+ const reading = liveReading(context, sample, attributions.get(sample.sampledAt) ?? null, memoryReadable);
27
+ return reading ? [reading] : [];
28
+ });
29
+ }
30
+ /**
31
+ * One sample as a host reading, stamped with the sampler's monotonic clock when it keeps one.
32
+ * With a dedicated cgroup, Forge's CPU comes from the sample's attribution (bridge and sandbox
33
+ * cgroups); a sample without one is left out rather than read with its sandboxes counted as
34
+ * other work. Forge's memory is the cgroup's anonymous memory above its idle baseline, when both
35
+ * are known.
36
+ */
37
+ function liveReading(context, sample, attribution, memoryReadable) {
38
+ const dedicated = sample.ownCgroupDedicated;
39
+ if (dedicated && !attribution)
40
+ return null;
41
+ const sampledAtMs = context.load.sampleMonotonicMs
42
+ ? context.load.sampleMonotonicMs(sample.sampledAt)
43
+ : Date.parse(sample.sampledAt);
44
+ if (sampledAtMs === null)
45
+ return null;
46
+ const ownMemory = dedicated ? sample.ownCgroup?.memoryAnonBytes ?? null : null;
47
+ return {
48
+ sampledAtMs,
49
+ hostCoresInUse: sample.hostCpuPercent === null ? null : (sample.hostCpuPercent / 100) * context.logicalCpus,
50
+ externalCoresInUse: dedicated ? attribution?.externalCoresInUse ?? null : null,
51
+ memoryAvailableBytes: memoryReadable ? sample.memoryAvailableBytes : null,
52
+ forgeMemoryBytes: ownMemory === null || context.idleOwnMemoryBytes === null
53
+ ? null
54
+ : Math.max(0, ownMemory - context.idleOwnMemoryBytes),
55
+ };
56
+ }
57
+ export function liveTestSlotsDirectory(stateRoot) {
58
+ return path.join(stateRoot, "host-load-governor", "live-test-slots");
59
+ }
60
+ /** A lowered count is rewritten this often while it holds; readers drop one older than the TTL. */
61
+ export const liveTestSlotsRefreshMs = 30_000;
62
+ export const liveTestSlotsTtlMs = 90_000;
63
+ /** A file this old belongs to a governor that is gone: any reader removes it. */
64
+ const abandonedMs = 10 * 60_000;
65
+ /** The most published counts read in one pass. */
66
+ const maximumEntries = 64;
67
+ /**
68
+ * This governor's lowered count, shared with every governor on the state root, and theirs read
69
+ * back. Each governor writes a file of its own (no two processes write one file); it is
70
+ * written while the count is lowered (when it changes, and every refresh period while the
71
+ * controller takes in fresh readings) and removed once the count is back. A file whose writer
72
+ * stopped refreshing it lapses after the TTL: a writer whose sampler went quiet stops
73
+ * refreshing, so a reduction nothing confirms any more does not hold every governor back.
74
+ * A reader skips a file another host wrote and removes one whose writer is gone. Times are
75
+ * wall-clock: they are compared across processes.
76
+ */
77
+ export class LiveTestSlotsBoard {
78
+ directory;
79
+ fileName = `${randomUUID()}.json`;
80
+ now;
81
+ liveness;
82
+ hostname;
83
+ published = null;
84
+ /** When a pass last took in a fresh reading for this governor's count. */
85
+ freshAtMs = null;
86
+ writing = Promise.resolve();
87
+ constructor(stateRoot, options = {}) {
88
+ this.directory = liveTestSlotsDirectory(stateRoot);
89
+ this.now = options.now ?? Date.now;
90
+ this.liveness = options.liveness ?? processHostLoadOwnerLiveness;
91
+ this.hostname = options.hostname ?? os.hostname();
92
+ }
93
+ /**
94
+ * Publishes this governor's own count (never one it adopted from another). `freshReading` says
95
+ * whether the pass behind it took in a new reading: an unchanged count is rewritten only while
96
+ * one came in within the TTL, so it lapses once the sampler goes quiet.
97
+ */
98
+ publish(own, configured, freshReading) {
99
+ const nowMs = this.now();
100
+ if (freshReading)
101
+ this.freshAtMs = nowMs;
102
+ const filePath = path.join(this.directory, this.fileName);
103
+ if (own.slots >= configured) {
104
+ if (this.published === null)
105
+ return;
106
+ this.published = null;
107
+ this.enqueue(async () => await fs.rm(filePath, { force: true }));
108
+ return;
109
+ }
110
+ const previous = this.published;
111
+ if (previous?.slots === own.slots && previous.detail === own.detail) {
112
+ const confirmed = this.freshAtMs !== null && nowMs - this.freshAtMs <= liveTestSlotsTtlMs;
113
+ if (!confirmed || nowMs - previous.atMs < liveTestSlotsRefreshMs)
114
+ return;
115
+ }
116
+ this.published = { slots: own.slots, detail: own.detail, atMs: nowMs };
117
+ const entry = {
118
+ schemaVersion: 1,
119
+ writer: currentHostLoadTokenOwner(),
120
+ hostname: this.hostname,
121
+ slots: own.slots,
122
+ detail: own.detail,
123
+ writtenAt: new Date(nowMs).toISOString(),
124
+ };
125
+ this.enqueue(async () => {
126
+ await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
127
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
128
+ try {
129
+ await fs.writeFile(temporary, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
130
+ await fs.rename(temporary, filePath);
131
+ }
132
+ catch (error) {
133
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
134
+ throw error;
135
+ }
136
+ });
137
+ }
138
+ /** The lowest count another governor on this state root has in force; null when none is lowered. */
139
+ async lowest() {
140
+ const names = await fs.readdir(this.directory).catch(() => []);
141
+ const nowMs = this.now();
142
+ let lowest = null;
143
+ for (const name of names.filter(entry => entry.endsWith(".json") && entry !== this.fileName).slice(0, maximumEntries)) {
144
+ const filePath = path.join(this.directory, name);
145
+ const entry = await fs.readFile(filePath, "utf8").then(parseEntry).catch(() => null);
146
+ const ageMs = entry ? nowMs - Date.parse(entry.writtenAt) : Number.NaN;
147
+ // Another host's pid cannot be checked here, and its load is not this host's.
148
+ if (entry && entry.hostname !== this.hostname)
149
+ continue;
150
+ const writerGone = entry !== null && !this.liveness.isLive(entry.writer);
151
+ if (ageMs > abandonedMs || writerGone)
152
+ void fs.rm(filePath, { force: true }).catch(() => undefined);
153
+ // A clock stepped far back makes an entry look written in the future: it is not trusted either.
154
+ if (!entry || writerGone || !(Math.abs(ageMs) <= liveTestSlotsTtlMs))
155
+ continue;
156
+ if (!lowest || entry.slots < lowest.slots)
157
+ lowest = { slots: entry.slots, detail: entry.detail };
158
+ }
159
+ return lowest;
160
+ }
161
+ /** Settles once every publish so far is on disk (tests). */
162
+ async flushed() {
163
+ await this.writing;
164
+ }
165
+ enqueue(write) {
166
+ this.writing = this.writing.then(write).catch(() => undefined);
167
+ }
168
+ }
169
+ function parseEntry(content) {
170
+ const raw = JSON.parse(content);
171
+ if (!raw || raw.schemaVersion !== 1 || typeof raw.writtenAt !== "string" || typeof raw.hostname !== "string")
172
+ return null;
173
+ const writer = parseWriter(raw.writer);
174
+ const slots = raw.slots;
175
+ if (!writer || typeof slots !== "number" || !Number.isInteger(slots) || slots < 1)
176
+ return null;
177
+ return {
178
+ schemaVersion: 1,
179
+ writer,
180
+ hostname: raw.hostname,
181
+ slots: Math.min(8, slots),
182
+ detail: typeof raw.detail === "string" ? raw.detail.slice(0, 500) : "",
183
+ writtenAt: raw.writtenAt,
184
+ };
185
+ }
186
+ function parseWriter(raw) {
187
+ if (!raw || typeof raw !== "object")
188
+ return null;
189
+ const { pid, processIdentity, processInstanceId } = raw;
190
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || typeof processInstanceId !== "string")
191
+ return null;
192
+ return { pid, processIdentity: typeof processIdentity === "string" ? processIdentity : null, processInstanceId };
193
+ }
@@ -76,6 +76,17 @@ export interface HostCpuAttribution {
76
76
  /** The governor's view: the load sample plus the CPU attribution from the same window. */
77
77
  export interface HostLoadGovernorSource extends Pick<HostLoadSource, "start" | "facts" | "current" | "recent"> {
78
78
  cpuAttribution?(): HostCpuAttribution | null;
79
+ /**
80
+ * The CPU attribution of each sample in recent(), oldest first, matched by sampledAt. It
81
+ * counts the Docker sandbox cgroups as Forge's own, which the snapshots' ownCgroup does not.
82
+ */
83
+ recentCpuAttributions?(): readonly HostCpuAttribution[];
84
+ /**
85
+ * When a sample in recent() was taken on the sampler's monotonic clock (ms), matched by
86
+ * sampledAt; null for one it does not know. Readings are ordered and timed by it, so a
87
+ * wall-clock step (NTP, resume) cannot reorder them.
88
+ */
89
+ sampleMonotonicMs?(sampledAt: string): number | null;
79
90
  /**
80
91
  * Free memory under the tightest cgroup `memory.max` on the bridge's path
81
92
  * (null when none is set), from the latest sample. The governor budgets
@@ -115,6 +126,10 @@ export declare class HostLoadSampler implements HostLoadSource {
115
126
  private hostFacts;
116
127
  private latest;
117
128
  private readonly history;
129
+ private readonly attributionHistory;
130
+ /** Each kept sample's monotonic time, by sampledAt (insertion order is sample order). */
131
+ private readonly monotonicStamps;
132
+ private readMonotonicMs;
118
133
  private cpuMark;
119
134
  private hostCpuMark;
120
135
  private latestCpuAttribution;
@@ -129,6 +144,8 @@ export declare class HostLoadSampler implements HostLoadSource {
129
144
  cpuAttribution(): HostCpuAttribution | null;
130
145
  cgroupMemoryHeadroomBytes(): number | null;
131
146
  recent(): readonly HostLoadSnapshot[];
147
+ recentCpuAttributions(): readonly HostCpuAttribution[];
148
+ sampleMonotonicMs(sampledAt: string): number | null;
132
149
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
133
150
  start(): Promise<void>;
134
151
  stop(): void;
@@ -25,6 +25,10 @@ export class HostLoadSampler {
25
25
  hostFacts = null;
26
26
  latest = null;
27
27
  history = [];
28
+ attributionHistory = [];
29
+ /** Each kept sample's monotonic time, by sampledAt (insertion order is sample order). */
30
+ monotonicStamps = new Map();
31
+ readMonotonicMs = 0;
28
32
  cpuMark = null;
29
33
  hostCpuMark = null;
30
34
  latestCpuAttribution = null;
@@ -61,6 +65,12 @@ export class HostLoadSampler {
61
65
  recent() {
62
66
  return [...this.history];
63
67
  }
68
+ recentCpuAttributions() {
69
+ return [...this.attributionHistory];
70
+ }
71
+ sampleMonotonicMs(sampledAt) {
72
+ return this.monotonicStamps.get(sampledAt) ?? null;
73
+ }
64
74
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
65
75
  start() {
66
76
  if (this.timer)
@@ -88,6 +98,19 @@ export class HostLoadSampler {
88
98
  this.history.push(snapshot);
89
99
  if (this.history.length > retainedSampleCount)
90
100
  this.history.splice(0, this.history.length - retainedSampleCount);
101
+ this.monotonicStamps.set(snapshot.sampledAt, this.readMonotonicMs);
102
+ for (const stamp of this.monotonicStamps.keys()) {
103
+ if (this.monotonicStamps.size <= retainedSampleCount)
104
+ break;
105
+ this.monotonicStamps.delete(stamp);
106
+ }
107
+ const attribution = this.latestCpuAttribution;
108
+ if (attribution?.sampledAt === snapshot.sampledAt) {
109
+ this.attributionHistory.push(attribution);
110
+ if (this.attributionHistory.length > retainedSampleCount) {
111
+ this.attributionHistory.splice(0, this.attributionHistory.length - retainedSampleCount);
112
+ }
113
+ }
91
114
  return snapshot;
92
115
  })
93
116
  .finally(() => {
@@ -111,6 +134,7 @@ export class HostLoadSampler {
111
134
  async readSnapshot() {
112
135
  const sampledAtMs = this.now();
113
136
  const monotonicMs = this.monotonicNow();
137
+ this.readMonotonicMs = monotonicMs;
114
138
  if (this.environment.platform === "win32")
115
139
  return this.readWindowsSnapshot(sampledAtMs, monotonicMs);
116
140
  const linux = this.environment.platform === "linux";
@@ -1,5 +1,5 @@
1
1
  import type { HostLoadAdmissionDecision } from "./host-load-admission.js";
2
- import type { HostLoadAdmission, HostLoadStepGate } from "./host-load-governor.js";
2
+ import { type HostLoadAdmission, type HostLoadStepGate } from "./host-load-governor.js";
3
3
  import type { HostLoadStepProcess } from "./host-load-step-reaper.js";
4
4
  import type { HostLoadStepClassification } from "./host-load-step-class.js";
5
5
  import type { HostLoadTokenPriority } from "./host-load-token-ledger.js";
@@ -10,8 +10,8 @@ export interface HostGovernedStep {
10
10
  readonly dispatchAttemptId: string | null;
11
11
  readonly priority: HostLoadTokenPriority;
12
12
  readonly signal?: AbortSignal;
13
- /** Called once, when the step first has to wait for capacity. */
14
- readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
13
+ /** Called when the step first has to wait for capacity, and again whenever that wait changes. */
14
+ readonly onWaiting?: (decision: HostLoadAdmissionDecision, fence: WaitReportFence) => void | Promise<void>;
15
15
  /**
16
16
  * The step records its own fenced outcome (a managed command's receipt). Otherwise a
17
17
  * step whose token was reclaimed while it ran fails with host_capacity_token_fenced.
@@ -53,6 +53,40 @@ export declare function retentionFor(error: unknown): HostLoadRetention | null;
53
53
  * is returned when `run` settles, whether it succeeded, failed or was stopped.
54
54
  */
55
55
  export declare function runHostGovernedStep<T>(gate: HostLoadStepGate | undefined, step: HostGovernedStep, run: (hostLoadWaitMs: HostLoadWait, control: HostLoadStepControl) => Promise<T>): Promise<T>;
56
+ /** A step's wait reports, run in order; see orderedWaitReports. */
57
+ export interface OrderedWaitReports {
58
+ readonly onWaiting: ((decision: HostLoadAdmissionDecision) => void) | undefined;
59
+ /**
60
+ * Resolves once every report made so far has landed, or after the governor's drain bound
61
+ * (afterNotified) at the latest. Either way the reports are then closed: one still queued, or
62
+ * made later, is dropped as stale and never runs, and one still running can no longer commit
63
+ * (WaitReportFence). A commit already under way is awaited, so it lands before what follows.
64
+ */
65
+ drained(): Promise<void>;
66
+ }
67
+ /**
68
+ * Handed to each wait report. The bound in `drained` stops waiting for a report, not the report
69
+ * itself, so a slow write that finally succeeds would land after the step's own state. A report
70
+ * that replaces durable state (a receipt) makes that last replace through `commit`: it then runs
71
+ * only while the reports are open, and never after the step's state is written.
72
+ */
73
+ export interface WaitReportFence {
74
+ /** False once the reports are closed. */
75
+ readonly current: boolean;
76
+ /** Runs `replace` only while the reports are open; false when it was skipped as stale. */
77
+ commit(replace: () => Promise<void>): Promise<boolean>;
78
+ }
79
+ /**
80
+ * Runs a step's wait reports one at a time, in the order they were made, and hands the governor a
81
+ * callback that returns at once. The governor waits only a few seconds for a report (afterNotified),
82
+ * so a report it waited on could still land after the step's admitted or failed state. The step
83
+ * awaits `drained` before writing that state instead, so a late "waiting" can never replace it.
84
+ * `drained` keeps the governor's bound, so a report that never settles (a stuck checkpoint or
85
+ * event) cannot hold the step's admission, or its failure, back for longer than that. A report
86
+ * still running after the bound can no longer replace a receipt (WaitReportFence.commit); an
87
+ * appended event it already sent stays in the log as history of the wait, which it was.
88
+ */
89
+ export declare function orderedWaitReports(report: ((decision: HostLoadAdmissionDecision, fence: WaitReportFence) => void | Promise<void>) | undefined): OrderedWaitReports;
56
90
  /**
57
91
  * Returns a step's token, unless part of its process tree could not be proven
58
92
  * gone: the token (and its cost) is then kept until the tree is.
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import { isProcessTreeTerminationUnproven, ProcessTreeTerminationError } from "../shared/process/process.js";
3
+ import { afterNotified } from "./host-load-governor.js";
3
4
  /**
4
5
  * The retention a step's failure calls for: a tree that could not be proven gone,
5
6
  * whether the runner said so with its own check (ProcessTreeTerminationError) or a
@@ -21,13 +22,21 @@ export function retentionFor(error) {
21
22
  export async function runHostGovernedStep(gate, step, run) {
22
23
  if (!gate?.enabled)
23
24
  return await run(null, {});
24
- const admission = await gate.acquire({
25
- stepClass: step.classification.stepClass,
26
- label: step.label,
27
- cost: step.classification.cost,
28
- dispatchAttemptId: step.dispatchAttemptId,
29
- priority: step.priority,
30
- }, { signal: step.signal, onWaiting: step.onWaiting });
25
+ const reports = orderedWaitReports(step.onWaiting);
26
+ let admission;
27
+ try {
28
+ admission = await gate.acquire({
29
+ stepClass: step.classification.stepClass,
30
+ label: step.label,
31
+ cost: step.classification.cost,
32
+ dispatchAttemptId: step.dispatchAttemptId,
33
+ priority: step.priority,
34
+ }, { signal: step.signal, onWaiting: reports.onWaiting });
35
+ }
36
+ finally {
37
+ // Every wait report lands before the step's own outcome (its launch, or why it was never admitted).
38
+ await reports.drained();
39
+ }
31
40
  let retention = null;
32
41
  try {
33
42
  let outcome;
@@ -55,6 +64,53 @@ export async function runHostGovernedStep(gate, step, run) {
55
64
  await returnHostLoadToken(admission, retention, step.onReleaseFailed);
56
65
  }
57
66
  }
67
+ /**
68
+ * Runs a step's wait reports one at a time, in the order they were made, and hands the governor a
69
+ * callback that returns at once. The governor waits only a few seconds for a report (afterNotified),
70
+ * so a report it waited on could still land after the step's admitted or failed state. The step
71
+ * awaits `drained` before writing that state instead, so a late "waiting" can never replace it.
72
+ * `drained` keeps the governor's bound, so a report that never settles (a stuck checkpoint or
73
+ * event) cannot hold the step's admission, or its failure, back for longer than that. A report
74
+ * still running after the bound can no longer replace a receipt (WaitReportFence.commit); an
75
+ * appended event it already sent stays in the log as history of the wait, which it was.
76
+ */
77
+ export function orderedWaitReports(report) {
78
+ let chain = Promise.resolve();
79
+ let closed = false;
80
+ let committing = Promise.resolve();
81
+ const fence = {
82
+ get current() { return !closed; },
83
+ commit: async (replace) => {
84
+ if (closed)
85
+ return false;
86
+ // Started while open: `drained` waits for it, so it cannot land after the step's state.
87
+ const replaced = replace();
88
+ committing = replaced.catch(() => undefined);
89
+ await replaced;
90
+ return true;
91
+ },
92
+ };
93
+ return {
94
+ onWaiting: report ? decision => {
95
+ if (closed)
96
+ return;
97
+ chain = chain.then(async () => { if (!closed)
98
+ await report(decision, fence); }).catch(() => undefined);
99
+ } : undefined,
100
+ drained: async () => {
101
+ // Once closed nothing new runs or commits: a report still in flight was already given its bound.
102
+ if (closed)
103
+ return;
104
+ try {
105
+ await afterNotified(chain);
106
+ }
107
+ finally {
108
+ closed = true;
109
+ }
110
+ await committing;
111
+ },
112
+ };
113
+ }
58
114
  /**
59
115
  * Returns a step's token, unless part of its process tree could not be proven
60
116
  * gone: the token (and its cost) is then kept until the tree is.
@@ -28,7 +28,10 @@ export interface HostTestSlotInput {
28
28
  readonly queue: readonly HostTestSlotTicketRequest[];
29
29
  /** Every live token on the host; fenced and degraded ones still hold their slot. */
30
30
  readonly tokens: readonly HostLoadToken[];
31
+ /** The count in force: the configured count, or lower while other work needs the host. */
31
32
  readonly testSlots: number;
33
+ /** Why testSlots is below the configured count (host-load-capacity.ts); empty or absent when it is not. */
34
+ readonly testSlotsDetail?: string;
32
35
  readonly nowMs: number;
33
36
  readonly antiStarvationMs: number;
34
37
  }
@@ -48,13 +48,13 @@ export function decideHostTestSlot(input) {
48
48
  return { ...reserved, admitted, reason: "admitted_test_slot", detail: "The host test slot is free." };
49
49
  }
50
50
  const heldBy = holders.length > 0
51
- ? `held by ${holders.map(describeHolder).join("; ")}`
51
+ ? `held by ${holders.map(token => describeHolder(token, input.ticket.dispatchAttemptId)).join("; ")}`
52
52
  : "the steps ahead of this one take it first";
53
53
  return {
54
54
  ...reserved,
55
55
  admitted,
56
56
  reason: "host_test_slot",
57
- detail: `Waiting for the host test slot (${input.testSlots} at once): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
57
+ detail: `Waiting for the host test slot (${input.testSlots} at once${input.testSlotsDetail ? `, ${input.testSlotsDetail}` : ""}): ${heldBy}; ${ahead} step(s) ahead in the host queue.`,
58
58
  // Only a running, healthy holder is progress. With no holder the steps ahead are waiting too (for
59
59
  // the budget, say), and that wait must count as stalled, not reset the clock.
60
60
  progressing: holders.length > 0 && holders.every(healthyHolder),
@@ -64,13 +64,25 @@ export function decideHostTestSlot(input) {
64
64
  function healthyHolder(token) {
65
65
  return !token.degradedAt && !token.fencedAt && !token.retainedAt;
66
66
  }
67
- function describeHolder(token) {
67
+ /**
68
+ * Names the holder for the waiting step's agent: whose step it is and since when. A step
69
+ * label alone reads like the agent's own: an agent that saw "held by dotnet_api_component"
70
+ * took another session's live test run for its own finished one and gave up the wait.
71
+ */
72
+ function describeHolder(token, waiterAttemptId) {
68
73
  const attempt = token.dispatchAttemptId ? `, attempt ${token.dispatchAttemptId}` : "";
74
+ const whose = !token.dispatchAttemptId ? ""
75
+ : token.dispatchAttemptId === waiterAttemptId ? ", this session's own step" : ", another session's step";
76
+ const admittedAtMs = Date.parse(token.admittedAt);
77
+ const since = Number.isFinite(admittedAtMs)
78
+ ? ` since ${new Date(admittedAtMs).toISOString().replace(/\.\d{3}Z$/u, "Z")}`
79
+ : "";
69
80
  const state = token.degradedAt
70
- ? ", whose owner is gone; it is returned once its processes are stopped"
71
- : token.fencedAt ? ", which is past its lease"
72
- : token.retainedAt ? ", whose processes could not be proven stopped; it is returned at attempt teardown" : "";
73
- return `${token.label} (${token.stepClass}${attempt}${state})`;
81
+ ? `, held${since}; its owner is gone, and it is returned once its processes are stopped`
82
+ : token.fencedAt ? `, held${since} and past its lease`
83
+ : token.retainedAt ? `, held${since}; its processes could not be proven stopped, and it is returned at attempt teardown`
84
+ : `, still running${since}`;
85
+ return `${token.label} (${token.stepClass}${attempt}${whose}${state})`;
74
86
  }
75
87
  /** A ticket read back from the ledger; a malformed one is dropped, never trusted. */
76
88
  export function validHostTestSlotTicket(value) {
@@ -2,6 +2,7 @@ import type { BridgeServiceConfig } from "../bridge/bridge.types.js";
2
2
  import type { SessionEventSink } from "../session/session.base.js";
3
3
  import { type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
4
4
  import type { SandboxService, ValidatedSandboxContract } from "./sandbox.types.js";
5
+ export { selectSandboxInputRefs } from "./sandbox-input.js";
5
6
  import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
6
7
  import { type RuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
7
8
  export interface SandboxRuntime {
@@ -169,7 +170,6 @@ export declare function selectSandboxConfigRefs(executionPolicy: string, configu
169
170
  readonly refs: readonly string[];
170
171
  readonly approvedSha: string | null;
171
172
  };
172
- export declare function selectSandboxInputRefs(worktreeKey: string, baseBranch: string): readonly string[];
173
173
  export declare function sandboxTimeLimits(environment?: NodeJS.ProcessEnv): {
174
174
  readonly hardWallMs: number;
175
175
  readonly idleMs: number;
@@ -308,4 +308,3 @@ export declare function classifySandboxResourceFailure(value: string): {
308
308
  readonly code: string;
309
309
  readonly message: string;
310
310
  } | null;
311
- export {};
@@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url";
5
5
  import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
6
6
  import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
7
7
  import { requireSandboxProcess, runSandboxProcess } from "./process.js";
8
- import { advanceCheckedOutBranch } from "./managed-branch.js";
8
+ import { advanceCheckedOutBranch, resolveReviewDiffBase, resolveSandboxInputCommit, reviewOnlySandboxOutput, sandboxPublicationAllowed, withReviewDiffBase } from "./sandbox-input.js";
9
+ export { selectSandboxInputRefs } from "./sandbox-input.js";
9
10
  import { createLeaseUpdate } from "./lease-watchdog.js";
10
11
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
11
12
  import { SandboxEventBudget } from "./event-budget.js";
@@ -111,7 +112,7 @@ export class DockerSandboxRuntime {
111
112
  const securityOptions = resolveSandboxSecurityOptions(dispatch.sandbox.executionPolicy);
112
113
  const builtImage = await this.buildImage(prepared.contextRoot, prepared.contextDigest, dispatch.repo.name, validated, upstreamImages, dispatch.sandbox.executionPolicy, sink, runtimeSignal);
113
114
  const imageDigest = builtImage.imageDigest;
114
- const runtimeDispatch = withSandboxMetadata(dispatch, prepared.inputCommitSha, prepared.configCommitSha, validated.digest, imageDigest);
115
+ const runtimeDispatch = withReviewDiffBase(withSandboxMetadata(dispatch, prepared.inputCommitSha, prepared.configCommitSha, validated.digest, imageDigest), prepared.reviewDiffBase);
115
116
  const providerAuthAdapter = sandboxProviderAuthAdapterFor(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
116
117
  const providerAuthUnavailable = sandboxProviderAuthUnavailableMessage(runtimeDispatch.execution.provider, runtimeDispatch.execution.authKind);
117
118
  if (providerAuthUnavailable) {
@@ -276,7 +277,7 @@ export class DockerSandboxRuntime {
276
277
  await this.docker(["cp", `${containerId}:/control/output/.`, path.join(attemptRoot, "output")], 60_000);
277
278
  let output;
278
279
  try {
279
- output = await validateOutput(attemptRoot, runtimeDispatch);
280
+ output = reviewOnlySandboxOutput(runtimeDispatch, await validateOutput(attemptRoot, runtimeDispatch));
280
281
  }
281
282
  catch (error) {
282
283
  if (start.exitCode !== 0 && isMissingSandboxManifest(error)) {
@@ -285,7 +286,7 @@ export class DockerSandboxRuntime {
285
286
  throw error;
286
287
  }
287
288
  await git.importResult(runtimeDispatch, output, () => assertSandboxImportCurrent(active, this.active.get(active.dispatchAttemptId), controller.signal));
288
- if (runtimeDispatch.sandbox.publicationMode === "bridge_push") {
289
+ if (sandboxPublicationAllowed(runtimeDispatch)) {
289
290
  const handle = runtimeDispatch.sandbox.publishGrantHandle;
290
291
  if (!handle || !output.manifest.resultCommitSha || !this.publicationGrantRedeemer) {
291
292
  throw trustedSandboxFailure("sandbox_output_publish_forbidden", "bridge publication grant redemption is unavailable.");
@@ -1166,7 +1167,7 @@ class HostGit {
1166
1167
  async prepareLocked(dispatch, attemptRoot) {
1167
1168
  const baseBranch = dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch;
1168
1169
  await this.git(["fetch", "--prune", "origin"], 5 * 60_000).catch(() => null);
1169
- const inputCommitSha = await this.resolveFirst([...selectSandboxInputRefs(dispatch.lease.worktreeKey, baseBranch)]);
1170
+ const [inputCommitSha, reviewDiffBase] = [await resolveSandboxInputCommit(dispatch, baseBranch, (refs) => this.resolveFirst(refs), (args) => this.git(args, 5 * 60_000)), await resolveReviewDiffBase(dispatch, async (args) => (await this.git(args, 5 * 60_000)).stdout)];
1170
1171
  const configSelection = selectSandboxConfigRefs(dispatch.sandbox.executionPolicy, dispatch.sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
1171
1172
  const configCommitSha = await this.resolveFirst([...configSelection.refs]);
1172
1173
  const approvedConfigSha = configSelection.approvedSha;
@@ -1190,7 +1191,7 @@ class HostGit {
1190
1191
  await fs.mkdir(contextRoot, { recursive: true });
1191
1192
  await requireSandboxProcess({ command: "tar", args: ["-xf", contextArchive, "-C", contextRoot], timeoutMs: 5 * 60_000, maxOutputBytes: 1024 * 1024 });
1192
1193
  const contextDigest = createHash("sha256").update(await fs.readFile(contextArchive)).digest("hex");
1193
- return { inputCommitSha, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1194
+ return { inputCommitSha, reviewDiffBase, configCommitSha, contractSource, dockerfile, bundlePath, contextRoot, contextDigest };
1194
1195
  }
1195
1196
  async importResult(dispatch, output, assertCurrent) {
1196
1197
  await this.coordinator.withLock(this.repoPath, () => this.importResultLocked(dispatch, output, assertCurrent));
@@ -1421,13 +1422,6 @@ export function selectSandboxConfigRefs(executionPolicy, configuredSha, defaultB
1421
1422
  ? { refs: [approvedSha], approvedSha }
1422
1423
  : { refs: [`refs/heads/${defaultBranch}`, `refs/remotes/origin/${defaultBranch}`], approvedSha: null };
1423
1424
  }
1424
- export function selectSandboxInputRefs(worktreeKey, baseBranch) {
1425
- return [
1426
- `refs/heads/${worktreeKey}`,
1427
- `refs/heads/${baseBranch}`,
1428
- `refs/remotes/origin/${baseBranch}`
1429
- ];
1430
- }
1431
1425
  export function sandboxTimeLimits(environment = process.env) {
1432
1426
  const hardWallSeconds = boundedInteger(environment.FORGE_SANDBOX_HARD_WALL_SECONDS, 8 * 60 * 60, 60, 8 * 60 * 60);
1433
1427
  const idleSeconds = boundedInteger(environment.FORGE_SANDBOX_IDLE_SECONDS, 10 * 60, 60, hardWallSeconds);