supipowers 2.1.0 → 2.2.1

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 (44) hide show
  1. package/README.md +71 -12
  2. package/package.json +4 -8
  3. package/skills/ui-design/SKILL.md +2 -2
  4. package/src/ai/final-message.ts +15 -1
  5. package/src/ai/schema-text.ts +60 -40
  6. package/src/ai/schema-validation.ts +88 -0
  7. package/src/ai/structured-output.ts +19 -19
  8. package/src/bootstrap.ts +3 -0
  9. package/src/commands/fix-pr.ts +166 -26
  10. package/src/commands/optimize-context.ts +153 -16
  11. package/src/commands/runbook.ts +511 -0
  12. package/src/config/schema.ts +102 -139
  13. package/src/context/rule-renderer.ts +274 -2
  14. package/src/context/runbook-extension-template.ts +193 -0
  15. package/src/context/startup-check.ts +197 -2
  16. package/src/context/startup-optimizer.ts +133 -10
  17. package/src/docs/contracts.ts +13 -23
  18. package/src/fix-pr/assessment.ts +63 -24
  19. package/src/fix-pr/contracts.ts +15 -23
  20. package/src/fix-pr/fetch-comments.ts +119 -0
  21. package/src/fix-pr/prompt-builder.ts +19 -8
  22. package/src/git/commit-contract.ts +13 -19
  23. package/src/git/commit.ts +168 -6
  24. package/src/harness/command.ts +98 -6
  25. package/src/harness/git-verification.ts +515 -0
  26. package/src/harness/git-verify-qa.ts +406 -0
  27. package/src/harness/pipeline.ts +17 -8
  28. package/src/harness/stages/implement-apply.ts +61 -4
  29. package/src/harness/stages/validate.ts +108 -0
  30. package/src/lsp/capabilities.ts +9 -12
  31. package/src/lsp/contracts.ts +15 -23
  32. package/src/planning/planning-ask-tool.ts +13 -2
  33. package/src/planning/spec.ts +21 -27
  34. package/src/planning/system-prompt.ts +1 -1
  35. package/src/planning/validate.ts +4 -7
  36. package/src/platform/progress.ts +11 -0
  37. package/src/quality/contracts.ts +15 -23
  38. package/src/quality/schemas.ts +40 -67
  39. package/src/release/contracts.ts +19 -28
  40. package/src/review/types.ts +142 -186
  41. package/src/types.ts +45 -2
  42. package/src/ui-design/session.ts +13 -2
  43. package/src/ui-design/system-prompt.ts +2 -2
  44. package/src/ultraplan/contracts.ts +458 -524
@@ -3,7 +3,7 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import type { Platform } from "../platform/types.js";
5
5
  import type { WorkspaceTarget } from "../types.js";
6
- import { buildWorkspaceTargetOptionLabel, parseTargetArg, selectWorkspaceTarget, stripCliArg, tokenizeCliArgs } from "../workspace/selector.js";
6
+ import { buildWorkspaceTargetOptionLabel, parseTargetArg, stripCliArg, tokenizeCliArgs } from "../workspace/selector.js";
7
7
  import { resolvePackageManager } from "../workspace/package-manager.js";
8
8
  import { resolveRepoRoot } from "../workspace/repo-root.js";
9
9
  import { discoverWorkspaceTargets } from "../workspace/targets.js";
@@ -31,6 +31,45 @@ import { loadModelConfig } from "../config/model-config.js";
31
31
  import { detectBotReviewers } from "../fix-pr/bot-detector.js";
32
32
  import { runFixPrAssessment, groupAssessmentsIntoBatches } from "../fix-pr/assessment.js";
33
33
  import { updateFixPrSession } from "../storage/fix-pr-sessions.js";
34
+ import { createWorkflowProgress } from "../platform/progress.js";
35
+
36
+
37
+ const FIX_PR_ASSESSMENT_TIMEOUT_MS = 5 * 60 * 1_000;
38
+ const FIX_PR_ASSESSMENT_COMMENTS_PER_BATCH = 12;
39
+
40
+ const FIX_PR_STEPS = [
41
+ { key: "fetch-comments", label: "Fetch PR comments" },
42
+ { key: "select-target", label: "Select target" },
43
+ { key: "prepare-session", label: "Prepare session" },
44
+ { key: "llm-assessment", label: "LLM assessment" },
45
+ { key: "send-prompt", label: "Send fix prompt" },
46
+ ] as const;
47
+
48
+ function createFixPrProgress(ctx: any) {
49
+ const progress = createWorkflowProgress(ctx.ui, {
50
+ title: "supi:fix-pr",
51
+ statusKey: "supi-fix-pr",
52
+ statusLabel: "Fixing PR...",
53
+ widgetKey: "supi-fix-pr",
54
+ clearStatusKeys: ["supi-model"],
55
+ steps: [...FIX_PR_STEPS],
56
+ });
57
+
58
+ return {
59
+ activate(stepIndex: number, detail?: string): void {
60
+ progress.activate(FIX_PR_STEPS[stepIndex]!.key, detail);
61
+ },
62
+ complete(stepIndex: number, detail?: string): void {
63
+ progress.complete(FIX_PR_STEPS[stepIndex]!.key, detail);
64
+ },
65
+ fail(stepIndex: number, detail?: string): void {
66
+ progress.fail(FIX_PR_STEPS[stepIndex]!.key, detail);
67
+ },
68
+ dispose(): void {
69
+ progress.dispose();
70
+ },
71
+ };
72
+ }
34
73
 
35
74
  modelRegistry.register({
36
75
  id: "fix-pr",
@@ -47,6 +86,7 @@ modelRegistry.register({
47
86
  harnessRoleHint: "default",
48
87
  });
49
88
 
89
+
50
90
  function getScriptsDir(): string {
51
91
  return path.join(moduleDir(import.meta.url), "..", "fix-pr", "scripts");
52
92
  }
@@ -91,6 +131,12 @@ function formatUnscopedCommentCount(count: number): string {
91
131
  return `${formatCommentCount(count)} without file path`;
92
132
  }
93
133
 
134
+ type FixPrSelectedTarget =
135
+ | { kind: "workspace"; target: WorkspaceTarget }
136
+ | { kind: "all"; target: WorkspaceTarget };
137
+
138
+ const ALL_FIX_PR_TARGET_ID = "all";
139
+
94
140
  function buildCommentTargetOptions(
95
141
  targets: readonly WorkspaceTarget[],
96
142
  commentsByTargetId: ReadonlyMap<string, readonly PrComment[]>,
@@ -109,6 +155,43 @@ function buildCommentTargetOptions(
109
155
  });
110
156
  }
111
157
 
158
+ function createAllCommentsTarget(repoRoot: string, packageManager: WorkspaceTarget["packageManager"]): WorkspaceTarget {
159
+ return {
160
+ id: ALL_FIX_PR_TARGET_ID,
161
+ name: "all",
162
+ kind: "workspace",
163
+ repoRoot,
164
+ packageDir: repoRoot,
165
+ manifestPath: path.join(repoRoot, "package.json"),
166
+ relativeDir: ALL_FIX_PR_TARGET_ID,
167
+ version: "0.0.0",
168
+ private: true,
169
+ packageManager,
170
+ };
171
+ }
172
+
173
+ function describeFixPrSelectedTarget(selected: FixPrSelectedTarget): string {
174
+ return selected.kind === "all" ? "all targets" : describeTarget(selected.target);
175
+ }
176
+
177
+ function getSelectedTargetComments(
178
+ selected: FixPrSelectedTarget,
179
+ commentsByTargetId: ReadonlyMap<string, readonly PrComment[]>,
180
+ unscopedComments: readonly PrComment[],
181
+ ): readonly PrComment[] {
182
+ if (selected.kind === "workspace") {
183
+ return commentsByTargetId.get(selected.target.id) ?? [];
184
+ }
185
+
186
+ const comments: PrComment[] = [];
187
+ for (const targetComments of commentsByTargetId.values()) {
188
+ comments.push(...targetComments);
189
+ }
190
+ comments.push(...unscopedComments);
191
+ return comments;
192
+ }
193
+
194
+
112
195
  function countUnresolvedAssessments(assessment: FixPrAssessmentBatch): number {
113
196
  return assessment.assessments.filter((item: FixPrAssessmentBatch["assessments"][number]) => item.verdict !== "apply").length;
114
197
  }
@@ -211,14 +294,18 @@ export function registerFixPrCommand(platform: Platform): void {
211
294
  return;
212
295
  }
213
296
 
297
+ const progress = createFixPrProgress(ctx);
214
298
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "supi-fix-pr-"));
215
299
  try {
300
+ progress.activate(0, `PR #${prNumber}`);
216
301
  const fetchedCommentsPath = path.join(tempDir, "comments.jsonl");
217
302
  const fetchError = await fetchPrComments(platform, repo, prNumber, fetchedCommentsPath, repoRoot);
218
303
  if (fetchError) {
304
+ progress.fail(0, "failed");
219
305
  notifyError(ctx, "Failed to fetch PR comments", fetchError);
220
306
  return;
221
307
  }
308
+ progress.complete(0, `PR #${prNumber}`);
222
309
 
223
310
  const fetchedComments = fs.readFileSync(fetchedCommentsPath, "utf-8").trim();
224
311
  if (!fetchedComments) {
@@ -238,36 +325,74 @@ export function registerFixPrCommand(platform: Platform): void {
238
325
  clusteredComments.commentsByTargetId,
239
326
  );
240
327
 
241
- if (targetOptions.length === 0) {
242
- const detail = clusteredComments.unscopedComments.length > 0
243
- ? `PR comments were fetched but only ${formatUnscopedCommentCount(clusteredComments.unscopedComments.length)} could not be assigned to a workspace target`
244
- : "PR comments were fetched but could not be assigned to a package or root target";
245
- notifyWarning(ctx, "No actionable comments found", detail);
328
+ const allTarget = createAllCommentsTarget(repoRoot, packageManager.id);
329
+ const allOption = {
330
+ target: allTarget,
331
+ changed: true,
332
+ label: buildWorkspaceTargetOptionLabel(
333
+ { target: allTarget, changed: true },
334
+ [formatCommentCount(parsedComments.length)],
335
+ ),
336
+ };
337
+
338
+ if (targetOptions.length === 0 && clusteredComments.unscopedComments.length === 0) {
339
+ notifyWarning(ctx, "No actionable comments found", "PR comments were fetched but could not be assigned to a package or root target");
246
340
  return;
247
341
  }
248
342
 
249
- if (!requestedTarget && !ctx.hasUI && targetOptions.length > 1) {
250
- notifyError(ctx, "Multiple comment targets found", buildAvailableTargetDetail(targetOptions, clusteredComments.unscopedComments.length));
251
- return;
343
+ progress.activate(1, `${formatCommentCount(parsedComments.length)}`);
344
+ let selected: FixPrSelectedTarget | null = null;
345
+ if (requestedTarget === ALL_FIX_PR_TARGET_ID) {
346
+ selected = { kind: "all", target: allTarget };
347
+ } else if (requestedTarget) {
348
+ const target = targetOptions
349
+ .map((option) => option.target)
350
+ .find((optionTarget) => optionTarget.id === requestedTarget || optionTarget.name === requestedTarget);
351
+ selected = target ? { kind: "workspace", target } : null;
352
+ } else if (!ctx.hasUI) {
353
+ selected = { kind: "all", target: allTarget };
354
+ } else {
355
+ const labels = [
356
+ allOption.label,
357
+ ...targetOptions.map((option) => option.label ?? buildWorkspaceTargetOptionLabel(option)),
358
+ ];
359
+ const choice = await ctx.ui.select("Fix-PR target", labels, {
360
+ helpText: "Select all comments or one target to process for this run",
361
+ });
362
+ if (!choice) {
363
+ progress.fail(1, "cancelled");
364
+ return;
365
+ }
366
+ const selectedIndex = labels.indexOf(choice);
367
+ selected = selectedIndex === 0
368
+ ? { kind: "all", target: allTarget }
369
+ : targetOptions[selectedIndex - 1]
370
+ ? { kind: "workspace", target: targetOptions[selectedIndex - 1].target }
371
+ : null;
252
372
  }
253
373
 
254
- const selectedTarget = await selectWorkspaceTarget(ctx, targetOptions, requestedTarget, {
255
- title: "Fix-PR target",
256
- helpText: "Select one target to process for this run",
257
- });
258
- if (!selectedTarget) {
374
+ if (!selected) {
259
375
  if (requestedTarget) {
260
376
  notifyError(ctx, "Target has no review comments", buildAvailableTargetDetail(targetOptions, clusteredComments.unscopedComments.length));
261
377
  }
378
+ progress.fail(1, "empty");
262
379
  return;
263
380
  }
381
+ progress.complete(1, describeFixPrSelectedTarget(selected));
264
382
 
265
- const selectedComments = clusteredComments.commentsByTargetId.get(selectedTarget.id) ?? [];
383
+ const selectedTarget = selected.target;
384
+ const selectedComments = getSelectedTargetComments(
385
+ selected,
386
+ clusteredComments.commentsByTargetId,
387
+ clusteredComments.unscopedComments,
388
+ );
266
389
  if (selectedComments.length === 0) {
267
390
  notifyInfo(ctx, "No comments for selected target", `${selectedTarget.id} has no actionable comments in this PR snapshot`);
268
391
  return;
269
392
  }
270
393
 
394
+ progress.activate(2, `${formatCommentCount(selectedComments.length)}`);
395
+
271
396
  let activeSession = findActiveFixPrSession(platform.paths, selectedTarget, repo, prNumber);
272
397
  if (activeSession && ctx.hasUI) {
273
398
  const choice = await ctx.ui.select(
@@ -278,7 +403,10 @@ export function registerFixPrCommand(platform: Platform): void {
278
403
  ],
279
404
  { helpText: "Select session · Esc to cancel" },
280
405
  );
281
- if (!choice) return;
406
+ if (!choice) {
407
+ progress.fail(2, "cancelled");
408
+ return;
409
+ }
282
410
  if (choice.startsWith("Start new")) activeSession = null;
283
411
  }
284
412
 
@@ -328,12 +456,17 @@ export function registerFixPrCommand(platform: Platform): void {
328
456
 
329
457
  const taskResolved = resolveModelForAction("task", modelRegistry, modelConfig, bridge);
330
458
  const taskModel = taskResolved.model ?? resolved.model ?? "claude-sonnet-4-6";
331
- const deferredCommentsSummary = buildDeferredCommentsSummary(
332
- targetOptions,
333
- clusteredComments.commentsByTargetId,
334
- selectedTarget,
335
- clusteredComments.unscopedComments.length,
336
- );
459
+ const deferredCommentsSummary = selected.kind === "all"
460
+ ? null
461
+ : buildDeferredCommentsSummary(
462
+ targetOptions,
463
+ clusteredComments.commentsByTargetId,
464
+ selectedTarget,
465
+ clusteredComments.unscopedComments.length,
466
+ );
467
+ progress.complete(2, activeSession ? `resume ${ledger.id}` : `new ${ledger.id}`);
468
+
469
+ progress.activate(3, `${formatCommentCount(selectedComments.length)}`);
337
470
 
338
471
  const assessmentResult = await runFixPrAssessment({
339
472
  createAgentSession: platform.createAgentSession,
@@ -342,17 +475,22 @@ export function registerFixPrCommand(platform: Platform): void {
342
475
  comments: selectedComments,
343
476
  repo,
344
477
  prNumber,
345
- selectedTargetLabel: describeTarget(selectedTarget),
478
+ selectedTargetLabel: describeFixPrSelectedTarget(selected),
346
479
  model: resolved.model,
347
480
  thinkingLevel: resolved.thinkingLevel,
481
+ timeoutMs: FIX_PR_ASSESSMENT_TIMEOUT_MS,
482
+ maxCommentsPerBatch: FIX_PR_ASSESSMENT_COMMENTS_PER_BATCH,
348
483
  });
349
484
  if (assessmentResult.status === "blocked") {
485
+ progress.fail(3, "blocked");
350
486
  notifyError(ctx, "Fix-PR assessment failed", assessmentResult.error);
351
487
  return;
352
488
  }
489
+ progress.complete(3, `${formatCommentCount(assessmentResult.output.assessments.length)} assessed`);
353
490
  const assessment = assessmentResult.output;
354
491
  const unresolvedAssessmentCount = countUnresolvedAssessments(assessment);
355
492
  const workBatches = groupAssessmentsIntoBatches(assessment);
493
+ progress.activate(4, `${workBatches.length} batch${workBatches.length === 1 ? "" : "es"}`);
356
494
  ledger.assessment = assessment;
357
495
  updateFixPrSession(platform.paths, selectedTarget, ledger);
358
496
 
@@ -360,7 +498,7 @@ export function registerFixPrCommand(platform: Platform): void {
360
498
  notifyWarning(
361
499
  ctx,
362
500
  "Unresolved comments remain",
363
- `${formatCommentCount(unresolvedAssessmentCount)} for ${describeTarget(selectedTarget)} still need rejection or investigation handling before this run can be considered complete.`,
501
+ `${formatCommentCount(unresolvedAssessmentCount)} for ${describeFixPrSelectedTarget(selected)} still need rejection or investigation handling before this run can be considered complete.`,
364
502
  );
365
503
  }
366
504
 
@@ -374,7 +512,7 @@ export function registerFixPrCommand(platform: Platform): void {
374
512
  iteration: ledger.iteration,
375
513
  skillContent,
376
514
  taskModel,
377
- selectedTargetLabel: describeTarget(selectedTarget),
515
+ selectedTargetLabel: describeFixPrSelectedTarget(selected),
378
516
  deferredCommentsSummary,
379
517
  assessment,
380
518
  workBatches,
@@ -388,14 +526,16 @@ export function registerFixPrCommand(platform: Platform): void {
388
526
  },
389
527
  { deliverAs: "steer", triggerTurn: true },
390
528
  );
529
+ progress.complete(4, "sent");
391
530
 
392
- const detailParts = [`${formatCommentCount(selectedComments.length)} for ${describeTarget(selectedTarget)}`];
531
+ const detailParts = [`${formatCommentCount(selectedComments.length)} for ${describeFixPrSelectedTarget(selected)}`];
393
532
  if (deferredCommentsSummary) {
394
533
  detailParts.push(`deferred: ${deferredCommentsSummary}`);
395
534
  }
396
535
  notifyInfo(ctx, `Fix-PR started: PR #${prNumber}`, `${detailParts.join(" | ")} | session ${ledger.id}`);
397
536
  } finally {
398
537
  fs.rmSync(tempDir, { recursive: true, force: true });
538
+ progress.dispose();
399
539
  }
400
540
  },
401
541
  });
@@ -18,9 +18,11 @@ import {
18
18
  import type {
19
19
  ManualOptimizationAction,
20
20
  OptimizationPlan,
21
+ WriteCommandAction,
21
22
  WriteRuleAction,
23
+ WriteExtensionAction,
22
24
  } from "../context/startup-optimizer.js";
23
- import { parseManagedRule, renderManagedRule } from "../context/rule-renderer.js";
25
+ import { parseManagedCommand, parseManagedExtension, parseManagedRule, renderManagedCommand, renderManagedExtension, renderManagedRule } from "../context/rule-renderer.js";
24
26
  import { DEFAULT_TOKENIGNORE_ENTRIES, mergeManagedTokenignore } from "../context/tokenignore.js";
25
27
  import {
26
28
  parseStartupOptimizerManifest,
@@ -142,6 +144,20 @@ async function runCheck(
142
144
  }
143
145
  }
144
146
 
147
+ const commandFiles: Record<string, string | null> = {};
148
+ if (manifest) {
149
+ for (const command of manifest.commands) {
150
+ commandFiles[command.path] = readOptionalFile(path.join(ctx.cwd, command.path));
151
+ }
152
+ }
153
+
154
+ const extensionFiles: Record<string, string | null> = {};
155
+ if (manifest) {
156
+ for (const extension of manifest.extensions) {
157
+ extensionFiles[extension.path] = readOptionalFile(path.join(ctx.cwd, extension.path));
158
+ }
159
+ }
160
+
145
161
  const currentSkills: ParsedSkill[] = currentPrompt ? parseIndividualSkills(currentPrompt) : [];
146
162
  const currentSections: PromptSection[] = currentPrompt ? parseSystemPrompt(currentPrompt) : [];
147
163
 
@@ -149,6 +165,8 @@ async function runCheck(
149
165
  manifestPath,
150
166
  manifestText,
151
167
  ruleFiles,
168
+ commandFiles,
169
+ extensionFiles,
152
170
  tokenignorePath,
153
171
  tokenignoreText: readOptionalFile(tokenignorePath),
154
172
  currentPrompt,
@@ -232,17 +250,23 @@ async function showDryRun(ctx: PlatformContext, plan: OptimizationPlan): Promise
232
250
 
233
251
  function buildPlanPreview(plan: OptimizationPlan): string[] {
234
252
  const writeRuleCount = plan.actions.filter((action) => action.kind === "write-rule").length;
235
- const manualCount = plan.actions.filter((action) => action.kind !== "write-rule").length;
253
+ const writeCommandCount = plan.actions.filter((action) => action.kind === "write-command").length;
254
+ const writeExtensionCount = plan.actions.filter((action) => action.kind === "write-extension").length;
255
+ const manualCount = plan.actions.filter((action) => action.kind !== "write-rule" && action.kind !== "write-command" && action.kind !== "write-extension").length;
236
256
  const lines = [
237
257
  `Source set: ${plan.sourceSetHash.slice(0, 12)}`,
238
258
  `Current: ~${formatTokens(Math.ceil(plan.beforeBytes / 4))} tokens | Estimated after planned removals: ~${formatTokens(Math.ceil(plan.estimatedAfterBytes / 4))} tokens`,
239
- `Actions: ${writeRuleCount} write-rule, ${manualCount} manual`,
259
+ `Actions: ${writeRuleCount} write-rule, ${writeCommandCount} write-command, ${writeExtensionCount} write-extension, ${manualCount} manual`,
240
260
  "",
241
261
  ];
242
262
 
243
263
  for (const action of plan.actions) {
244
264
  if (action.kind === "write-rule") {
245
265
  lines.push(`write-rule ${action.mode}: ${action.targetPath}`);
266
+ } else if (action.kind === "write-command") {
267
+ lines.push(`write-command: /${action.commandName} -> ${action.targetPath}`);
268
+ } else if (action.kind === "write-extension") {
269
+ lines.push(`write-extension: ${action.extensionName} -> ${action.targetPath}`);
246
270
  } else if (action.kind === "manual-disable") {
247
271
  lines.push(`manual-disable ${action.sourceName}: ${action.reason}`);
248
272
  } else {
@@ -268,9 +292,14 @@ async function applyOptimizationPlan(
268
292
  }
269
293
 
270
294
  const writeRules = plan.actions.filter((action): action is WriteRuleAction => action.kind === "write-rule");
271
- const preflight = preflightRuleWrites(ctx.cwd, writeRules);
272
- if (preflight.conflicts.length > 0) {
273
- ctx.ui.notify(`Apply blocked: ${preflight.conflicts.join("; ")}`, "error");
295
+ const writeCommands = plan.actions.filter((action): action is WriteCommandAction => action.kind === "write-command");
296
+ const writeExtensions = plan.actions.filter((action): action is WriteExtensionAction => action.kind === "write-extension");
297
+ const rulePreflight = preflightRuleWrites(ctx.cwd, writeRules);
298
+ const commandPreflight = preflightCommandWrites(ctx.cwd, writeCommands);
299
+ const extensionPreflight = preflightExtensionWrites(ctx.cwd, writeExtensions);
300
+ const preflightConflicts = [...rulePreflight.conflicts, ...commandPreflight.conflicts, ...extensionPreflight.conflicts];
301
+ if (preflightConflicts.length > 0) {
302
+ ctx.ui.notify(`Apply blocked: ${preflightConflicts.join("; ")}`, "error");
274
303
  return;
275
304
  }
276
305
 
@@ -279,7 +308,7 @@ async function applyOptimizationPlan(
279
308
  return;
280
309
  }
281
310
 
282
- const summary = buildApplySummary(plan, preflight.updates);
311
+ const summary = buildApplySummary(plan, [...rulePreflight.updates, ...commandPreflight.updates, ...extensionPreflight.updates]);
283
312
  const accepted = await confirmApply(ctx, summary);
284
313
  if (!accepted) {
285
314
  ctx.ui.notify("Apply cancelled.", "info");
@@ -299,6 +328,18 @@ async function applyOptimizationPlan(
299
328
  fs.writeFileSync(target, renderManagedRule(action));
300
329
  }
301
330
 
331
+ for (const action of writeCommands) {
332
+ const target = absoluteRulePath(ctx.cwd, action.targetPath);
333
+ fs.mkdirSync(path.dirname(target), { recursive: true });
334
+ fs.writeFileSync(target, renderManagedCommand(action));
335
+ }
336
+
337
+ for (const action of writeExtensions) {
338
+ const target = absoluteRulePath(ctx.cwd, action.targetPath);
339
+ fs.mkdirSync(path.dirname(target), { recursive: true });
340
+ fs.writeFileSync(target, renderManagedExtension(action));
341
+ }
342
+
302
343
  fs.mkdirSync(path.dirname(tokenignorePath), { recursive: true });
303
344
  fs.writeFileSync(tokenignorePath, tokenignore.content);
304
345
 
@@ -315,7 +356,7 @@ async function applyOptimizationPlan(
315
356
  // process can't see the just-written .omp/rules without a full restart.
316
357
  // Be honest about this rather than silently calling reload() and lying.
317
358
  ctx.ui.notify(
318
- "Applied deterministic context migration. Restart OMP so the new managed rules in .omp/rules are picked up by rule discovery, then disable the original sources and run /supi:optimize-context --check to validate runtime savings.",
359
+ "Applied deterministic context migration. Restart OMP so new managed rules in .omp/rules, commands in .omp/commands, and the runbook extension in .omp/extensions are picked up by discovery, then disable the original sources and run /supi:optimize-context --check to validate runtime savings.",
319
360
  "info",
320
361
  );
321
362
  }
@@ -358,11 +399,73 @@ function preflightRuleWrites(
358
399
  conflicts.push(`${action.targetPath} is malformed: ${parsed.error}`);
359
400
  continue;
360
401
  }
361
- if (
362
- parsed.metadata.sourceHash !== action.sourceHash ||
363
- parsed.metadata.sourceId !== action.sourceId ||
364
- parsed.metadata.mode !== action.mode
365
- ) {
402
+ if (fs.readFileSync(target, "utf-8") !== renderManagedRule(action)) {
403
+ updates.push(action.targetPath);
404
+ }
405
+ }
406
+
407
+ return { conflicts, updates };
408
+ }
409
+
410
+ function preflightCommandWrites(
411
+ cwd: string,
412
+ actions: WriteCommandAction[],
413
+ ): { conflicts: string[]; updates: string[] } {
414
+ const conflicts: string[] = [];
415
+ const updates: string[] = [];
416
+
417
+ for (const action of actions) {
418
+ const target = absoluteRulePath(cwd, action.targetPath);
419
+ if (!fs.existsSync(target)) continue;
420
+ const stat = fs.statSync(target);
421
+ if (!stat.isFile()) {
422
+ conflicts.push(`${action.targetPath} exists and is not a file`);
423
+ continue;
424
+ }
425
+
426
+ const parsed = parseManagedCommand(fs.readFileSync(target, "utf-8"));
427
+ if (parsed.status === "unmanaged") {
428
+ conflicts.push(`${action.targetPath} is unmanaged`);
429
+ continue;
430
+ }
431
+ if (parsed.status === "malformed") {
432
+ conflicts.push(`${action.targetPath} is malformed: ${parsed.error}`);
433
+ continue;
434
+ }
435
+ if (fs.readFileSync(target, "utf-8") !== renderManagedCommand(action)) {
436
+ updates.push(action.targetPath);
437
+ }
438
+ }
439
+
440
+ return { conflicts, updates };
441
+ }
442
+
443
+ function preflightExtensionWrites(
444
+ cwd: string,
445
+ actions: WriteExtensionAction[],
446
+ ): { conflicts: string[]; updates: string[] } {
447
+ const conflicts: string[] = [];
448
+ const updates: string[] = [];
449
+
450
+ for (const action of actions) {
451
+ const target = absoluteRulePath(cwd, action.targetPath);
452
+ if (!fs.existsSync(target)) continue;
453
+ const stat = fs.statSync(target);
454
+ if (!stat.isFile()) {
455
+ conflicts.push(`${action.targetPath} exists and is not a file`);
456
+ continue;
457
+ }
458
+
459
+ const parsed = parseManagedExtension(fs.readFileSync(target, "utf-8"));
460
+ if (parsed.status === "unmanaged") {
461
+ conflicts.push(`${action.targetPath} is unmanaged`);
462
+ continue;
463
+ }
464
+ if (parsed.status === "malformed") {
465
+ conflicts.push(`${action.targetPath} is malformed: ${parsed.error}`);
466
+ continue;
467
+ }
468
+ if (fs.readFileSync(target, "utf-8") !== renderManagedExtension(action)) {
366
469
  updates.push(action.targetPath);
367
470
  }
368
471
  }
@@ -370,11 +473,16 @@ function preflightRuleWrites(
370
473
  return { conflicts, updates };
371
474
  }
372
475
 
476
+
373
477
  function buildApplySummary(plan: OptimizationPlan, updates: string[]): string {
374
478
  const writeRuleCount = plan.actions.filter((action) => action.kind === "write-rule").length;
375
- const manualCount = plan.actions.filter((action) => action.kind !== "write-rule").length;
479
+ const writeCommandCount = plan.actions.filter((action) => action.kind === "write-command").length;
480
+ const writeExtensionCount = plan.actions.filter((action) => action.kind === "write-extension").length;
481
+ const manualCount = plan.actions.filter((action) => action.kind !== "write-rule" && action.kind !== "write-command" && action.kind !== "write-extension").length;
376
482
  const lines = [
377
483
  `Write ${writeRuleCount} managed rule file${writeRuleCount === 1 ? "" : "s"}.`,
484
+ `Write ${writeCommandCount} managed command file${writeCommandCount === 1 ? "" : "s"}.`,
485
+ `Write ${writeExtensionCount} managed extension file${writeExtensionCount === 1 ? "" : "s"}.`,
378
486
  `Merge ${DEFAULT_TOKENIGNORE_ENTRIES.length} managed .tokenignore entries.`,
379
487
  `Record ${manualCount} manual follow-up action${manualCount === 1 ? "" : "s"}.`,
380
488
  `Estimated savings after planned removals: ~${formatTokens(Math.ceil(plan.estimatedSavedBytes / 4))} tokens.`,
@@ -382,7 +490,7 @@ function buildApplySummary(plan: OptimizationPlan, updates: string[]): string {
382
490
  if (updates.length > 0) {
383
491
  lines.push(`Managed update candidate${updates.length === 1 ? "" : "s"}: ${updates.join(", ")}`);
384
492
  }
385
- lines.push("Manifest is written last after managed rule and tokenignore writes succeed.");
493
+ lines.push("Manifest is written last after managed rule, command, extension, and tokenignore writes succeed.");
386
494
  return lines.join("\n");
387
495
  }
388
496
 
@@ -406,8 +514,35 @@ function buildManifest(plan: OptimizationPlan): StartupOptimizerManifest {
406
514
  slug: action.slug,
407
515
  sourceBytes: action.sourceBytes,
408
516
  ...(action.condition ? { condition: action.condition } : {}),
517
+ ...(action.triggers ? { triggers: action.triggers } : {}),
518
+ ...(action.scope ? { scope: action.scope } : {}),
409
519
  ...(action.description ? { description: action.description } : {}),
410
520
  }));
521
+ const commands = plan.actions
522
+ .filter((action): action is WriteCommandAction => action.kind === "write-command")
523
+ .map((action) => ({
524
+ path: action.targetPath,
525
+ sourceId: action.sourceId,
526
+ sourceName: action.sourceName,
527
+ sourceHash: action.sourceHash,
528
+ slug: action.slug,
529
+ commandName: action.commandName,
530
+ sourceBytes: action.sourceBytes,
531
+ ...(action.description ? { description: action.description } : {}),
532
+ }));
533
+ const extensions = plan.actions
534
+ .filter((action): action is WriteExtensionAction => action.kind === "write-extension")
535
+ .map((action) => ({
536
+ path: action.targetPath,
537
+ sourceId: action.sourceId,
538
+ sourceName: action.sourceName,
539
+ sourceHash: action.sourceHash,
540
+ slug: action.slug,
541
+ extensionName: action.extensionName,
542
+ sourceBytes: action.sourceBytes,
543
+ }));
544
+
545
+
411
546
 
412
547
  return {
413
548
  version: 1,
@@ -417,12 +552,14 @@ function buildManifest(plan: OptimizationPlan): StartupOptimizerManifest {
417
552
  estimatedAfterBytes: plan.estimatedAfterBytes,
418
553
  estimatedSavedBytes: plan.estimatedSavedBytes,
419
554
  rules,
555
+ commands,
556
+ extensions,
420
557
  tokenignore: {
421
558
  path: ".omp/supipowers/.tokenignore",
422
559
  entries: tokenignore.entries,
423
560
  hash: tokenignore.hash,
424
561
  },
425
- manualActions: plan.actions.filter((action): action is ManualOptimizationAction => action.kind !== "write-rule"),
562
+ manualActions: plan.actions.filter((action): action is ManualOptimizationAction => action.kind !== "write-rule" && action.kind !== "write-command" && action.kind !== "write-extension"),
426
563
  };
427
564
  }
428
565