@leitwerk-dev/worker 0.5.10 → 0.5.12

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.
@@ -5,8 +5,6 @@ import {
5
5
  type ComponentManifest,
6
6
  type ComponentManifestEntry,
7
7
  deserializeManifest,
8
- diffManifest,
9
- type ManifestDiff,
10
8
  serializeManifest,
11
9
  } from "./manifest.js";
12
10
  import { aggregateAgentsMd, collectSkills } from "./resource-aggregator.js";
@@ -17,8 +15,12 @@ export interface GitOps {
17
15
  clone(repoLocator: string, targetDir: string): Promise<void>;
18
16
  /** @internal */
19
17
  checkout(repoDir: string, branch: string): Promise<void>;
20
- /** Refuse dirty worktrees and pin an exact commit. @internal */
21
- checkoutRevision?(repoDir: string, revision: string): Promise<void>;
18
+ /** Refuse dirty worktrees, pin an exact commit, and return the verified SHA. @internal */
19
+ checkoutRevision?(
20
+ repoDir: string,
21
+ revision: string,
22
+ preserveSubmodules?: boolean,
23
+ ): Promise<string>;
22
24
  /** @internal */
23
25
  createBranch(repoDir: string, branchName: string, startPoint: string): Promise<void>;
24
26
  /** @internal */
@@ -28,7 +30,13 @@ export interface GitOps {
28
30
  /** @internal */
29
31
  readFile(repoDir: string, filePath: string): Promise<string | null>;
30
32
  /** @internal */
31
- listFiles(repoDir: string, pattern: string): Promise<string[]>;
33
+ listFiles(repoDir: string, patterns: string[], excludeSubmodules?: boolean): Promise<string[]>;
34
+ /** @internal */
35
+ prepareSubmodules(
36
+ projectKey: string,
37
+ repoDir: string,
38
+ signal?: AbortSignal,
39
+ ): Promise<string | undefined>;
32
40
  }
33
41
 
34
42
  /** @internal */
@@ -47,18 +55,14 @@ export interface RunRootPlan {
47
55
  workspaceRoot: string;
48
56
  instanceId: string;
49
57
  components: ComponentCheckoutPlan[];
58
+ submodules?: { signal?: AbortSignal };
50
59
  }
51
60
 
52
61
  export interface MaterializeResult {
53
62
  manifest: ComponentManifest;
54
63
  aggregatedAgentsMdSources: string[];
55
64
  loadedSkills: string[];
56
- }
57
-
58
- export interface ValidationResult {
59
- valid: boolean;
60
- diff: ManifestDiff;
61
- existingManifest: ComponentManifest | null;
65
+ submoduleWarnings?: string[];
62
66
  }
63
67
 
64
68
  export class RunRootPreparationError extends Error {
@@ -97,11 +101,13 @@ export function planRunRoot(
97
101
  workspaceRoot: string,
98
102
  instanceId: string,
99
103
  projectSnapshots: ComponentCheckoutPlan[],
104
+ submodules?: RunRootPlan["submodules"],
100
105
  ): RunRootPlan {
101
106
  return {
102
107
  workspaceRoot,
103
108
  instanceId,
104
109
  components: projectSnapshots.map((p) => ({ ...p })),
110
+ ...(submodules ? { submodules } : {}),
105
111
  };
106
112
  }
107
113
 
@@ -131,20 +137,26 @@ async function collectMaterializedEntries(
131
137
  plan: RunRootPlan,
132
138
  git: RunRootGitOps,
133
139
  errors: string[],
134
- reusable = new Map<string, ComponentManifestEntry>(),
140
+ existing?: ReadonlyMap<string, ComponentManifestEntry>,
141
+ pin?: { projectKey: string; revision: string },
135
142
  ): Promise<ComponentManifestEntry[]> {
136
143
  const entries: ComponentManifestEntry[] = [];
137
144
  for (const comp of plan.components) {
138
145
  try {
139
- const retained = reusable.get(comp.key);
140
- if (retained?.revision) {
146
+ const retained = existing?.get(comp.key);
147
+ const entry =
148
+ retained?.repoLocator === comp.repoLocator &&
149
+ retained.baseBranch === comp.baseBranch &&
150
+ retained.workBranch === comp.workBranch
151
+ ? retained
152
+ : await materializeComponentEntry(plan, comp, git);
153
+ const revision = pin?.projectKey === comp.key ? pin.revision : entry.revision;
154
+ if (revision) {
141
155
  if (!git.checkoutRevision) throw new Error("Pinned repository checkout is unavailable");
142
156
  const dir = componentDir(plan.workspaceRoot, comp.key);
143
- await git.checkoutRevision(dir, retained.revision);
144
- if ((await git.getHeadSha(dir)).toLowerCase() !== retained.revision.toLowerCase())
145
- throw new Error("Recovered checkout HEAD does not match captured commit");
146
- }
147
- entries.push(retained ?? (await materializeComponentEntry(plan, comp, git)));
157
+ const headSha = await git.checkoutRevision(dir, revision, !!plan.submodules);
158
+ entries.push({ ...entry, headSha, revision });
159
+ } else entries.push(entry);
148
160
  } catch (e) {
149
161
  errors.push(`${comp.key}: ${e instanceof Error ? e.message : String(e)}`);
150
162
  }
@@ -170,40 +182,25 @@ async function gatherAgentsAndSkills(
170
182
  skillId: string;
171
183
  content: string;
172
184
  }> = [];
173
- const aggregatedAgentsMdSources: string[] = [];
174
-
175
185
  for (const comp of plan.components) {
176
186
  const root = componentDir(plan.workspaceRoot, comp.key);
177
- const agentPaths = await git.listFiles(root, AGENTS_GLOB);
178
- const sortedAgentPaths = [...agentPaths].sort((a, b) => a.localeCompare(b));
179
- for (const p of sortedAgentPaths) {
180
- const content = await git.readFile(root, p);
181
- if (content !== null) {
182
- agentSources.push({
183
- componentKey: comp.key,
184
- filePath: p,
185
- content,
186
- });
187
- aggregatedAgentsMdSources.push(`${comp.key}/${p}`);
188
- }
189
- }
190
-
191
- const skillPaths = await git.listFiles(root, SKILL_GLOB);
192
- for (const p of skillPaths) {
193
- const skillId = skillIdFromSkillPath(p);
194
- if (!skillId) {
195
- continue;
196
- }
187
+ for (const p of await git.listFiles(root, [AGENTS_GLOB, SKILL_GLOB], !!plan.submodules)) {
197
188
  const content = await git.readFile(root, p);
198
- if (content !== null) {
199
- skillSources.push({ componentKey: comp.key, skillId, content });
189
+ if (content === null) continue;
190
+ if (path.posix.basename(p) === "AGENTS.md") {
191
+ agentSources.push({ componentKey: comp.key, filePath: p, content });
192
+ } else {
193
+ const skillId = skillIdFromSkillPath(p);
194
+ if (skillId) skillSources.push({ componentKey: comp.key, skillId, content });
200
195
  }
201
196
  }
202
197
  }
203
198
 
204
199
  const agentsMd = aggregateAgentsMd(agentSources);
205
200
  const skillsMap = collectSkills(skillSources);
206
- aggregatedAgentsMdSources.sort((a, b) => a.localeCompare(b));
201
+ const aggregatedAgentsMdSources = agentSources
202
+ .map(({ componentKey, filePath }) => `${componentKey}/${filePath}`)
203
+ .sort((a, b) => a.localeCompare(b));
207
204
  return { aggregatedAgentsMdSources, agentsMd, skillsMap };
208
205
  }
209
206
 
@@ -236,11 +233,22 @@ async function finalizeRunRoot(
236
233
  components: entries,
237
234
  };
238
235
 
236
+ const submoduleWarnings: string[] = [];
237
+ if (plan.submodules && errors.length === 0) {
238
+ for (const { key } of entries) {
239
+ const dir = componentDir(plan.workspaceRoot, key);
240
+ const warning = await git.prepareSubmodules(key, dir, plan.submodules.signal);
241
+ if (warning) submoduleWarnings.push(warning);
242
+ }
243
+ }
239
244
  const { aggregatedAgentsMdSources, agentsMd, skillsMap } = await gatherAgentsAndSkills(plan, git);
245
+ const instructions = submoduleWarnings.length
246
+ ? `${agentsMd}\n\n## Workspace preparation warnings\n\n${submoduleWarnings.map((warning) => `- ${warning}`).join("\n")}\n`
247
+ : agentsMd;
240
248
  const loadedSkills = [...skillsMap.keys()].sort((a, b) => a.localeCompare(b));
241
249
 
242
250
  try {
243
- await writeAggregatedArtifacts(plan, git, manifest, agentsMd, skillsMap);
251
+ await writeAggregatedArtifacts(plan, git, manifest, instructions, skillsMap);
244
252
  } catch (e) {
245
253
  errors.push(`write: ${e instanceof Error ? e.message : String(e)}`);
246
254
  }
@@ -256,18 +264,10 @@ async function finalizeRunRoot(
256
264
  manifest,
257
265
  aggregatedAgentsMdSources,
258
266
  loadedSkills,
267
+ ...(submoduleWarnings.length ? { submoduleWarnings } : {}),
259
268
  };
260
269
  }
261
270
 
262
- export async function materializeRunRoot(
263
- plan: RunRootPlan,
264
- git: RunRootGitOps,
265
- ): Promise<MaterializeResult> {
266
- const errors: string[] = [];
267
- const entries = await collectMaterializedEntries(plan, git, errors);
268
- return finalizeRunRoot(plan, git, entries, errors);
269
- }
270
-
271
271
  /** @internal */
272
272
  export async function prepareOnDemandRunRoot(
273
273
  plan: RunRootPlan,
@@ -282,77 +282,38 @@ export async function prepareOnDemandRunRoot(
282
282
  !plan.components.some((component) => component.key === projectKey)
283
283
  )
284
284
  throw new Error("Repository is outside this process's authorized scope");
285
- const validation = await validateRunRoot(plan.workspaceRoot, plan.components, git);
286
- const existingKeys = new Set(
287
- validation.existingManifest?.components.map((component) => component.key) ?? [],
288
- );
285
+ const existing = await readManifestEntries(plan.workspaceRoot, git);
289
286
  const selected = {
290
287
  ...plan,
291
288
  components: plan.components.filter(
292
- (component) => existingKeys.has(component.key) || component.key === projectKey,
289
+ (component) => existing.has(component.key) || component.key === projectKey,
293
290
  ),
294
291
  };
295
- // Selection only omits missing components, so retained entries keep the same validation.
296
- const result = await repairRunRoot(validation, selected, git);
297
- if (revision !== undefined) {
298
- if (!git.checkoutRevision) throw new Error("Pinned repository checkout is unavailable");
299
- const dir = componentDir(plan.workspaceRoot, projectKey!);
300
- await git.checkoutRevision(dir, revision);
301
- const headSha = await git.getHeadSha(dir);
302
- if (headSha.toLowerCase() !== revision.toLowerCase())
303
- throw new Error("Checkout HEAD does not match captured commit");
304
- return finalizeRunRoot(
305
- selected,
306
- git,
307
- result.manifest.components.map((entry) =>
308
- entry.key === projectKey ? { ...entry, headSha, revision } : entry,
309
- ),
310
- [],
311
- );
312
- }
313
- return result;
292
+ const pin = projectKey && revision ? { projectKey, revision } : undefined;
293
+ return materializeSelection(selected, git, existing, pin);
314
294
  }
315
295
 
316
- export async function validateRunRoot(
317
- workspaceRoot: string,
318
- serverProjects: ComponentCheckoutPlan[],
319
- git: GitOps,
320
- ): Promise<ValidationResult> {
296
+ async function readManifestEntries(workspaceRoot: string, git: GitOps) {
321
297
  const raw = await git.readFile(workspaceRoot, MANIFEST_REL);
322
298
  const parsed = raw === null ? null : deserializeManifest(raw);
323
- if (!parsed?.ok) {
324
- return {
325
- valid: false,
326
- diff: {
327
- stale: [],
328
- missing: serverProjects.map((p) => p.key),
329
- extra: [],
330
- unchanged: [],
331
- },
332
- existingManifest: null,
333
- };
334
- }
335
- const diff = diffManifest(parsed.manifest, serverProjects);
336
- const valid = diff.stale.length === 0 && diff.missing.length === 0 && diff.extra.length === 0;
337
- return {
338
- valid,
339
- diff,
340
- existingManifest: parsed.manifest,
341
- };
299
+ return new Map(parsed?.ok ? parsed.manifest.components.map((entry) => [entry.key, entry]) : []);
300
+ }
301
+
302
+ export async function materializeRunRoot(plan: RunRootPlan, git: RunRootGitOps, resume = false) {
303
+ return materializeSelection(
304
+ plan,
305
+ git,
306
+ resume ? await readManifestEntries(plan.workspaceRoot, git) : undefined,
307
+ );
342
308
  }
343
309
 
344
- export async function repairRunRoot(
345
- validation: ValidationResult,
310
+ async function materializeSelection(
346
311
  plan: RunRootPlan,
347
312
  git: RunRootGitOps,
313
+ existing?: ReadonlyMap<string, ComponentManifestEntry>,
314
+ pin?: { projectKey: string; revision: string },
348
315
  ): Promise<MaterializeResult> {
349
316
  const errors: string[] = [];
350
- const reusable = new Map(
351
- validation.existingManifest?.components
352
- .filter((component) => validation.diff.unchanged.includes(component.key))
353
- .map((component) => [component.key, component]),
354
- );
355
- const manifestEntries = await collectMaterializedEntries(plan, git, errors, reusable);
356
-
357
- return finalizeRunRoot(plan, git, manifestEntries, errors);
317
+ const entries = await collectMaterializedEntries(plan, git, errors, existing, pin);
318
+ return finalizeRunRoot(plan, git, entries, errors);
358
319
  }