@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.93045aceba29

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 (72) hide show
  1. package/README.md +33 -0
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +70 -1
  4. package/dist/bridge/bridge.service.js +279 -5
  5. package/dist/bridge/bridge.types.d.ts +11 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/cleanup/cleanup.service.d.ts +9 -0
  9. package/dist/cleanup/cleanup.service.js +72 -109
  10. package/dist/cleanup/cleanup.types.d.ts +4 -0
  11. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  12. package/dist/cleanup/forge-owned-paths.js +53 -0
  13. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  14. package/dist/cleanup/host-runtime-ledger.js +109 -0
  15. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  16. package/dist/cleanup/managed-branch-sweep.js +111 -0
  17. package/dist/cli/cli.help.js +18 -0
  18. package/dist/cli/cli.service.d.ts +16 -0
  19. package/dist/cli/cli.service.js +139 -15
  20. package/dist/cli/local-config.d.ts +4 -0
  21. package/dist/cli/local-config.js +26 -4
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/host-load-admission.d.ts +9 -1
  24. package/dist/runtime/host-load-admission.js +19 -4
  25. package/dist/runtime/host-load-child-environment.js +3 -1
  26. package/dist/runtime/host-load-governor-config.d.ts +9 -0
  27. package/dist/runtime/host-load-governor-config.js +30 -0
  28. package/dist/runtime/host-load-governor.d.ts +2 -0
  29. package/dist/runtime/host-load-governor.js +23 -1
  30. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  31. package/dist/runtime/host-load-runtime-settings.js +78 -0
  32. package/dist/runtime/host-runtime-lease.d.ts +57 -1
  33. package/dist/runtime/host-runtime-lease.js +196 -6
  34. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  35. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  36. package/dist/runtime/runner-settings.d.ts +100 -0
  37. package/dist/runtime/runner-settings.js +214 -0
  38. package/dist/session/managed-attempt-tools.d.ts +2 -0
  39. package/dist/session/managed-attempt-tools.js +36 -13
  40. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  41. package/dist/session/mcp-argument-coercion.js +121 -0
  42. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  43. package/dist/session/phase-completion.artifacts.js +94 -25
  44. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  45. package/dist/session/phase-completion.command-validation.js +77 -0
  46. package/dist/session/phase-completion.d.ts +2 -0
  47. package/dist/session/phase-completion.helpers.js +13 -12
  48. package/dist/session/phase-completion.js +4 -0
  49. package/dist/session/phase-completion.prompts.js +6 -1
  50. package/dist/session/phase-completion.runtime.d.ts +4 -2
  51. package/dist/session/phase-completion.runtime.js +35 -13
  52. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  53. package/dist/session/phase-completion.schema-parts.js +188 -0
  54. package/dist/session/phase-completion.schemas.d.ts +3 -3
  55. package/dist/session/phase-completion.schemas.js +184 -209
  56. package/dist/session/phase-completion.validation.d.ts +2 -3
  57. package/dist/session/phase-completion.validation.js +46 -92
  58. package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
  59. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  60. package/dist/session/provider-cli/provider-cli.service.js +103 -3
  61. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  62. package/dist/session/session.base.d.ts +6 -1
  63. package/dist/session/session.service.d.ts +7 -2
  64. package/dist/session/session.service.js +100 -2
  65. package/dist/session/session.types.js +2 -2
  66. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  67. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/worktree/worktree.service.d.ts +5 -1
  71. package/dist/worktree/worktree.service.js +29 -1
  72. package/package.json +2 -2
@@ -469,7 +469,7 @@ function unvalidatedFailureFactsForCode(code, source) {
469
469
  if (code === "bridge.unavailable") {
470
470
  return facts(code, "transport", "offer", source, "retryable", "retry_dispatch");
471
471
  }
472
- if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet"].includes(code)) {
472
+ if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet", "runner_yielding", "runner_settings_pending", "runner_settings_apply_failed", "runner_tier_light", "runner_project_not_allowed"].includes(code)) {
473
473
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
474
474
  }
475
475
  if (["bridge.lease_retry_exhausted", "bridge.capacity_wait_exhausted"].includes(code)) {
@@ -496,7 +496,7 @@ function unvalidatedFailureFactsForCode(code, source) {
496
496
  if (code === "provider_configuration_invalid") {
497
497
  return facts(code, "provider", "prepare", source, "non_retryable", "fix_environment");
498
498
  }
499
- if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
499
+ if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_contract_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
500
500
  return facts(code, "resource", "prepare", source, "retryable", "retry_dispatch");
501
501
  }
502
502
  if (code === "host_runtime_project_start_failed") {
@@ -0,0 +1,32 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ /**
3
+ * What the attempt's host runtime stack was built and launched from. When the
4
+ * workspace no longer matches, the running API binary and dev server are stale:
5
+ * an uncommitted edit or an in-progress `merge --no-commit` changes the source
6
+ * without moving HEAD.
7
+ */
8
+ export interface WorkspaceRuntimeFingerprint {
9
+ readonly headSha: string;
10
+ /** Contents of MERGE_HEAD while a merge is in progress, else null. */
11
+ readonly mergeHead: string | null;
12
+ /** sha256 of `git diff HEAD --binary` (staged and unstaged changes to tracked files, mode changes included). */
13
+ readonly diffDigest: string;
14
+ /**
15
+ * sha256 over untracked, non-ignored file names, their executable bit, and their contents (or
16
+ * size and mtime for large files).
17
+ */
18
+ readonly untrackedDigest: string;
19
+ /**
20
+ * sha256 over the runtime contract as loaded now and the files its launch commands name. Git's
21
+ * views above skip ignored files, and a project may ignore its contract or a launch script; a
22
+ * change there alters what the stack runs without changing anything git reports.
23
+ */
24
+ readonly runtimeInputsDigest: string;
25
+ /** One digest over every field above. */
26
+ readonly digest: string;
27
+ }
28
+ export type WorkspaceRuntimeFingerprintReader = (worktreePath: string) => Promise<WorkspaceRuntimeFingerprint>;
29
+ export declare function readWorkspaceRuntimeFingerprint(worktreePath: string, git?: Pick<GitClient, "run">): Promise<WorkspaceRuntimeFingerprint>;
30
+ export declare function sameWorkspaceRuntimeFingerprint(left: WorkspaceRuntimeFingerprint | null, right: WorkspaceRuntimeFingerprint | null): boolean;
31
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
32
+ export declare function workspaceRuntimeFingerprintChanges(previous: WorkspaceRuntimeFingerprint | null, current: WorkspaceRuntimeFingerprint): readonly string[];
@@ -0,0 +1,138 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { GitClient } from "../shared/git/git.js";
5
+ import { loadHostRuntimeContract } from "../runtime/host-runtime-contract.js";
6
+ import { hostRuntimeContractFingerprint } from "../runtime/host-runtime-promotion.js";
7
+ import { isRuntimeOnlyPath } from "./publishable-worktree-changes.js";
8
+ /** Untracked files up to this size are hashed by content; larger ones by size and mtime. */
9
+ const untrackedContentHashLimitBytes = 1024 * 1024;
10
+ /**
11
+ * Forge's own runtime output never changes what the application runs, and Forge
12
+ * rewrites some of it (readiness manifests, completion artifacts) between passes.
13
+ */
14
+ const runtimeOnlyPathspecs = [
15
+ ":(exclude).local",
16
+ ":(exclude).forge/work-items",
17
+ ":(exclude).forge/stories",
18
+ ];
19
+ export async function readWorkspaceRuntimeFingerprint(worktreePath, git = new GitClient()) {
20
+ const headSha = (await git.run(worktreePath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim().toLowerCase();
21
+ const mergeHead = await readMergeHead(git, worktreePath);
22
+ // A mode change (chmod +x on a launch script) changes what runs. The repository may set
23
+ // core.fileMode=false, which would drop it from the diff, so this read always records modes.
24
+ const diff = await git.run(worktreePath, ["-c", "core.fileMode=true", "diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv", "--", ".", ...runtimeOnlyPathspecs]);
25
+ const diffDigest = sha256(diff);
26
+ const untracked = (await git.run(worktreePath, [
27
+ "ls-files", "--others", "--exclude-standard", "-z", "--", ".", ...runtimeOnlyPathspecs,
28
+ ]))
29
+ .split("\0")
30
+ .filter(entry => entry.length > 0 && !isRuntimeOnlyPath(entry))
31
+ .sort((left, right) => left.localeCompare(right));
32
+ const untrackedHash = createHash("sha256");
33
+ for (const relative of untracked) {
34
+ untrackedHash.update(relative).update("\0");
35
+ const absolute = path.join(worktreePath, relative);
36
+ const stat = await fs.lstat(absolute).catch(() => null);
37
+ if (!stat) {
38
+ untrackedHash.update("missing\0");
39
+ continue;
40
+ }
41
+ // Like git, record the executable bit: chmod changes what runs without touching content or mtime.
42
+ untrackedHash.update(stat.isFile() && (stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
43
+ if (stat.isFile() && stat.size <= untrackedContentHashLimitBytes) {
44
+ const content = await fs.readFile(absolute).catch(() => null);
45
+ untrackedHash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
46
+ }
47
+ else {
48
+ untrackedHash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
49
+ }
50
+ }
51
+ const untrackedDigest = `sha256:${untrackedHash.digest("hex")}`;
52
+ const runtimeInputsDigest = await readRuntimeInputsDigest(worktreePath);
53
+ const digest = sha256(JSON.stringify({ headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest }));
54
+ return { headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest, digest };
55
+ }
56
+ export function sameWorkspaceRuntimeFingerprint(left, right) {
57
+ return left !== null && right !== null && left.digest === right.digest;
58
+ }
59
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
60
+ export function workspaceRuntimeFingerprintChanges(previous, current) {
61
+ if (!previous)
62
+ return ["unrecorded"];
63
+ const changes = [];
64
+ if (previous.headSha !== current.headSha)
65
+ changes.push("head");
66
+ if (previous.mergeHead !== current.mergeHead)
67
+ changes.push("merge_head");
68
+ if (previous.diffDigest !== current.diffDigest)
69
+ changes.push("tracked_changes");
70
+ if (previous.untrackedDigest !== current.untrackedDigest)
71
+ changes.push("untracked_files");
72
+ if (previous.runtimeInputsDigest !== current.runtimeInputsDigest)
73
+ changes.push("runtime_inputs");
74
+ return changes;
75
+ }
76
+ /**
77
+ * The loaded runtime contract (project file or derived) and each regular file inside the worktree
78
+ * that a configured launch names as its command or an argument, by executable bit and content.
79
+ * Ignored or not: these are exactly what the stack was launched from. Nothing else ignored is read.
80
+ */
81
+ async function readRuntimeInputsDigest(worktreePath) {
82
+ const hash = createHash("sha256");
83
+ let contract;
84
+ try {
85
+ contract = await loadHostRuntimeContract(worktreePath);
86
+ }
87
+ catch (error) {
88
+ // An unloadable contract is a state of its own; the restart reports why it cannot load.
89
+ const message = error instanceof Error ? error.message : String(error);
90
+ return sha256(`unloadable:${message.split(":", 1)[0]}`);
91
+ }
92
+ hash.update(`contract:${hostRuntimeContractFingerprint(contract)}\0`);
93
+ const root = await fs.realpath(worktreePath);
94
+ const named = new Set();
95
+ for (const port of contract.contract.runtime.ports) {
96
+ if (!port.launch)
97
+ continue;
98
+ const workingDirectory = path.resolve(root, port.launch.workingDirectory);
99
+ for (const candidate of [port.launch.command, ...port.launch.args]) {
100
+ if (!candidate || candidate.startsWith("-"))
101
+ continue;
102
+ const absolute = path.resolve(workingDirectory, candidate);
103
+ const relative = path.relative(root, absolute);
104
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative))
105
+ continue;
106
+ named.add(relative);
107
+ }
108
+ }
109
+ for (const relative of [...named].sort((left, right) => left.localeCompare(right))) {
110
+ const stat = await fs.stat(path.join(root, relative)).catch(() => null);
111
+ if (!stat?.isFile())
112
+ continue;
113
+ hash.update(relative).update("\0").update((stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
114
+ if (stat.size <= untrackedContentHashLimitBytes) {
115
+ const content = await fs.readFile(path.join(root, relative)).catch(() => null);
116
+ hash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
117
+ }
118
+ else {
119
+ hash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
120
+ }
121
+ }
122
+ return `sha256:${hash.digest("hex")}`;
123
+ }
124
+ async function readMergeHead(git, worktreePath) {
125
+ const relative = (await git.run(worktreePath, ["rev-parse", "--git-path", "MERGE_HEAD"])).trim();
126
+ if (!relative)
127
+ return null;
128
+ const mergeHeadPath = path.resolve(worktreePath, relative);
129
+ const content = await fs.readFile(mergeHeadPath, "utf8").catch((error) => {
130
+ if (error.code === "ENOENT")
131
+ return null;
132
+ throw error;
133
+ });
134
+ return content === null ? null : content.trim().toLowerCase();
135
+ }
136
+ function sha256(value) {
137
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
138
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.4-dev.8901ba056f68";
1
+ export declare const forgeBridgeVersion = "0.1.4-dev.93045aceba29";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.4-dev.8901ba056f68";
1
+ export const forgeBridgeVersion = "0.1.4-dev.93045aceba29";
@@ -7,9 +7,13 @@ export declare class GitWorktreeService implements WorktreeService {
7
7
  private readonly coordinator;
8
8
  /** Gates dependency install fallbacks; inert unless the governor is on. */
9
9
  private readonly hostLoadGate?;
10
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
11
+ private readonly leaseStateRoot;
10
12
  constructor(git?: GitClient, coordinator?: WorktreeLifecycleCoordinator,
11
13
  /** Gates dependency install fallbacks; inert unless the governor is on. */
12
- hostLoadGate?: HostLoadStepGate | undefined);
14
+ hostLoadGate?: HostLoadStepGate | undefined,
15
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
16
+ leaseStateRoot?: string);
13
17
  prepare(request: WorktreePrepareRequest): Promise<WorktreeHandle>;
14
18
  private trackedForgePaths;
15
19
  private registeredManagedWorktreePath;
@@ -3,22 +3,30 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
5
5
  import { GitClient } from "../shared/git/git.js";
6
+ import { liveLeaseBranches, readHostRuntimeLeases } from "../cleanup/host-runtime-ledger.js";
7
+ import { deleteBranchIfUnused, isRuntimeReadinessBranch, sweepManagedBranches } from "../cleanup/managed-branch-sweep.js";
6
8
  import { ensureDirectory, isSubPath, resolveExistingDirectoryPath, safeSegment } from "../shared/path/path.js";
7
9
  import { filterArtifactsForLane, injectWorktreeArtifacts } from "./artifact-injector.js";
8
10
  import { hydratePriorPhaseArtifacts } from "./prior-phase-artifact-hydrator.js";
9
11
  import { materializeStoryQaReferences } from "./story-qa-reference-hydrator.js";
10
12
  import { warmWorktreeDependencies } from "./dependency-warmer.js";
11
13
  import { defaultWorktreeCoordinatorStateRoot, managedRepoRoot, resolveManagedWorktreeRoot, } from "./worktree-paths.js";
14
+ // Bounds the branch sweep that runs after each release, so one release never holds the repository lock long.
15
+ const releaseSweepLimit = 25;
12
16
  export class GitWorktreeService {
13
17
  git;
14
18
  coordinator;
15
19
  hostLoadGate;
20
+ leaseStateRoot;
16
21
  constructor(git = new GitClient(), coordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
17
22
  /** Gates dependency install fallbacks; inert unless the governor is on. */
18
- hostLoadGate) {
23
+ hostLoadGate,
24
+ /** Holds the host runtime lease ledger; branches of live leases are never swept on release. */
25
+ leaseStateRoot = defaultWorktreeCoordinatorStateRoot()) {
19
26
  this.git = git;
20
27
  this.coordinator = coordinator;
21
28
  this.hostLoadGate = hostLoadGate;
29
+ this.leaseStateRoot = leaseStateRoot;
22
30
  }
23
31
  async prepare(request) {
24
32
  const allowedRoot = await ensureDirectory(request.allowedRepoRoot);
@@ -176,6 +184,26 @@ export class GitWorktreeService {
176
184
  // directory is fully materialized (or after an external cleanup removes it).
177
185
  // Always prune so those missing-directory registrations do not accumulate.
178
186
  await this.git.run(handle.repoPath, ["worktree", "prune", "--expire", "now"]).catch(() => undefined);
187
+ // A readiness probe's branch goes with its worktree. Other Forge branches on this device
188
+ // whose work is already merged into the base go too; branches with unmerged work stay.
189
+ // A lease can be live while its worktree is briefly missing, so its branch is protected
190
+ // even when no worktree has it checked out. If the ledger can't be read, sweep nothing.
191
+ const protectedBranches = await readHostRuntimeLeases(this.leaseStateRoot)
192
+ .then(liveLeaseBranches)
193
+ .catch(() => null);
194
+ if (!protectedBranches)
195
+ return;
196
+ let budget = releaseSweepLimit;
197
+ if (isRuntimeReadinessBranch(handle.branchName) && !protectedBranches.has(handle.branchName)
198
+ && await deleteBranchIfUnused(this.git, handle.repoPath, handle.branchName)) {
199
+ budget -= 1;
200
+ }
201
+ await sweepManagedBranches(this.git, handle.repoPath, {
202
+ baseBranch: handle.baseBranch,
203
+ includeMergedWorkBranches: true,
204
+ protectedBranches,
205
+ limit: budget,
206
+ }).catch(() => undefined);
179
207
  });
180
208
  }
181
209
  async restoreOrphanedWorktree(input) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.4-dev.8901ba056f68",
3
+ "version": "0.1.4-dev.93045aceba29",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -43,7 +43,7 @@
43
43
  "test:residue": "node scripts/run-owned-residue-gate.mjs",
44
44
  "test:watch": "vitest",
45
45
  "smoke:package": "tsc -p tsconfig.json && node scripts/smoke-package.mjs",
46
- "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\""
46
+ "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\" && node ../../scripts/class-design/check-eslint-ratchet.mjs bridge"
47
47
  },
48
48
  "dependencies": {
49
49
  "@microsoft/signalr": "^8.0.17",