@loucompanion/forge-bridge 0.1.1-dev.9acab970e5d1 → 0.1.1-dev.ac656b52f9c6

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.
@@ -6,6 +6,11 @@ export interface ProviderCliRunContext {
6
6
  readonly signal?: AbortSignal;
7
7
  emit(event: RunnerDispatchEvent): Promise<void>;
8
8
  }
9
+ export interface ProviderCliDraftContext {
10
+ readonly dispatch: RunOnceDispatchPacket;
11
+ readonly signal?: AbortSignal;
12
+ emit(event: RunnerDispatchEvent): Promise<void>;
13
+ }
9
14
  export interface ProviderCliRunResult {
10
15
  readonly summary: string;
11
16
  readonly spec?: RunnerDispatchSpec | null;
@@ -27,17 +27,39 @@ export class BridgeSessionService {
27
27
  content: "forge-bridge accepted run-once dispatch.",
28
28
  eventType: "dispatch_accepted"
29
29
  });
30
+ if (dispatch.draft) {
31
+ const run = await this.providerCli.runDraft({
32
+ dispatch,
33
+ emit,
34
+ signal
35
+ });
36
+ throwIfAborted(signal);
37
+ return redactSecrets({
38
+ schemaVersion: 1,
39
+ exitCode: 0,
40
+ summary: run.summary,
41
+ events,
42
+ spec: run.spec ?? null,
43
+ artifact: run.artifact ?? null,
44
+ artifacts: run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : []
45
+ }, redactionSecrets);
46
+ }
30
47
  const worktree = await this.worktrees.prepare({
31
48
  repo: dispatch.repo,
32
49
  workItem: dispatch.workItem,
33
50
  baseBranch: dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase,
51
+ worktreeKey: dispatch.lease.worktreeKey,
52
+ ownerType: dispatch.cycleRun.ownerType ?? dispatch.lease.ownerType ?? null,
53
+ ownerId: dispatch.cycleRun.ownerId ?? dispatch.lease.ownerId ?? null,
34
54
  lane: dispatch.execution.lane,
35
55
  phase: dispatch.cycleRun.phase,
36
56
  allowedRepoRoot: dispatch.serverLocal.repoRoot,
37
57
  cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
38
58
  artifacts: dispatch.artifacts,
59
+ qaRework: dispatch.qaRework,
39
60
  warmPathOverrides: dispatch.warmPathOverrides
40
61
  });
62
+ const providerDispatch = withPreparedQaReworkPacket(dispatch, worktree.qaReworkPacketPath);
41
63
  throwIfAborted(signal);
42
64
  await emit({
43
65
  role: "runner",
@@ -53,18 +75,21 @@ export class BridgeSessionService {
53
75
  const lane = dispatch.execution.lane.toLowerCase();
54
76
  const role = dispatch.execution.role.toLowerCase();
55
77
  const isQa = role === "qa" || lane === "qa";
78
+ const isArchitect = role === "architect" || lane === "architect" || dispatch.cycleRun.kind.toLowerCase() === "architect";
56
79
  const isConflictResolve = role === "conflict_resolve" || lane === "conflict_resolve";
57
80
  const context = {
58
- dispatch,
81
+ dispatch: providerDispatch,
59
82
  worktree,
60
83
  emit,
61
84
  signal
62
85
  };
63
86
  const run = isQa
64
87
  ? await this.providerCli.runQa(context)
65
- : isConflictResolve
66
- ? await this.providerCli.runConflictResolve(context)
67
- : await this.providerCli.runImplementation(context);
88
+ : isArchitect
89
+ ? await this.providerCli.runArchitect(context)
90
+ : isConflictResolve
91
+ ? await this.providerCli.runConflictResolve(context)
92
+ : await this.providerCli.runImplementation(context);
68
93
  throwIfAborted(signal);
69
94
  const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
70
95
  return redactSecrets({
@@ -109,6 +134,18 @@ function validateApiKeySecretGrant(dispatch) {
109
134
  function exactSecrets(dispatch) {
110
135
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
111
136
  }
137
+ function withPreparedQaReworkPacket(dispatch, packetPath) {
138
+ if (!dispatch.qaRework || !packetPath) {
139
+ return dispatch;
140
+ }
141
+ return {
142
+ ...dispatch,
143
+ qaRework: {
144
+ ...dispatch.qaRework,
145
+ packetPath
146
+ }
147
+ };
148
+ }
112
149
  async function emitDependencyWarmEvents(warm, emit) {
113
150
  if (warm.linked.length > 0) {
114
151
  await emit({
@@ -14,6 +14,15 @@ export interface RunOnceDispatchPacket {
14
14
  readonly warmPathOverrides?: readonly string[];
15
15
  readonly qaBrowser?: DispatchQaBrowserContext | null;
16
16
  readonly qaRework?: DispatchQaReworkContext | null;
17
+ readonly architectRevision?: DispatchArchitectRevisionContext | null;
18
+ readonly storyDevelop?: DispatchStoryDevelopContext | null;
19
+ readonly storyQa?: DispatchStoryQaContext | null;
20
+ readonly draft?: DispatchDraftPrompt | null;
21
+ }
22
+ export interface DispatchDraftPrompt {
23
+ readonly kind: string;
24
+ readonly systemPrompt: string;
25
+ readonly userPrompt: string;
17
26
  }
18
27
  export interface DispatchQaBrowserContext {
19
28
  readonly required: boolean;
@@ -37,6 +46,67 @@ export interface DispatchQaReworkContext {
37
46
  readonly findingIds: readonly string[];
38
47
  readonly findings: readonly Record<string, unknown>[];
39
48
  }
49
+ export interface DispatchArchitectRevisionContext {
50
+ readonly priorPlanId: string;
51
+ readonly priorContentHash: string;
52
+ readonly feedback: string;
53
+ }
54
+ export interface DispatchStoryDevelopContext {
55
+ readonly storyWorkItemId: string;
56
+ readonly planId: string;
57
+ readonly planContentHash: string;
58
+ readonly architectTaskId: string;
59
+ readonly phaseId: string;
60
+ readonly dependencyWorkItemIds: readonly string[];
61
+ }
62
+ export interface DispatchStoryQaContext {
63
+ readonly storyWorkItemId: string;
64
+ readonly planId: string;
65
+ readonly planContentHash: string;
66
+ readonly worktreeKey: string;
67
+ readonly branch: string;
68
+ readonly implementationPlanJson?: string | null;
69
+ readonly qaPlanJson?: string | null;
70
+ readonly finalQaChecks: readonly string[];
71
+ readonly childTasks: readonly DispatchStoryQaChildTaskContext[];
72
+ readonly dependencies: readonly DispatchStoryQaDependencyContext[];
73
+ }
74
+ export interface DispatchStoryQaChildTaskContext {
75
+ readonly workItemId: string;
76
+ readonly title: string;
77
+ readonly architectTaskId: string;
78
+ readonly phaseId: string;
79
+ readonly phaseOrder: number;
80
+ readonly dependencyWorkItemIds: readonly string[];
81
+ readonly spec?: DispatchStoryQaChildSpecContext | null;
82
+ readonly implementationArtifact?: DispatchStoryQaArtifactContext | null;
83
+ readonly selfReviewArtifact?: DispatchStoryQaArtifactContext | null;
84
+ readonly validationArtifact?: DispatchStoryQaArtifactContext | null;
85
+ readonly qaArtifact?: DispatchStoryQaArtifactContext | null;
86
+ }
87
+ export interface DispatchStoryQaChildSpecContext {
88
+ readonly version: number;
89
+ readonly status: string;
90
+ readonly path: string;
91
+ readonly contentHash: string;
92
+ readonly body: string;
93
+ }
94
+ export interface DispatchStoryQaArtifactContext {
95
+ readonly artifactId: string;
96
+ readonly cycleRunId: string;
97
+ readonly phase: string;
98
+ readonly status: string;
99
+ readonly producedAt: string;
100
+ readonly path?: string | null;
101
+ readonly verdictJson?: string | null;
102
+ readonly evidenceJson?: string | null;
103
+ readonly findingsJson?: string | null;
104
+ readonly report?: string | null;
105
+ }
106
+ export interface DispatchStoryQaDependencyContext {
107
+ readonly fromWorkItemId: string;
108
+ readonly toWorkItemId: string;
109
+ }
40
110
  export interface DispatchPullRequestContext {
41
111
  readonly number: number;
42
112
  readonly provider: string;
@@ -151,6 +221,11 @@ export interface RunnerDispatchArtifact {
151
221
  readonly repoPath: string;
152
222
  readonly path: string;
153
223
  readonly verdictJson: string;
224
+ readonly planJson?: string | null;
225
+ readonly evidenceJson?: string | null;
226
+ readonly findingsJson?: string | null;
227
+ readonly implementationPlanJson?: string | null;
228
+ readonly qaPlanJson?: string | null;
154
229
  readonly report: string;
155
230
  readonly producedBy: string;
156
231
  readonly status: string;
@@ -20,7 +20,11 @@ export function parseRunOnceDispatchPacket(value) {
20
20
  artifacts: parseArtifacts(packet.artifacts),
21
21
  warmPathOverrides: parseWarmPathOverrides(packet.warmPathOverrides),
22
22
  qaBrowser: parseQaBrowser(packet.qaBrowser),
23
- qaRework: parseQaRework(packet.qaRework)
23
+ qaRework: parseQaRework(packet.qaRework),
24
+ architectRevision: parseArchitectRevision(packet.architectRevision),
25
+ storyDevelop: parseStoryDevelop(packet.storyDevelop),
26
+ storyQa: parseStoryQa(packet.storyQa),
27
+ draft: parseDraftPrompt(packet.draft)
24
28
  };
25
29
  }
26
30
  export function failureResult(summary, events = []) {
@@ -106,6 +110,17 @@ function parseExecution(value) {
106
110
  runnerRepoLocalPath: optionalString(execution, "runnerRepoLocalPath")
107
111
  };
108
112
  }
113
+ function parseDraftPrompt(value) {
114
+ if (value === undefined || value === null) {
115
+ return null;
116
+ }
117
+ const draft = asObject(value, "draft");
118
+ return {
119
+ kind: requiredString(draft, "kind"),
120
+ systemPrompt: requiredString(draft, "systemPrompt"),
121
+ userPrompt: requiredString(draft, "userPrompt")
122
+ };
123
+ }
109
124
  function parseApiKeySecretGrant(value) {
110
125
  if (value === undefined || value === null) {
111
126
  return null;
@@ -234,6 +249,133 @@ function parseQaRework(value) {
234
249
  findings: findingsValue.map((entry, index) => asObject(entry, `qaRework.findings[${index}]`))
235
250
  };
236
251
  }
252
+ function parseArchitectRevision(value) {
253
+ if (value === undefined || value === null) {
254
+ return null;
255
+ }
256
+ const revision = asObject(value, "architectRevision");
257
+ return {
258
+ priorPlanId: requiredString(revision, "priorPlanId"),
259
+ priorContentHash: requiredString(revision, "priorContentHash"),
260
+ feedback: requiredString(revision, "feedback")
261
+ };
262
+ }
263
+ function parseStoryDevelop(value) {
264
+ if (value === undefined || value === null) {
265
+ return null;
266
+ }
267
+ const storyDevelop = asObject(value, "storyDevelop");
268
+ const dependencyWorkItemIds = storyDevelop.dependencyWorkItemIds;
269
+ if (!Array.isArray(dependencyWorkItemIds)) {
270
+ throw new Error("storyDevelop.dependencyWorkItemIds must be an array.");
271
+ }
272
+ return {
273
+ storyWorkItemId: requiredString(storyDevelop, "storyWorkItemId"),
274
+ planId: requiredString(storyDevelop, "planId"),
275
+ planContentHash: requiredString(storyDevelop, "planContentHash"),
276
+ architectTaskId: requiredString(storyDevelop, "architectTaskId"),
277
+ phaseId: requiredString(storyDevelop, "phaseId"),
278
+ dependencyWorkItemIds: dependencyWorkItemIds.map((entry, index) => {
279
+ if (typeof entry !== "string" || entry.trim().length === 0) {
280
+ throw new Error(`storyDevelop.dependencyWorkItemIds[${index}] must be a non-empty string.`);
281
+ }
282
+ return entry.trim();
283
+ })
284
+ };
285
+ }
286
+ function parseStoryQa(value) {
287
+ if (value === undefined || value === null) {
288
+ return null;
289
+ }
290
+ const storyQa = asObject(value, "storyQa");
291
+ return {
292
+ storyWorkItemId: requiredString(storyQa, "storyWorkItemId"),
293
+ planId: requiredString(storyQa, "planId"),
294
+ planContentHash: requiredString(storyQa, "planContentHash"),
295
+ worktreeKey: requiredString(storyQa, "worktreeKey"),
296
+ branch: requiredString(storyQa, "branch"),
297
+ implementationPlanJson: optionalString(storyQa, "implementationPlanJson"),
298
+ qaPlanJson: optionalString(storyQa, "qaPlanJson"),
299
+ finalQaChecks: parseStringArray(storyQa.finalQaChecks, "storyQa.finalQaChecks"),
300
+ childTasks: parseStoryQaChildTasks(storyQa.childTasks),
301
+ dependencies: parseStoryQaDependencies(storyQa.dependencies)
302
+ };
303
+ }
304
+ function parseStoryQaChildTasks(value) {
305
+ if (!Array.isArray(value)) {
306
+ throw new Error("storyQa.childTasks must be an array.");
307
+ }
308
+ return value.map((entry, index) => {
309
+ const child = asObject(entry, `storyQa.childTasks[${index}]`);
310
+ return {
311
+ workItemId: requiredString(child, "workItemId"),
312
+ title: requiredString(child, "title"),
313
+ architectTaskId: requiredString(child, "architectTaskId"),
314
+ phaseId: requiredString(child, "phaseId"),
315
+ phaseOrder: requiredNumber(child, "phaseOrder"),
316
+ dependencyWorkItemIds: parseStringArray(child.dependencyWorkItemIds, `storyQa.childTasks[${index}].dependencyWorkItemIds`),
317
+ spec: parseStoryQaSpec(child.spec, `storyQa.childTasks[${index}].spec`),
318
+ implementationArtifact: parseStoryQaArtifact(child.implementationArtifact, `storyQa.childTasks[${index}].implementationArtifact`),
319
+ selfReviewArtifact: parseStoryQaArtifact(child.selfReviewArtifact, `storyQa.childTasks[${index}].selfReviewArtifact`),
320
+ validationArtifact: parseStoryQaArtifact(child.validationArtifact, `storyQa.childTasks[${index}].validationArtifact`),
321
+ qaArtifact: parseStoryQaArtifact(child.qaArtifact, `storyQa.childTasks[${index}].qaArtifact`)
322
+ };
323
+ });
324
+ }
325
+ function parseStoryQaSpec(value, label) {
326
+ if (value === undefined || value === null) {
327
+ return null;
328
+ }
329
+ const spec = asObject(value, label);
330
+ return {
331
+ version: requiredNumber(spec, "version"),
332
+ status: requiredString(spec, "status"),
333
+ path: requiredString(spec, "path"),
334
+ contentHash: requiredString(spec, "contentHash"),
335
+ body: requiredString(spec, "body")
336
+ };
337
+ }
338
+ function parseStoryQaArtifact(value, label) {
339
+ if (value === undefined || value === null) {
340
+ return null;
341
+ }
342
+ const artifact = asObject(value, label);
343
+ return {
344
+ artifactId: requiredString(artifact, "artifactId"),
345
+ cycleRunId: requiredString(artifact, "cycleRunId"),
346
+ phase: requiredString(artifact, "phase"),
347
+ status: requiredString(artifact, "status"),
348
+ producedAt: requiredString(artifact, "producedAt"),
349
+ path: optionalString(artifact, "path"),
350
+ verdictJson: optionalString(artifact, "verdictJson"),
351
+ evidenceJson: optionalString(artifact, "evidenceJson"),
352
+ findingsJson: optionalString(artifact, "findingsJson"),
353
+ report: optionalString(artifact, "report")
354
+ };
355
+ }
356
+ function parseStoryQaDependencies(value) {
357
+ if (!Array.isArray(value)) {
358
+ throw new Error("storyQa.dependencies must be an array.");
359
+ }
360
+ return value.map((entry, index) => {
361
+ const dependency = asObject(entry, `storyQa.dependencies[${index}]`);
362
+ return {
363
+ fromWorkItemId: requiredString(dependency, "fromWorkItemId").trim(),
364
+ toWorkItemId: requiredString(dependency, "toWorkItemId").trim()
365
+ };
366
+ });
367
+ }
368
+ function parseStringArray(value, label) {
369
+ if (!Array.isArray(value)) {
370
+ throw new Error(`${label} must be an array.`);
371
+ }
372
+ return value.map((entry, index) => {
373
+ if (typeof entry !== "string" || entry.trim().length === 0) {
374
+ throw new Error(`${label}[${index}] must be a non-empty string.`);
375
+ }
376
+ return entry.trim();
377
+ });
378
+ }
237
379
  function parseArtifacts(value) {
238
380
  if (value === undefined || value === null) {
239
381
  return [];
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.1-dev.9acab970e5d1";
1
+ export declare const forgeBridgeVersion = "0.1.1-dev.ac656b52f9c6";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.1-dev.9acab970e5d1";
1
+ export const forgeBridgeVersion = "0.1.1-dev.ac656b52f9c6";
@@ -3,17 +3,49 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  const DEBUG_OPERATIONAL_SKILLS = new Set(["debug-repro", "debug-root-cause", "debug-fix", "debug-regression"]);
5
5
  const DEBUG_OPERATIONAL_HOOKS = new Set(["debug-gate", "debug-tool-hook", "debug-rework"]);
6
+ const ARCHITECT_OPERATIONAL_SKILLS = new Set([
7
+ "architect-repo-map",
8
+ "architect-acceptance-map",
9
+ "architect-contract-designer",
10
+ "architect-dag-planner",
11
+ "architect-test-plan-designer",
12
+ "architect-risk-review",
13
+ "architect-integration-strategy",
14
+ "architect-handoff-writer",
15
+ "architect-mcp-contract",
16
+ "architect-semantic-validator"
17
+ ]);
18
+ const ARCHITECT_OPERATIONAL_HOOKS = new Set([
19
+ "architect-preflight",
20
+ "architect-context",
21
+ "architect-repo-map",
22
+ "architect-acceptance-map",
23
+ "architect-contracts",
24
+ "architect-plan",
25
+ "architect-qa-seed",
26
+ "architect-integration",
27
+ "architect-mcp-contract",
28
+ "architect-validate-plan",
29
+ "architect-risk-gate",
30
+ "architect-mcp-complete",
31
+ "architect-complete",
32
+ "architect-revise"
33
+ ]);
6
34
  export async function injectWorktreeArtifacts(worktreePath, artifacts) {
7
35
  for (const artifact of artifacts) {
8
36
  await writeArtifact(worktreePath, artifact);
9
37
  }
10
38
  }
11
39
  export function filterArtifactsForLane(artifacts, lane, phase) {
12
- if (lane.trim().toLowerCase() !== "debug") {
13
- return artifacts;
14
- }
40
+ const normalizedLane = lane.trim().toLowerCase();
15
41
  const commandSlug = resolveCommandSlug(lane, phase).toLowerCase();
16
- return artifacts.filter((artifact) => shouldInjectDebugArtifact(artifact, commandSlug));
42
+ if (normalizedLane === "debug") {
43
+ return artifacts.filter((artifact) => shouldInjectDebugArtifact(artifact, commandSlug));
44
+ }
45
+ if (normalizedLane === "architect") {
46
+ return artifacts.filter((artifact) => shouldInjectArchitectArtifact(artifact, commandSlug));
47
+ }
48
+ return artifacts;
17
49
  }
18
50
  export async function writeArtifact(worktreePath, artifact) {
19
51
  const writtenHash = sha256(artifact.body);
@@ -71,6 +103,22 @@ function shouldInjectDebugArtifact(artifact, commandSlug) {
71
103
  return true;
72
104
  }
73
105
  }
106
+ function shouldInjectArchitectArtifact(artifact, commandSlug) {
107
+ if (artifact.scope.trim().toLowerCase() !== "operational") {
108
+ return false;
109
+ }
110
+ const slug = artifact.slug.trim().toLowerCase();
111
+ switch (normalizedArtifactKind(artifact.kind)) {
112
+ case "command":
113
+ return slug === commandSlug;
114
+ case "skill":
115
+ return ARCHITECT_OPERATIONAL_SKILLS.has(slug);
116
+ case "hook":
117
+ return ARCHITECT_OPERATIONAL_HOOKS.has(slug);
118
+ default:
119
+ return false;
120
+ }
121
+ }
74
122
  export function buildSpecBody(laneCommand, workItem, phase = "implementation") {
75
123
  const prompt = laneCommand.body.replaceAll("{workItemId}", workItem.id);
76
124
  return `---
@@ -11,6 +11,7 @@ export declare class GitWorktreeService implements WorktreeService {
11
11
  private resolveMatchingRepo;
12
12
  private ensureBaseBranch;
13
13
  private gitRefExists;
14
+ private currentBranch;
14
15
  private ensureGitIdentity;
15
16
  }
16
17
  export declare function normalizeBranchName(value: string | null | undefined, fallback: string): string;
@@ -17,9 +17,12 @@ export class GitWorktreeService {
17
17
  await this.ensureBaseBranch(repoPath, baseBranch);
18
18
  const shortId = request.workItem.id.replace(/-/g, "").slice(0, 12);
19
19
  const kind = safeSegment(request.workItem.kind, "work-item");
20
- const branchName = normalizeBranchName(`${kind}/${shortId}`, "work-item/unknown");
20
+ const fallbackWorktreeKey = `${kind}/${shortId}`;
21
+ const worktreeKey = request.worktreeKey?.trim() || fallbackWorktreeKey;
22
+ const worktreeSegments = worktreeKeySegments(worktreeKey, kind, shortId);
23
+ const branchName = normalizeBranchName(worktreeSegments.join("/"), "work-item/unknown");
21
24
  const worktreeRoot = resolveWorktreeRoot(allowedRoot, repoPath);
22
- const worktreePath = path.join(worktreeRoot, kind, shortId);
25
+ const worktreePath = path.join(worktreeRoot, ...worktreeSegments);
23
26
  const resolvedWorktreeParent = await ensureDirectory(path.dirname(worktreePath));
24
27
  if (!isSubPath(allowedRoot, resolvedWorktreeParent)) {
25
28
  throw new Error(`Worktree path must stay under ${allowedRoot}.`);
@@ -35,8 +38,14 @@ export class GitWorktreeService {
35
38
  if (!isSubPath(allowedRoot, resolvedWorktreePath)) {
36
39
  throw new Error(`Worktree path must stay under ${allowedRoot}.`);
37
40
  }
41
+ const currentBranch = await this.currentBranch(resolvedWorktreePath);
42
+ if (currentBranch !== branchName) {
43
+ throw new Error(`Existing worktree ${resolvedWorktreePath} is on branch '${currentBranch}', expected '${branchName}'.`);
44
+ }
38
45
  }
39
46
  await this.ensureGitIdentity(resolvedWorktreePath);
47
+ await clearRunArtifactRoots(resolvedWorktreePath, request);
48
+ const qaReworkPacketPath = await materializeQaReworkPacket(resolvedWorktreePath, request);
40
49
  const artifacts = filterArtifactsForLane(request.artifacts, request.lane, request.phase);
41
50
  if (artifacts.length > 0) {
42
51
  await injectWorktreeArtifacts(resolvedWorktreePath, artifacts);
@@ -53,7 +62,8 @@ export class GitWorktreeService {
53
62
  branchName,
54
63
  baseBranch,
55
64
  cleanupWorktrees: request.cleanupWorktrees,
56
- dependencyWarm
65
+ dependencyWarm,
66
+ qaReworkPacketPath
57
67
  };
58
68
  }
59
69
  async release(handle) {
@@ -172,6 +182,9 @@ export class GitWorktreeService {
172
182
  async gitRefExists(repoPath, gitRef) {
173
183
  return this.git.run(repoPath, ["show-ref", "--verify", "--quiet", gitRef]).then(() => true).catch(() => false);
174
184
  }
185
+ async currentBranch(repoPath) {
186
+ return (await this.git.run(repoPath, ["rev-parse", "--abbrev-ref", "HEAD"])).trim();
187
+ }
175
188
  async ensureGitIdentity(repoPath) {
176
189
  await this.git.run(repoPath, ["config", "user.email", "forge-bridge@forge.local"]);
177
190
  await this.git.run(repoPath, ["config", "user.name", "Forge Bridge"]);
@@ -193,6 +206,76 @@ function isCloneableRemote(remoteUrl) {
193
206
  }
194
207
  return trimmed.startsWith("git@") || trimmed.includes("://") || path.isAbsolute(trimmed);
195
208
  }
209
+ async function clearRunArtifactRoots(worktreePath, request) {
210
+ const roots = new Set();
211
+ roots.add(workItemArtifactRoot(worktreePath, request.workItem.id));
212
+ const ownerType = normalizeOwnerType(request.ownerType);
213
+ const ownerId = request.ownerId?.trim();
214
+ if (ownerType && ownerId) {
215
+ roots.add(ownerArtifactRoot(worktreePath, ownerType, ownerId));
216
+ }
217
+ for (const root of roots) {
218
+ const resolvedRoot = path.resolve(root);
219
+ if (!isSubPath(worktreePath, resolvedRoot)) {
220
+ throw new Error(`Artifact root must stay under ${worktreePath}.`);
221
+ }
222
+ await ensureNoSymlinkPathSegments(worktreePath, resolvedRoot, "Artifact root must not traverse symlinked path segments.");
223
+ await fs.rm(resolvedRoot, { recursive: true, force: true });
224
+ await fs.mkdir(resolvedRoot, { recursive: true });
225
+ }
226
+ }
227
+ async function materializeQaReworkPacket(worktreePath, request) {
228
+ const qaRework = request.qaRework;
229
+ if (!qaRework) {
230
+ return undefined;
231
+ }
232
+ const artifactRoot = artifactRootForRequest(worktreePath, request);
233
+ const packetFileName = qaReworkPacketFileName(qaRework.packetPath);
234
+ const packetPath = path.join(artifactRoot, packetFileName);
235
+ const paths = new Set([packetPath, path.join(artifactRoot, "qa-rework-packet.json")]);
236
+ const packetJson = qaRework.packetJson.endsWith("\n") ? qaRework.packetJson : `${qaRework.packetJson}\n`;
237
+ for (const target of paths) {
238
+ const resolvedTarget = path.resolve(target);
239
+ if (!isSubPath(worktreePath, resolvedTarget)) {
240
+ throw new Error(`QA rework packet path must stay under ${worktreePath}.`);
241
+ }
242
+ await ensureNoSymlinkPathSegments(worktreePath, path.dirname(resolvedTarget), "QA rework packet path must not traverse symlinked path segments.");
243
+ await fs.mkdir(path.dirname(resolvedTarget), { recursive: true });
244
+ await fs.writeFile(resolvedTarget, packetJson, "utf8");
245
+ }
246
+ return path.resolve(packetPath);
247
+ }
248
+ function artifactRootForRequest(worktreePath, request) {
249
+ const ownerType = normalizeOwnerType(request.ownerType);
250
+ const ownerId = request.ownerId?.trim();
251
+ if (ownerType && ownerId) {
252
+ return ownerArtifactRoot(worktreePath, ownerType, ownerId);
253
+ }
254
+ return workItemArtifactRoot(worktreePath, request.workItem.id);
255
+ }
256
+ function workItemArtifactRoot(worktreePath, workItemId) {
257
+ return path.join(worktreePath, ".forge", "work-items", safeSegment(workItemId, "work item id"), "artifacts");
258
+ }
259
+ function ownerArtifactRoot(worktreePath, ownerType, ownerId) {
260
+ return path.join(worktreePath, ".forge", ownerType === "story" ? "stories" : "work-items", safeSegment(ownerId, "owner id"), "artifacts");
261
+ }
262
+ function normalizeOwnerType(value) {
263
+ const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
264
+ if (normalized === "story") {
265
+ return "story";
266
+ }
267
+ if (normalized === "work_item" || normalized === "workitem" || normalized === "work item") {
268
+ return "work_item";
269
+ }
270
+ return null;
271
+ }
272
+ function qaReworkPacketFileName(packetPath) {
273
+ const normalized = packetPath.trim().replace(/\\/g, "/");
274
+ const fileName = normalized.split("/").filter(Boolean).at(-1) ?? "";
275
+ return /^qa-rework-packet(?:\.attempt-\d+)?\.json$/i.test(fileName)
276
+ ? fileName
277
+ : "qa-rework-packet.json";
278
+ }
196
279
  export function normalizeBranchName(value, fallback) {
197
280
  const branch = (value?.trim() || fallback).trim();
198
281
  if (branch.length === 0 ||
@@ -205,6 +288,7 @@ export function normalizeBranchName(value, fallback) {
205
288
  branch.endsWith(".") ||
206
289
  branch.toLowerCase().endsWith(".lock") ||
207
290
  /\s/.test(branch) ||
291
+ // eslint-disable-next-line no-control-regex -- Git branch validation must reject ASCII control characters.
208
292
  /[\u0000-\u001f~^:?*[\\]/.test(branch) ||
209
293
  branch.split("/").some((part) => part.length === 0 || part.startsWith(".") || part.toLowerCase().endsWith(".lock"))) {
210
294
  throw new Error("Git branch name must be valid, without whitespace, and cannot start with '-'.");
@@ -241,6 +325,39 @@ async function gitMetadataExists(repoPath, allowedRoot) {
241
325
  const resolvedGitDir = await resolveExistingDirectoryPath(gitDirPath);
242
326
  return isSubPath(allowedRoot, resolvedGitDir);
243
327
  }
328
+ async function ensureNoSymlinkPathSegments(root, targetPath, errorMessage) {
329
+ const resolvedRoot = path.resolve(root);
330
+ const resolvedTarget = path.resolve(targetPath);
331
+ const relative = path.relative(resolvedRoot, resolvedTarget);
332
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
333
+ throw new Error(errorMessage);
334
+ }
335
+ let current = resolvedRoot;
336
+ const rootStat = await fs.lstat(current);
337
+ if (rootStat.isSymbolicLink()) {
338
+ throw new Error(errorMessage);
339
+ }
340
+ if (!relative) {
341
+ return;
342
+ }
343
+ for (const segment of relative.split(path.sep)) {
344
+ if (!segment) {
345
+ continue;
346
+ }
347
+ current = path.join(current, segment);
348
+ const stat = await fs.lstat(current).catch((error) => {
349
+ if (error.code === "ENOENT")
350
+ return null;
351
+ throw error;
352
+ });
353
+ if (!stat) {
354
+ return;
355
+ }
356
+ if (stat.isSymbolicLink()) {
357
+ throw new Error(errorMessage);
358
+ }
359
+ }
360
+ }
244
361
  async function pathExists(inputPath) {
245
362
  return fs.stat(inputPath).then(() => true).catch(() => false);
246
363
  }
@@ -260,6 +377,14 @@ function uniqueStrings(values) {
260
377
  }
261
378
  return result;
262
379
  }
380
+ function worktreeKeySegments(worktreeKey, fallbackKind, fallbackShortId) {
381
+ const segments = worktreeKey
382
+ .split("/")
383
+ .map((segment) => segment.trim())
384
+ .filter((segment) => segment.length > 0)
385
+ .map((segment) => safeSegment(segment, "worktree"));
386
+ return segments.length > 0 ? segments : [fallbackKind, fallbackShortId];
387
+ }
263
388
  function isSinglePathSegment(value) {
264
389
  return value.length > 0 && value !== "." && value !== ".." && !value.includes("/") && !value.includes("\\");
265
390
  }
@@ -1,14 +1,18 @@
1
- import type { DispatchRepo, DispatchWorkItem, DispatchResolvedArtifact } from "../session/session.types.js";
1
+ import type { DispatchQaReworkContext, DispatchRepo, DispatchWorkItem, DispatchResolvedArtifact } from "../session/session.types.js";
2
2
  import type { WarmDependenciesResult } from "./dependency-warmer.js";
3
3
  export interface WorktreePrepareRequest {
4
4
  readonly repo: DispatchRepo;
5
5
  readonly workItem: DispatchWorkItem;
6
6
  readonly baseBranch: string;
7
+ readonly worktreeKey?: string | null;
8
+ readonly ownerType?: string | null;
9
+ readonly ownerId?: string | null;
7
10
  readonly lane: string;
8
11
  readonly phase: string;
9
12
  readonly allowedRepoRoot: string;
10
13
  readonly cleanupWorktrees: boolean;
11
14
  readonly artifacts: readonly DispatchResolvedArtifact[];
15
+ readonly qaRework?: DispatchQaReworkContext | null;
12
16
  readonly warmPathOverrides?: readonly string[];
13
17
  }
14
18
  export interface WorktreeHandle {
@@ -18,4 +22,5 @@ export interface WorktreeHandle {
18
22
  readonly baseBranch: string;
19
23
  readonly cleanupWorktrees: boolean;
20
24
  readonly dependencyWarm?: WarmDependenciesResult;
25
+ readonly qaReworkPacketPath?: string;
21
26
  }