@leitwerk-dev/process-analysis 0.1.8 → 0.2.0

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 (41) hide show
  1. package/README.md +12 -7
  2. package/dist/actions.d.ts +0 -13
  3. package/dist/actions.d.ts.map +1 -1
  4. package/dist/index.d.ts +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +468 -33
  7. package/dist/index.js.map +1 -1
  8. package/dist/process-definition.d.ts +1 -4
  9. package/dist/process-definition.d.ts.map +1 -1
  10. package/dist/server-runtime.d.ts +0 -8
  11. package/dist/server-runtime.d.ts.map +1 -1
  12. package/dist/snapshot-downloader.d.ts +8 -0
  13. package/dist/snapshot-downloader.d.ts.map +1 -1
  14. package/dist/state.d.ts +1 -1
  15. package/dist/state.d.ts.map +1 -1
  16. package/dist/tools.d.ts +4 -0
  17. package/dist/tools.d.ts.map +1 -0
  18. package/package.json +4 -5
  19. package/src/actions.ts +0 -16
  20. package/src/index.ts +11 -13
  21. package/src/process-definition.ts +70 -195
  22. package/src/server-runtime.ts +0 -46
  23. package/src/snapshot-downloader.ts +14 -9
  24. package/src/state.ts +4 -7
  25. package/src/tools.ts +35 -0
  26. package/dist/actions.js +0 -36
  27. package/dist/actions.js.map +0 -1
  28. package/dist/params.js +0 -25
  29. package/dist/params.js.map +0 -1
  30. package/dist/process-definition.js +0 -266
  31. package/dist/process-definition.js.map +0 -1
  32. package/dist/process-ref.js +0 -37
  33. package/dist/process-ref.js.map +0 -1
  34. package/dist/server-runtime.js +0 -52
  35. package/dist/server-runtime.js.map +0 -1
  36. package/dist/snapshot-downloader.js +0 -61
  37. package/dist/snapshot-downloader.js.map +0 -1
  38. package/dist/snapshot-markdown.js +0 -34
  39. package/dist/snapshot-markdown.js.map +0 -1
  40. package/dist/state.js +0 -31
  41. package/dist/state.js.map +0 -1
package/README.md CHANGED
@@ -9,9 +9,18 @@
9
9
 
10
10
  Unsupported protocols, credentials in URLs, missing ids, and empty instructions are rejected. Credential-bearing URLs are not remembered.
11
11
 
12
+ ## Process
13
+
14
+ The process has two business turns:
15
+
16
+ | Turn | Kind | Purpose |
17
+ |---|---|---|
18
+ | `analyze_process` | LLM | Prepare a current snapshot, then analyze it read-only. |
19
+ | `analysis_decision` | Human | Complete, refine, ask a follow-up, or refresh and rerun the analysis. |
20
+
12
21
  ## Snapshot behavior
13
22
 
14
- The first server turn downloads `/api/processes/:id` and `/api/processes/:id/primary-path`, then writes:
23
+ The preparation phase of `analyze_process` calls the authorized `process_analysis_download_snapshot` integration tool before Pi is prompted. It reports **Analysis preparation** progress in the same Chronicle cluster and does not create a separate Turn Rail entry. The server-owned tool downloads `/api/processes/:id` and `/api/processes/:id/primary-path`, then writes:
15
24
 
16
25
  - `process-detail.json`
17
26
  - `primary-path.json`
@@ -26,10 +35,6 @@ Snapshots are stored below the target process workspace at `.leitwerk/process-an
26
35
 
27
36
  The analysis LLM turn has only `read` and `bash`. It runs in the absolute directory where the Leitwerk server was launched. Its prompt requires read-only inspection, prohibits file modifications, and directs any code/repository inspection to that server launch directory only. Process Analysis does not require any configured `components` entry.
28
37
 
29
- ## Follow-up and handoff
30
-
31
- From the decision turn, the operator can complete the analysis, ask follow-up questions, refine/rerun analysis, or refresh the snapshot. When Local Repo Change is also loaded, its launch-planner capability adds the action and turn for starting a Local Repo Change process. Without that optional capability, neither is present in the process graph.
32
-
33
- Handoff targets the same server launch directory as a local repository, derives its base branch from that repository when possible (falling back to `main`), leaves the work branch blank for automatic selection, and asks the Local Repo Change planner for an explicit `imported_plan` launch. The analysis is imported as a hidden plan, and implementation starts after Local Repo Change creates the automatic work branch and replans its entry turn. If the server launch directory is not a git repository, that error is reported only when starting the handoff.
38
+ ## Follow-up
34
39
 
35
- Process Analysis keeps its source provenance in opaque target-process metadata and owns the durable deduplication key (`process-analysis:<analysisProcessId>:local-repo-change`). Retrying or concurrently triggering the same handoff therefore reuses the same Local Repo Change process instead of creating duplicates. A successful create or reuse completes Process Analysis and runs its normal snapshot cleanup. An unsuccessful handoff leaves the failed turn available for retry.
40
+ From the decision turn, the operator can complete the analysis, ask follow-up questions, refine the analysis, or refresh the snapshot. Refresh routes back to `analyze_process`; its preparation phase replaces the snapshot before the next prompt. Completion retains the latest analysis product. Process Analysis does not launch repository-change processes or create tracker tickets.
package/dist/actions.d.ts CHANGED
@@ -3,7 +3,6 @@ export declare const processAnalysisActionIds: {
3
3
  readonly askFollowup: "ask_followup";
4
4
  readonly refineAnalysis: "refine_analysis";
5
5
  readonly refreshSnapshot: "refresh_snapshot";
6
- readonly startLocalRepoChange: "start_local_repo_change";
7
6
  };
8
7
  export declare const followupForm: {
9
8
  id: string;
@@ -17,16 +16,4 @@ export declare const followupForm: {
17
16
  }[];
18
17
  submitLabel: string;
19
18
  };
20
- export declare const handoffForm: {
21
- id: string;
22
- title: string;
23
- fields: {
24
- id: string;
25
- label: string;
26
- kind: "textarea";
27
- primaryPrompt: true;
28
- description: string;
29
- }[];
30
- submitLabel: string;
31
- };
32
19
  //# sourceMappingURL=actions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,wBAAwB;;;;;;CAM3B,CAAC;AAEX,eAAO,MAAM,YAAY;;;;;;;;;;;CAaxB,CAAC;AAEF,eAAO,MAAM,WAAW;;;;;;;;;;;CAavB,CAAC"}
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,wBAAwB;;;;;CAK3B,CAAC;AAEX,eAAO,MAAM,YAAY;;;;;;;;;;;CAaxB,CAAC"}
package/dist/index.d.ts CHANGED
@@ -2,7 +2,6 @@ import { type LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
2
2
  export declare const manifest: {
3
3
  readonly id: "process-analysis";
4
4
  readonly version: "0.1.0";
5
- readonly optional: readonly ["local-repo-change"];
6
5
  };
7
6
  declare const processAnalysisExtension: LeitwerkExtensionModule;
8
7
  export default processAnalysisExtension;
@@ -14,4 +13,5 @@ export * from "./server-runtime.js";
14
13
  export * from "./snapshot-downloader.js";
15
14
  export * from "./snapshot-markdown.js";
16
15
  export * from "./state.js";
16
+ export * from "./tools.js";
17
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAwB,KAAK,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAI/F,eAAO,MAAM,QAAQ;;;;CAIX,CAAC;AAEX,QAAA,MAAM,wBAAwB,EAAE,uBAiB/B,CAAC;AAEF,eAAe,wBAAwB,CAAC;AACxC,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AACpC,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAwB,KAAK,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAK/F,eAAO,MAAM,QAAQ;;;CAGX,CAAC;AAEX,QAAA,MAAM,wBAAwB,EAAE,uBAe/B,CAAC;AAEF,eAAe,wBAAwB,CAAC;AACxC,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AACpC,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,38 +1,473 @@
1
- import path from "node:path";
2
- import { localRepoChangeCapabilities } from "@leitwerk-dev/local-repo-change";
1
+ // src/index.ts
2
+ import path3 from "path";
3
3
  import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
4
- import { createProcessAnalysisProcess } from "./process-definition.js";
5
- import { configureProcessAnalysisRuntime } from "./server-runtime.js";
6
- export const manifest = {
7
- id: "process-analysis",
8
- version: "0.1.0",
9
- optional: ["local-repo-change"],
10
- };
11
- const processAnalysisExtension = {
12
- manifest,
13
- setupCatalog(api) {
14
- const planner = api.get(localRepoChangeCapabilities.launchPlanner);
15
- api.registerProcess(createProcessAnalysisProcess(Array.isArray(planner) ? undefined : planner));
4
+
5
+ // src/process-definition.ts
6
+ import { rm } from "fs/promises";
7
+ import {
8
+ createEmptyStructuralProcessState,
9
+ flow,
10
+ humanTurn,
11
+ revisionAction
12
+ } from "@leitwerk-dev/process-sdk";
13
+
14
+ // src/actions.ts
15
+ var processAnalysisActionIds = {
16
+ completeAnalysis: "complete_analysis",
17
+ askFollowup: "ask_followup",
18
+ refineAnalysis: "refine_analysis",
19
+ refreshSnapshot: "refresh_snapshot"
20
+ };
21
+ var followupForm = {
22
+ id: "process_analysis_followup",
23
+ title: "Follow up",
24
+ fields: [
25
+ {
26
+ id: "message",
27
+ label: "Question or refinement",
28
+ kind: "textarea",
29
+ primaryPrompt: true,
30
+ required: true
31
+ }
32
+ ],
33
+ submitLabel: "Send"
34
+ };
35
+
36
+ // src/params.ts
37
+ import { trimString } from "@leitwerk-dev/domain";
38
+ var processAnalysisParamsCodec = {
39
+ parse(value) {
40
+ const record = typeof value === "object" && value !== null ? value : {};
41
+ return {
42
+ processRef: trimString(record.processRef),
43
+ instruction: trimString(record.instruction),
44
+ analysisCwd: trimString(record.analysisCwd)
45
+ };
46
+ },
47
+ serialize(value) {
48
+ return value;
49
+ }
50
+ };
51
+ function validateProcessAnalysisLaunchInput(input) {
52
+ const processRef = trimString(input.processRef);
53
+ const instruction = trimString(input.instruction);
54
+ const errors = [];
55
+ if (!processRef)
56
+ errors.push({ code: "required", fieldId: "processRef", message: "processRef is required" });
57
+ if (!instruction)
58
+ errors.push({ code: "required", fieldId: "instruction", message: "instruction is required" });
59
+ return errors.length ? { ok: false, errors } : { ok: true, value: { processRef, instruction } };
60
+ }
61
+
62
+ // src/server-runtime.ts
63
+ import path from "path";
64
+ var runtime = {
65
+ analysisCwd: path.resolve(process.cwd()),
66
+ serverBaseUrl: "http://localhost",
67
+ processWorkspacesDir: null
68
+ };
69
+ function configureProcessAnalysisRuntime(overrides) {
70
+ runtime.analysisCwd = overrides.analysisCwd ? path.resolve(overrides.analysisCwd) : runtime.analysisCwd;
71
+ runtime.serverBaseUrl = overrides.serverBaseUrl ?? runtime.serverBaseUrl;
72
+ runtime.processWorkspacesDir = overrides.processWorkspacesDir ?? null;
73
+ }
74
+ function getProcessAnalysisRuntime() {
75
+ return runtime;
76
+ }
77
+
78
+ // src/snapshot-downloader.ts
79
+ import { mkdir, writeFile } from "fs/promises";
80
+ import path2 from "path";
81
+
82
+ // src/process-ref.ts
83
+ var ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
84
+ function resolveProcessRef(input) {
85
+ const raw = input.processRef.trim();
86
+ if (!raw) throw new Error("processRef is required");
87
+ const currentOrigin = new URL(input.serverBaseUrl).origin;
88
+ let id = "";
89
+ if (ID_RE.test(raw) && !raw.includes("/")) {
90
+ id = raw;
91
+ } else {
92
+ let url;
93
+ try {
94
+ url = raw.startsWith("/") ? new URL(raw, currentOrigin) : new URL(raw);
95
+ } catch {
96
+ throw new Error("processRef must be a process id or process URL");
97
+ }
98
+ if (url.protocol !== "http:" && url.protocol !== "https:")
99
+ throw new Error("Only http(s) process URLs are supported");
100
+ if (url.username || url.password)
101
+ throw new Error("Credentials in process URLs are not allowed");
102
+ const parts = url.pathname.split("/").filter(Boolean);
103
+ const apiIndex = parts[0] === "api" ? 1 : 0;
104
+ if (parts[apiIndex] !== "processes" || !parts[apiIndex + 1])
105
+ throw new Error("URL must point to /processes/:id or /api/processes/:id");
106
+ id = decodeURIComponent(parts[apiIndex + 1]);
107
+ }
108
+ if (!ID_RE.test(id)) throw new Error("process id is missing or invalid");
109
+ return {
110
+ id,
111
+ origin: currentOrigin,
112
+ apiUrl: `${currentOrigin}/api/processes/${encodeURIComponent(id)}`
113
+ };
114
+ }
115
+
116
+ // src/snapshot-markdown.ts
117
+ function fence(value, language = "json") {
118
+ let marker = "```";
119
+ while (value.includes(marker)) marker += "`";
120
+ return `${marker}${language}
121
+ ${value.endsWith("\n") ? value : `${value}
122
+ `}${marker}`;
123
+ }
124
+ function jsonMarkdown(title, value) {
125
+ return `# ${title}
126
+
127
+ ${fence(JSON.stringify(value, null, 2))}
128
+ `;
129
+ }
130
+ function buildSummaryMarkdown(input) {
131
+ const detail = input.detail;
132
+ return [
133
+ "# Process snapshot summary",
134
+ `- Source: ${input.sourceUrl}`,
135
+ `- Process id: ${String(detail.id ?? "unknown")}`,
136
+ `- Process type: ${String(detail.processId ?? "unknown")}`,
137
+ `- Title: ${String(detail.title ?? "(untitled)")}`,
138
+ `- Lifecycle: ${String(detail.lifecycleStatus ?? "unknown")}`,
139
+ `- Selected turn: ${String(detail.selectedTurnId ?? "none")}`,
140
+ "",
141
+ "## Primary path",
142
+ fence(JSON.stringify(input.primaryPath, null, 2))
143
+ ].join("\n");
144
+ }
145
+ function buildRecordsMarkdown(title, value) {
146
+ if (Array.isArray(value))
147
+ return [
148
+ `# ${title}`,
149
+ "",
150
+ ...value.map((item, i) => `## ${i + 1}
151
+
152
+ ${fence(JSON.stringify(item, null, 2))}`)
153
+ ].join("\n");
154
+ return jsonMarkdown(title, value);
155
+ }
156
+
157
+ // src/snapshot-downloader.ts
158
+ var SNAPSHOT_FETCH_TIMEOUT_MS = 3e4;
159
+ async function fetchJson(url) {
160
+ let response;
161
+ try {
162
+ response = await fetch(url, {
163
+ headers: { accept: "application/json" },
164
+ signal: AbortSignal.timeout(SNAPSHOT_FETCH_TIMEOUT_MS)
165
+ });
166
+ } catch (error) {
167
+ const message = error instanceof Error ? error.message : String(error);
168
+ throw new Error(`Network error fetching ${url}: ${message}`);
169
+ }
170
+ if (!response.ok)
171
+ throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
172
+ try {
173
+ return await response.json();
174
+ } catch (error) {
175
+ const message = error instanceof Error ? error.message : String(error);
176
+ throw new Error(`Invalid JSON response from ${url}: ${message}`);
177
+ }
178
+ }
179
+ async function writeJson(file, value) {
180
+ await writeFile(file, `${JSON.stringify(value, null, 2)}
181
+ `, "utf8");
182
+ }
183
+ function resolveProcessSnapshotDirectory(input) {
184
+ const runtime2 = getProcessAnalysisRuntime();
185
+ if (!runtime2.processWorkspacesDir) throw new Error("processWorkspacesDir is not configured");
186
+ const ref = resolveProcessRef({
187
+ processRef: input.processRef,
188
+ serverBaseUrl: runtime2.serverBaseUrl
189
+ });
190
+ const sourceWorkspace = path2.join(runtime2.processWorkspacesDir, ref.id);
191
+ return {
192
+ ref,
193
+ baseDir: path2.join(sourceWorkspace, ".leitwerk", "process-analysis", input.analysisProcessId)
194
+ };
195
+ }
196
+ async function downloadProcessSnapshot(input) {
197
+ const { baseDir, ref } = resolveProcessSnapshotDirectory(input);
198
+ const detail = await fetchJson(ref.apiUrl);
199
+ const primaryPath = await fetchJson(`${ref.apiUrl}/primary-path`);
200
+ await mkdir(baseDir, { recursive: true });
201
+ await writeJson(path2.join(baseDir, "process-detail.json"), detail);
202
+ await writeJson(path2.join(baseDir, "primary-path.json"), primaryPath);
203
+ await writeFile(
204
+ path2.join(baseDir, "summary.md"),
205
+ buildSummaryMarkdown({ detail, primaryPath, sourceUrl: ref.apiUrl }),
206
+ "utf8"
207
+ );
208
+ await writeFile(
209
+ path2.join(baseDir, "turn-records.md"),
210
+ buildRecordsMarkdown(
211
+ "Turn records",
212
+ detail.turnRecords ?? detail.turns ?? []
213
+ ),
214
+ "utf8"
215
+ );
216
+ await writeFile(
217
+ path2.join(baseDir, "events.md"),
218
+ buildRecordsMarkdown("Events", detail.events ?? []),
219
+ "utf8"
220
+ );
221
+ await writeFile(
222
+ path2.join(baseDir, "chronicle.md"),
223
+ jsonMarkdown("Chronicle", detail.chronicle ?? detail),
224
+ "utf8"
225
+ );
226
+ return {
227
+ sourceProcessId: ref.id,
228
+ apiUrl: ref.apiUrl,
229
+ snapshotDir: baseDir,
230
+ primaryPath,
231
+ downloadedAt: (/* @__PURE__ */ new Date()).toISOString()
232
+ };
233
+ }
234
+
235
+ // src/state.ts
236
+ import { parseStructuralProcessState } from "@leitwerk-dev/process-sdk";
237
+ function parseProcessAnalysisSnapshotState(value) {
238
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
239
+ const r = value;
240
+ if (typeof r.sourceProcessId !== "string" || typeof r.snapshotDir !== "string") return null;
241
+ return {
242
+ sourceProcessId: r.sourceProcessId,
243
+ apiUrl: typeof r.apiUrl === "string" ? r.apiUrl : "",
244
+ snapshotDir: r.snapshotDir,
245
+ primaryPath: r.primaryPath,
246
+ downloadedAt: typeof r.downloadedAt === "string" ? r.downloadedAt : ""
247
+ };
248
+ }
249
+ var processAnalysisStateCodec = {
250
+ parse(value) {
251
+ const r = typeof value === "object" && value !== null ? value : {};
252
+ return {
253
+ ...parseStructuralProcessState(r),
254
+ snapshot: parseProcessAnalysisSnapshotState(r.snapshot)
255
+ };
256
+ },
257
+ serialize(value) {
258
+ return value;
259
+ }
260
+ };
261
+
262
+ // src/tools.ts
263
+ var processAnalysisDownloadSnapshotTool = "process_analysis_download_snapshot";
264
+ function parseArgs(value) {
265
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
266
+ throw new Error("Tool arguments must be an object");
267
+ }
268
+ const processRef = value.processRef;
269
+ if (typeof processRef !== "string" || !processRef.trim()) {
270
+ throw new Error("'processRef' must be a non-empty string");
271
+ }
272
+ return { processRef: processRef.trim() };
273
+ }
274
+ function registerProcessAnalysisTools(api) {
275
+ api.tool({
276
+ name: processAnalysisDownloadSnapshotTool,
277
+ description: "Download a durable snapshot of a process for read-only analysis",
278
+ parameters: {
279
+ type: "object",
280
+ properties: { processRef: { type: "string" } },
281
+ required: ["processRef"],
282
+ additionalProperties: false
16
283
  },
17
- setupServer(api) {
18
- const deps = api.get(coreHostCapabilities.serverSetup);
19
- if (deps && !Array.isArray(deps)) {
20
- configureProcessAnalysisRuntime({
21
- analysisCwd: path.resolve(process.cwd()),
22
- serverBaseUrl: deps.serverBaseUrl,
23
- processWorkspacesDir: deps.processWorkspacesDir ?? null,
24
- processLaunches: deps.processLaunches,
25
- });
26
- }
284
+ parse: parseArgs,
285
+ execute(ctx, args) {
286
+ return downloadProcessSnapshot({
287
+ analysisProcessId: ctx.process.id,
288
+ processRef: args.processRef
289
+ });
290
+ }
291
+ });
292
+ }
293
+
294
+ // src/process-definition.ts
295
+ var turnIds = {
296
+ analyzeProcess: "analyze_process",
297
+ analysisDecision: "analysis_decision"
298
+ };
299
+ var products = { analysis: "analysis" };
300
+ function analysisPrompt(ctx) {
301
+ const snapshot = ctx.prepared;
302
+ return [
303
+ "Analyze the referenced leitwerk process for the operator.",
304
+ "You are in read-only analysis mode. Use only read and bash inspection commands. Do not modify files.",
305
+ "Run from the server launch directory shown below. Code/repo inspection must happen only from that analysis directory. Limit process-specific evidence to the downloaded snapshot directory unless the operator asks for repository code inspection.",
306
+ `Original instruction:
307
+ ${ctx.params.instruction}`,
308
+ `Snapshot directory: ${snapshot.snapshotDir}
309
+ Analysis directory: ${ctx.params.analysisCwd}
310
+ Source: ${snapshot.apiUrl}`,
311
+ "Publish a concise analysis with: findings, evidence, likely root cause, and recommended next steps. If a repository change is needed, include implementation guidance suitable for handoff."
312
+ ].join("\n\n");
313
+ }
314
+ var analyzeTurn = flow.llm(turnIds.analyzeProcess).description("Analyze process").integrationTools(processAnalysisDownloadSnapshotTool).prepare(async (ctx) => {
315
+ ctx.reportProgress({
316
+ title: "Analysis preparation",
317
+ steps: [
318
+ { id: "download_snapshot", label: "Download process snapshot", status: "in_progress" }
319
+ ]
320
+ });
321
+ const result = await ctx.callIntegrationTool(processAnalysisDownloadSnapshotTool, {
322
+ processRef: ctx.params.processRef
323
+ });
324
+ const snapshot = parseProcessAnalysisSnapshotState(result);
325
+ if (!snapshot) throw new Error("Snapshot tool returned an invalid process snapshot");
326
+ ctx.reportProgress({
327
+ title: "Analysis preparation",
328
+ steps: [{ id: "download_snapshot", label: "Download process snapshot", status: "completed" }]
329
+ });
330
+ return snapshot;
331
+ }).tools("read", "bash").freshPrimary().buildPrompt(analysisPrompt).publish(products.analysis).to(turnIds.analysisDecision);
332
+ var reviseAnalysis = (label) => revisionAction({
333
+ label,
334
+ acceptanceState: "neutral",
335
+ form: followupForm,
336
+ to: turnIds.analyzeProcess,
337
+ queueTarget: { productName: products.analysis },
338
+ schedulable: true
339
+ });
340
+ var decisionTurn = humanTurn({
341
+ description: "Review process analysis",
342
+ reviewProduct: products.analysis,
343
+ commentary: "Ask follow-up questions, refine the analysis, or refresh the snapshot.",
344
+ actions: {
345
+ [processAnalysisActionIds.completeAnalysis]: {
346
+ label: "Complete analysis",
347
+ acceptanceState: "accepted",
348
+ complete: true
27
349
  },
350
+ [processAnalysisActionIds.askFollowup]: reviseAnalysis("Ask follow-up"),
351
+ [processAnalysisActionIds.refineAnalysis]: reviseAnalysis("Refine analysis"),
352
+ [processAnalysisActionIds.refreshSnapshot]: {
353
+ label: "Refresh snapshot",
354
+ acceptanceState: "neutral",
355
+ to: turnIds.analyzeProcess
356
+ }
357
+ }
358
+ });
359
+ function createProcessAnalysisProcess() {
360
+ return flow.process("process_analysis_process").displayName("Process Analysis").entry(turnIds.analyzeProcess).codecs({ params: processAnalysisParamsCodec, state: processAnalysisStateCodec }).piConfig({ sessionCwdTemplate: "{{{analysisCwd}}}" }).initialState(() => ({
361
+ ...createEmptyStructuralProcessState(),
362
+ snapshot: null
363
+ })).turn(analyzeTurn).turn({ id: turnIds.analysisDecision, definition: decisionTurn }).server((api) => {
364
+ api.onCleanup(async (ctx) => {
365
+ let snapshotDir = ctx.state.snapshot?.snapshotDir ?? null;
366
+ if (!snapshotDir) {
367
+ try {
368
+ snapshotDir = resolveProcessSnapshotDirectory({
369
+ analysisProcessId: ctx.process.id,
370
+ processRef: ctx.params.processRef
371
+ }).baseDir;
372
+ } catch {
373
+ return { state: { ...ctx.state, snapshot: null } };
374
+ }
375
+ }
376
+ await rm(snapshotDir, { recursive: true, force: true });
377
+ return { state: { ...ctx.state, snapshot: null } };
378
+ });
379
+ }).launcher((api) => {
380
+ api.launcher({
381
+ id: "process_analysis_process.ui_launcher",
382
+ label: "Process Analysis",
383
+ description: "Download an leitwerk process snapshot and analyze it read-only.",
384
+ visibility: "ui",
385
+ ui: {
386
+ card: { title: "Process Analysis", description: "Analyze another process by id or URL." },
387
+ launchConfigSchema: {
388
+ id: "process_analysis_form",
389
+ title: "Process Analysis",
390
+ fields: [
391
+ {
392
+ id: "processRef",
393
+ label: "Process id or URL",
394
+ kind: "text",
395
+ required: true,
396
+ rememberRecentValues: true
397
+ },
398
+ { id: "instruction", label: "What to analyze", kind: "textarea", required: true }
399
+ ],
400
+ submitLabel: "Start analysis"
401
+ },
402
+ resolveDefaults() {
403
+ return { processRef: "", instruction: "" };
404
+ },
405
+ resolveLaunchConfig(input) {
406
+ const validated = validateProcessAnalysisLaunchInput(input);
407
+ if (!validated.ok) return { ok: false, errors: validated.errors };
408
+ const runtime2 = getProcessAnalysisRuntime();
409
+ return {
410
+ ok: true,
411
+ launchConfig: {
412
+ processId: "process_analysis_process",
413
+ params: { ...validated.value, analysisCwd: runtime2.analysisCwd },
414
+ startTurnId: turnIds.analyzeProcess,
415
+ titleSourceFields: [
416
+ { label: "Analysis instruction", value: validated.value.instruction }
417
+ ]
418
+ }
419
+ };
420
+ }
421
+ }
422
+ });
423
+ }).define();
424
+ }
425
+ var processAnalysisProcess = createProcessAnalysisProcess();
426
+ var processAnalysisTurnIds = turnIds;
427
+
428
+ // src/index.ts
429
+ var manifest = {
430
+ id: "process-analysis",
431
+ version: "0.1.0"
432
+ };
433
+ var processAnalysisExtension = {
434
+ manifest,
435
+ setupCatalog(api) {
436
+ api.registerProcess(processAnalysisProcess);
437
+ },
438
+ setupServer(api) {
439
+ const deps = api.get(coreHostCapabilities.serverSetup);
440
+ if (!deps || Array.isArray(deps)) return;
441
+ configureProcessAnalysisRuntime({
442
+ analysisCwd: path3.resolve(process.cwd()),
443
+ serverBaseUrl: deps.serverBaseUrl,
444
+ processWorkspacesDir: deps.processWorkspacesDir ?? null
445
+ });
446
+ registerProcessAnalysisTools(api);
447
+ }
448
+ };
449
+ var index_default = processAnalysisExtension;
450
+ export {
451
+ buildRecordsMarkdown,
452
+ buildSummaryMarkdown,
453
+ configureProcessAnalysisRuntime,
454
+ createProcessAnalysisProcess,
455
+ index_default as default,
456
+ downloadProcessSnapshot,
457
+ followupForm,
458
+ getProcessAnalysisRuntime,
459
+ jsonMarkdown,
460
+ manifest,
461
+ parseProcessAnalysisSnapshotState,
462
+ processAnalysisActionIds,
463
+ processAnalysisDownloadSnapshotTool,
464
+ processAnalysisParamsCodec,
465
+ processAnalysisProcess,
466
+ processAnalysisStateCodec,
467
+ processAnalysisTurnIds,
468
+ registerProcessAnalysisTools,
469
+ resolveProcessRef,
470
+ resolveProcessSnapshotDirectory,
471
+ validateProcessAnalysisLaunchInput
28
472
  };
29
- export default processAnalysisExtension;
30
- export * from "./actions.js";
31
- export * from "./params.js";
32
- export * from "./process-definition.js";
33
- export * from "./process-ref.js";
34
- export * from "./server-runtime.js";
35
- export * from "./snapshot-downloader.js";
36
- export * from "./snapshot-markdown.js";
37
- export * from "./state.js";
38
473
  //# sourceMappingURL=index.js.map