opencastle 1.4.2 → 1.5.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 (128) hide show
  1. package/dist/cli/bootstrap-on-init.test.js +5 -5
  2. package/dist/cli/bootstrap-on-init.test.js.map +1 -1
  3. package/dist/cli/bootstrap.d.ts +17 -0
  4. package/dist/cli/bootstrap.d.ts.map +1 -1
  5. package/dist/cli/bootstrap.js +284 -312
  6. package/dist/cli/bootstrap.js.map +1 -1
  7. package/dist/cli/bootstrap.test.js +22 -16
  8. package/dist/cli/bootstrap.test.js.map +1 -1
  9. package/dist/cli/convoy/engine.d.ts.map +1 -1
  10. package/dist/cli/convoy/engine.js +8 -2
  11. package/dist/cli/convoy/engine.js.map +1 -1
  12. package/dist/cli/convoy/spec-types.d.ts +15 -0
  13. package/dist/cli/convoy/spec-types.d.ts.map +1 -1
  14. package/dist/cli/detect.d.ts +4 -0
  15. package/dist/cli/detect.d.ts.map +1 -1
  16. package/dist/cli/detect.js +1 -1
  17. package/dist/cli/detect.js.map +1 -1
  18. package/dist/cli/doctor.js +4 -4
  19. package/dist/cli/doctor.js.map +1 -1
  20. package/dist/cli/init.test.js +4 -5
  21. package/dist/cli/init.test.js.map +1 -1
  22. package/dist/cli/log.d.ts +2 -2
  23. package/dist/cli/log.d.ts.map +1 -1
  24. package/dist/cli/log.js +1 -1
  25. package/dist/cli/log.js.map +1 -1
  26. package/dist/cli/log.test.js +1 -1
  27. package/dist/cli/log.test.js.map +1 -1
  28. package/dist/cli/managed-paths.d.ts +1 -1
  29. package/dist/cli/managed-paths.d.ts.map +1 -1
  30. package/dist/cli/managed-paths.js +0 -1
  31. package/dist/cli/managed-paths.js.map +1 -1
  32. package/dist/cli/pipeline.d.ts.map +1 -1
  33. package/dist/cli/pipeline.flow.test.js +134 -27
  34. package/dist/cli/pipeline.flow.test.js.map +1 -1
  35. package/dist/cli/pipeline.js +113 -34
  36. package/dist/cli/pipeline.js.map +1 -1
  37. package/dist/cli/plan.d.ts +22 -0
  38. package/dist/cli/plan.d.ts.map +1 -1
  39. package/dist/cli/plan.js +43 -6
  40. package/dist/cli/plan.js.map +1 -1
  41. package/dist/cli/project-facts.d.ts +103 -0
  42. package/dist/cli/project-facts.d.ts.map +1 -0
  43. package/dist/cli/project-facts.js +577 -0
  44. package/dist/cli/project-facts.js.map +1 -0
  45. package/dist/cli/project-facts.test.d.ts +2 -0
  46. package/dist/cli/project-facts.test.d.ts.map +1 -0
  47. package/dist/cli/project-facts.test.js +209 -0
  48. package/dist/cli/project-facts.test.js.map +1 -0
  49. package/dist/cli/run/adapters/claude.d.ts +13 -0
  50. package/dist/cli/run/adapters/claude.d.ts.map +1 -1
  51. package/dist/cli/run/adapters/claude.js +30 -1
  52. package/dist/cli/run/adapters/claude.js.map +1 -1
  53. package/dist/cli/run/adapters/claude.test.js +34 -1
  54. package/dist/cli/run/adapters/claude.test.js.map +1 -1
  55. package/dist/cli/run/adapters/codex.d.ts.map +1 -1
  56. package/dist/cli/run/adapters/codex.js +4 -0
  57. package/dist/cli/run/adapters/codex.js.map +1 -1
  58. package/dist/cli/run/adapters/codex.test.js +8 -0
  59. package/dist/cli/run/adapters/codex.test.js.map +1 -1
  60. package/dist/cli/run/adapters/copilot.d.ts.map +1 -1
  61. package/dist/cli/run/adapters/copilot.js +4 -1
  62. package/dist/cli/run/adapters/copilot.js.map +1 -1
  63. package/dist/cli/run/adapters/copilot.test.js +9 -0
  64. package/dist/cli/run/adapters/copilot.test.js.map +1 -1
  65. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts +2 -0
  66. package/dist/cli/run/adapters/stub-cli.test-helper.d.ts.map +1 -1
  67. package/dist/cli/run/adapters/stub-cli.test-helper.js +16 -1
  68. package/dist/cli/run/adapters/stub-cli.test-helper.js.map +1 -1
  69. package/dist/cli/run/platform.d.ts +12 -0
  70. package/dist/cli/run/platform.d.ts.map +1 -1
  71. package/dist/cli/run/platform.js +49 -0
  72. package/dist/cli/run/platform.js.map +1 -1
  73. package/dist/cli/run/platform.test.js +21 -1
  74. package/dist/cli/run/platform.test.js.map +1 -1
  75. package/dist/cli/stack-config.js +1 -1
  76. package/dist/cli/stack-config.js.map +1 -1
  77. package/package.json +1 -1
  78. package/src/cli/bootstrap-on-init.test.ts +5 -5
  79. package/src/cli/bootstrap.test.ts +22 -16
  80. package/src/cli/bootstrap.ts +361 -373
  81. package/src/cli/convoy/engine.ts +9 -2
  82. package/src/cli/convoy/spec-types.ts +15 -0
  83. package/src/cli/detect.ts +1 -1
  84. package/src/cli/doctor.ts +4 -4
  85. package/src/cli/init.test.ts +4 -5
  86. package/src/cli/log.test.ts +1 -1
  87. package/src/cli/log.ts +2 -2
  88. package/src/cli/managed-paths.ts +0 -1
  89. package/src/cli/pipeline.flow.test.ts +143 -28
  90. package/src/cli/pipeline.ts +141 -34
  91. package/src/cli/plan.ts +51 -6
  92. package/src/cli/project-facts.test.ts +228 -0
  93. package/src/cli/project-facts.ts +647 -0
  94. package/src/cli/run/adapters/claude.test.ts +39 -1
  95. package/src/cli/run/adapters/claude.ts +27 -1
  96. package/src/cli/run/adapters/codex.test.ts +9 -0
  97. package/src/cli/run/adapters/codex.ts +3 -0
  98. package/src/cli/run/adapters/copilot.test.ts +11 -0
  99. package/src/cli/run/adapters/copilot.ts +3 -1
  100. package/src/cli/run/adapters/stub-cli.test-helper.ts +16 -1
  101. package/src/cli/run/platform.test.ts +23 -1
  102. package/src/cli/run/platform.ts +50 -0
  103. package/src/cli/stack-config.ts +1 -1
  104. package/src/orchestrator/agent-workflows/data-pipeline.md +2 -2
  105. package/src/orchestrator/agent-workflows/feature-implementation.md +1 -1
  106. package/src/orchestrator/agent-workflows/schema-changes.md +1 -1
  107. package/src/orchestrator/agents/team-lead.agent.md +1 -1
  108. package/src/orchestrator/customizations/README.md +27 -84
  109. package/src/orchestrator/prompts/bootstrap-customizations.prompt.md +38 -238
  110. package/src/orchestrator/prompts/brainstorm.prompt.md +1 -1
  111. package/src/orchestrator/prompts/implement-feature.prompt.md +6 -6
  112. package/src/orchestrator/skills/agent-memory/KNOWLEDGE-GRAPH.md +1 -1
  113. package/src/orchestrator/skills/agent-memory/SKILL.md +7 -16
  114. package/src/orchestrator/skills/documentation-standards/SKILL.md +1 -1
  115. package/src/orchestrator/skills/observability-logging/SKILL.md +1 -1
  116. package/src/orchestrator/skills/panel-majority-vote/REFERENCE.md +1 -1
  117. package/src/orchestrator/skills/team-lead-reference/SKILL.md +2 -2
  118. package/src/orchestrator/customizations/AGENT-EXPERTISE.md +0 -325
  119. package/src/orchestrator/customizations/AGENT-FAILURES.md +0 -69
  120. package/src/orchestrator/customizations/AGENT-PERFORMANCE.md +0 -55
  121. package/src/orchestrator/customizations/DISPUTES.md +0 -162
  122. package/src/orchestrator/customizations/KNOWLEDGE-GRAPH.md +0 -10
  123. package/src/orchestrator/customizations/agents/skill-matrix.md +0 -111
  124. package/src/orchestrator/customizations/logs/events.ndjson +0 -0
  125. package/src/orchestrator/customizations/project/decisions.md +0 -31
  126. package/src/orchestrator/customizations/project/docs-structure.md +0 -34
  127. package/src/orchestrator/customizations/project/roadmap.md +0 -24
  128. /package/src/orchestrator/{customizations/logs/README.md → skills/observability-logging/LOG-SCHEMA.md} +0 -0
@@ -1,9 +1,9 @@
1
- import { readFile, writeFile, mkdir } from 'node:fs/promises'
1
+ import { readFile, writeFile, mkdir, rm, rmdir } from 'node:fs/promises'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { createHash } from 'node:crypto'
4
- import { resolve, relative, basename } from 'node:path'
4
+ import { resolve, relative, basename, dirname } from 'node:path'
5
5
  import { c, confirm, closePrompts } from './prompt.js'
6
- import { runPromptStep, freePath } from './plan.js'
6
+ import { runPromptStep, freePath, StepCancelled } from './plan.js'
7
7
  import type { PromptStepOptions, PromptStepResult } from './plan.js'
8
8
  import { resolveAdapter, cleanupAdapters, type ResolvedAdapter } from './run/adapters/index.js'
9
9
  import { findProjectRoot } from './convoy/read-model.js'
@@ -416,11 +416,19 @@ async function settleAll<T>(work: Array<Promise<T>>): Promise<T[]> {
416
416
  }
417
417
 
418
418
  /** generate-convoy, with the one retry an unreadable answer gets. */
419
- async function generatePlan(step: StepRunner, goal: string, context: string, label: string, convoyDir: string): Promise<TaskPlan> {
419
+ async function generatePlan(
420
+ step: StepRunner,
421
+ goal: string,
422
+ context: string,
423
+ label: string,
424
+ convoyDir: string,
425
+ signal?: AbortSignal,
426
+ onStart?: () => void,
427
+ ): Promise<TaskPlan> {
420
428
  let raw = ''
421
429
  let reason = ''
422
430
  for (let attempt = 1; attempt <= 2; attempt++) {
423
- raw = (await step('generate-convoy', { goalText: goal, contextText: context })).rawOutput
431
+ raw = (await step('generate-convoy', { goalText: goal, contextText: context, signal, onStart })).rawOutput
424
432
  const parsed = parseTaskPlanWithReason(raw)
425
433
  if (parsed.plan) return parsed.plan
426
434
  reason = parsed.reason ?? 'unreadable'
@@ -443,13 +451,55 @@ async function fixPlan(step: StepRunner, plan: TaskPlan, problems: string): Prom
443
451
  return normalizePlanFiles(applyPatches(plan, patches)).plan
444
452
  }
445
453
 
454
+ /**
455
+ * A step started before the planner knows it will use it.
456
+ *
457
+ * Planning was a chain of sessions, each waiting for the one before, and every
458
+ * session costs its start-up and its answer however short the question. Where
459
+ * the next step does not depend on the answer it waits for, it starts at the
460
+ * same time, and is stopped if that answer says it is not needed.
461
+ */
462
+ interface Speculation<T> {
463
+ value: Promise<T>
464
+ /**
465
+ * Settles once its session has started, or once the step has failed without
466
+ * one. The planner waits for it before starting the step that decides, so
467
+ * the same answers always lead to the same sessions.
468
+ */
469
+ started: Promise<void>
470
+ /** Stop the session and wait until it has stopped: its answer, if it finished first. */
471
+ drop(): Promise<T | undefined>
472
+ }
473
+
474
+ function speculate<T>(start: (signal: AbortSignal, onStart: () => void) => Promise<T>): Speculation<T> {
475
+ const control = new AbortController()
476
+ let began!: () => void
477
+ const sessionStarted = new Promise<void>((r) => (began = r))
478
+ const value = start(control.signal, began)
479
+ // Settled whether or not anyone awaits it, so a dropped step is not an
480
+ // unhandled rejection.
481
+ const settled = value.then((v) => v, () => undefined)
482
+ return {
483
+ value,
484
+ started: Promise.race([sessionStarted, settled.then(() => undefined)]),
485
+ drop: async () => {
486
+ control.abort()
487
+ return settled
488
+ },
489
+ }
490
+ }
491
+
446
492
  /**
447
493
  * From a request (or an edited PRD) to a checked spec on disk.
448
494
  *
449
495
  * Sessions, all read-only, on the one adapter the caller resolved:
496
+ * - assess-complexity on the request, beside a plan written straight from it,
497
+ * which is kept when the change is small and stopped when it is not;
450
498
  * - generate-prd, unless a PRD was given;
451
- * - validate-prd beside assess-complexity, which is skipped when this exact
452
- * PRD was assessed before; up to two fix-prd + validate-prd rounds;
499
+ * - validate-prd beside the plan from the PRD when how to plan it is already
500
+ * known, or beside assess-complexity on the PRD when it is not, which is
501
+ * skipped when this exact PRD was assessed before; up to two fix-prd +
502
+ * validate-prd rounds, and the plan is written again from the fixed PRD;
453
503
  * - generate-convoy, once, or once per group at the same time for a large
454
504
  * feature; one retry when an answer cannot be read;
455
505
  * - fix-convoy only when the code's checks fail, at most twice;
@@ -459,6 +509,15 @@ async function fixPlan(step: StepRunner, plan: TaskPlan, problems: string): Prom
459
509
  * checks it was there for are done in code, and a person reads the plan
460
510
  * before it runs.
461
511
  */
512
+ function tasksPlanned(plan: TaskPlan): string {
513
+ return `${plan.tasks.length} task${plan.tasks.length === 1 ? '' : 's'}`
514
+ }
515
+
516
+ /** Whether an assessment asks for the work to be planned as groups, side by side. */
517
+ function inGroups(c: ComplexityAssessment): boolean {
518
+ return c.recommended_strategy === 'chain' && c.convoy_groups.length > 1
519
+ }
520
+
462
521
  /** Where a PRD would go, for a change small enough to plan from the request alone. */
463
522
  const NO_PRD = 'There is no PRD: this is a small change, planned straight from the request. Read the code it touches before you plan.'
464
523
 
@@ -469,7 +528,18 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
469
528
  const started = Date.now()
470
529
  const spend: PlanningSpend = { sessions: 0, ms: 0, tokens: 0, costUsd: 0, costComplete: true }
471
530
  const step: StepRunner = async (template, inputs) => {
472
- const r = await runPromptStep({ template, adapter: req.adapter, pkgRoot: req.pkgRoot, cwd: root, verbose: req.verbose, ...inputs })
531
+ let r: PromptStepResult
532
+ try {
533
+ r = await runPromptStep({ template, adapter: req.adapter, pkgRoot: req.pkgRoot, cwd: root, verbose: req.verbose, ...inputs })
534
+ } catch (err) {
535
+ // A stopped session ran, and spent what it never got to report.
536
+ if (err instanceof StepCancelled) {
537
+ spend.sessions++
538
+ spend.costComplete = false
539
+ spend.ms = Date.now() - started
540
+ }
541
+ throw err
542
+ }
473
543
  spend.sessions++
474
544
  spend.tokens += r.tokens ?? 0
475
545
  if (r.costUsd === undefined) spend.costComplete = false
@@ -479,21 +549,37 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
479
549
  }
480
550
 
481
551
  // ── A small change: no PRD ────────────────────────────────────────────────
482
- // Sizing the request first is one short economy session. When it is small,
483
- // the plan is written straight from it: a PRD, its review and its fixes were
484
- // four or five sessions and most of the planning time — 7m 25s in a real
485
- // run — for a change the request already described.
552
+ // When the request is small, the plan is written straight from it: a PRD,
553
+ // its review and its fixes were four or five sessions and most of the
554
+ // planning time — 7m 25s in a real run — for a change the request already
555
+ // described. Neither the plan from the request nor the PRD depends on the
556
+ // size, so all three start together, and the size decides which of the two
557
+ // is kept: the other is stopped. Waiting for the size first added its whole
558
+ // session, about 20s, to every plan.
486
559
  let prdPath: string | null = null
487
560
  let plan: TaskPlan | null = null
488
561
  let quick: ComplexityAssessment | null = null
562
+ let drafting: Speculation<PromptStepResult> | null = null
489
563
  if (!req.prdPath && req.task) {
490
- quick = await step('assess-complexity', { goalText: req.task, contextText: req.task })
564
+ const task = req.task
565
+ const direct = speculate((signal, onStart) => generatePlan(step, task, NO_PRD, 'task', convoyDir, signal, onStart))
566
+ drafting = speculate((signal, onStart) => step('generate-prd', { goalText: task, signal, onStart }))
567
+ await Promise.all([direct.started, drafting.started])
568
+ quick = await step('assess-complexity', { goalText: task, contextText: task })
491
569
  .then((r) => parseComplexityAssessment(r.rawOutput))
492
570
  .catch(() => null)
493
571
  if (quick?.complexity === 'low' && quick.recommended_strategy !== 'chain') {
494
572
  done('Sized', 'low — planned straight from the request, without a PRD')
495
- plan = await generatePlan(step, req.task, appendTaskComplexity(NO_PRD, quick.task_complexity), 'task', convoyDir)
496
- done(`${plan.tasks.length} tasks planned`)
573
+ // A PRD that finished first is not left behind for a change that has none.
574
+ const unneeded = await drafting.drop()
575
+ if (unneeded?.outputPath) {
576
+ await rm(unneeded.outputPath, { force: true })
577
+ await rmdir(dirname(unneeded.outputPath)).catch(() => {})
578
+ }
579
+ plan = await direct.value
580
+ done(`${tasksPlanned(plan)} planned`)
581
+ } else {
582
+ await direct.drop()
497
583
  }
498
584
  }
499
585
 
@@ -503,7 +589,7 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
503
589
  prdPath = resolve(root, req.prdPath)
504
590
  done('PRD', relPath(prdPath))
505
591
  } else {
506
- const written = await step('generate-prd', { goalText: req.task ?? '' })
592
+ const written = drafting ? await drafting.value : await step('generate-prd', { goalText: req.task ?? '' })
507
593
  prdPath = written.outputPath!
508
594
  done('PRD written', relPath(prdPath))
509
595
  }
@@ -514,25 +600,45 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
514
600
  // it is cached under this draft's text, which is the text it describes.
515
601
  const cached = await readCachedComplexity(prdPath, prd)
516
602
  const assessedFrom = prd
517
- const [verdict, complexity] = await settleAll<PromptStepResult | ComplexityAssessment | null>([
518
- step('validate-prd', { goalText: `<!-- validation-pass: 1 -->\n${prd}` }),
519
- // The request was sized already. Only groups need sizing against the
520
- // PRD, whose phases they name.
521
- cached || (quick && quick.recommended_strategy !== 'chain')
522
- ? Promise.resolve(cached ?? quick)
523
- : step('assess-complexity', { goalText: prd, contextText: req.task ?? '' })
524
- .then((r) => parseComplexityAssessment(r.rawOutput))
525
- .catch((err: unknown) => {
526
- warn(`Could not size the work (${message(err)}) — planning it as one`)
527
- return null
528
- }),
529
- ]) as [PromptStepResult, ComplexityAssessment | null]
603
+ // The request was sized already. Only groups need sizing against the PRD,
604
+ // whose phases they name.
605
+ const known = cached ?? (quick && quick.recommended_strategy !== 'chain' ? quick : null)
606
+ const goalFor = (c: ComplexityAssessment | null): string => req.task ?? c?.original_prompt ?? 'Implement the PRD.'
607
+ // When how to plan it is known already, the plan starts beside the review:
608
+ // most PRDs pass, and a plan from one that does not is written again from
609
+ // the fixed text.
610
+ const draft = prd
611
+ let early = known && !inGroups(known)
612
+ ? speculate((signal, onStart) =>
613
+ generatePlan(step, goalFor(known), appendTaskComplexity(draft, known.task_complexity), 'task', convoyDir, signal, onStart))
614
+ : null
615
+ await early?.started
616
+ let verdict: PromptStepResult
617
+ let complexity: ComplexityAssessment | null
618
+ try {
619
+ ;[verdict, complexity] = await settleAll<PromptStepResult | ComplexityAssessment | null>([
620
+ step('validate-prd', { goalText: `<!-- validation-pass: 1 -->\n${prd}` }),
621
+ known
622
+ ? Promise.resolve(known)
623
+ : step('assess-complexity', { goalText: prd, contextText: req.task ?? '' })
624
+ .then((r) => parseComplexityAssessment(r.rawOutput))
625
+ .catch((err: unknown) => {
626
+ warn(`Could not size the work (${message(err)}) — planning it as one`)
627
+ return null
628
+ }),
629
+ ]) as [PromptStepResult, ComplexityAssessment | null]
630
+ } catch (err) {
631
+ await early?.drop()
632
+ throw err
633
+ }
530
634
 
531
635
  if (complexity && !cached && complexity !== quick) await writeCachedComplexity(prdPath, assessedFrom, complexity)
532
636
 
533
637
  if (verdict.isValid) {
534
638
  done('PRD checked')
535
639
  } else {
640
+ await early?.drop()
641
+ early = null
536
642
  let issues = verdict.errors || verdict.rawOutput
537
643
  let fixed = false
538
644
  for (let round = 1; round <= MAX_FIX_ROUNDS && !fixed; round++) {
@@ -554,7 +660,7 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
554
660
 
555
661
  // ── The tasks ─────────────────────────────────────────────────────────────
556
662
  let groups: ConvoyGroup[] | null = null
557
- if (complexity?.recommended_strategy === 'chain' && complexity.convoy_groups.length > 1) {
663
+ if (complexity && inGroups(complexity)) {
558
664
  const check = validateComplexityGroups(complexity)
559
665
  if (check.valid) groups = topologicalSortGroups(complexity.convoy_groups)
560
666
  else warn(`Ignoring the suggested groups (${check.reason}) — planning it as one`)
@@ -592,11 +698,12 @@ export async function planConvoy(req: PlanRequest): Promise<PlanOutcome> {
592
698
  featureName,
593
699
  all.map((g, i) => ({ name: g.name, depends_on: g.depends_on, plan: plans[i] })),
594
700
  )
595
- done(`${plan.tasks.length} tasks planned`, `${all.length} groups, planned side by side`)
701
+ done(`${tasksPlanned(plan)} planned`, `${all.length} groups, planned side by side`)
596
702
  } else {
597
- const goal = req.task ?? complexity?.original_prompt ?? 'Implement the PRD.'
598
- plan = await generatePlan(step, goal, appendTaskComplexity(prd, complexity?.task_complexity), 'task', convoyDir)
599
- done(`${plan.tasks.length} tasks planned`)
703
+ plan = early
704
+ ? await early.value
705
+ : await generatePlan(step, goalFor(complexity), appendTaskComplexity(prd, complexity?.task_complexity), 'task', convoyDir)
706
+ done(`${tasksPlanned(plan)} planned`)
600
707
  }
601
708
  }
602
709
 
package/src/cli/plan.ts CHANGED
@@ -37,6 +37,22 @@ export interface PromptStepOptions {
37
37
  verbose?: boolean
38
38
  /** How long one session may run before it is stopped. Defaults to 10 minutes. */
39
39
  timeoutMs?: number
40
+ /**
41
+ * Stops the session when aborted, and the step fails with a `StepCancelled`.
42
+ * The planner starts some steps before it knows it needs them, and stops the
43
+ * ones it turns out not to.
44
+ */
45
+ signal?: AbortSignal
46
+ /** Called once the session has started, before its answer. */
47
+ onStart?: () => void
48
+ }
49
+
50
+ /** A step stopped through its `signal`, not one that failed. */
51
+ export class StepCancelled extends Error {
52
+ constructor(template: string) {
53
+ super(`${template} was stopped: its answer is no longer needed`)
54
+ this.name = 'StepCancelled'
55
+ }
40
56
  }
41
57
 
42
58
  export interface PromptStepResult {
@@ -265,6 +281,19 @@ function modelFor(adapter: AgentAdapter, template: string): string | undefined {
265
281
  return adapter.tierModels?.[tier]
266
282
  }
267
283
 
284
+ /**
285
+ * How much each step reasons before it answers.
286
+ *
287
+ * Planning sessions spent most of their time thinking, not reading: on a small
288
+ * project a PRD took 129s at Claude Code's default effort and 36s at `low`, with
289
+ * every section, and a plan 55s against 30s at `medium`. The plan gets
290
+ * `medium` because its task prompts are the only instructions the workers see;
291
+ * sizing, the PRD, the checks and the fixes get `low`.
292
+ */
293
+ export function effortFor(template: string): 'low' | 'medium' {
294
+ return template === 'generate-convoy' ? 'medium' : 'low'
295
+ }
296
+
268
297
  /**
269
298
  * Run one planning template through the caller's adapter.
270
299
  *
@@ -297,28 +326,44 @@ export async function runPromptStep(opts: PromptStepOptions): Promise<PromptStep
297
326
  console.log(c.dim(` ${opts.template} · ${opts.adapter.name} · read-only · ${prompt.length} chars`))
298
327
  }
299
328
 
329
+ if (opts.signal?.aborted) throw new StepCancelled(opts.template)
300
330
  const timeoutMs = opts.timeoutMs ?? DEFAULT_STEP_TIMEOUT_MS
301
331
  const stop = opts.verbose ? null : startProgress(opts.template)
302
332
  let timer: ReturnType<typeof setTimeout> | undefined
333
+ let onAbort: (() => void) | undefined
303
334
  let execResult
304
335
  try {
336
+ const running = opts.adapter.execute(task, {
337
+ verbose: opts.verbose ?? false,
338
+ cwd: opts.cwd ?? process.cwd(),
339
+ permissionMode: 'plan',
340
+ // Everything a planning step needs is in its prompt or in the files it
341
+ // reads: no MCP servers, skills or web searches.
342
+ lean: true,
343
+ effort: effortFor(opts.template),
344
+ ...(modelFor(opts.adapter, opts.template) ? { model: modelFor(opts.adapter, opts.template) } : {}),
345
+ })
346
+ opts.onStart?.()
305
347
  execResult = await Promise.race([
306
- opts.adapter.execute(task, {
307
- verbose: opts.verbose ?? false,
308
- cwd: opts.cwd ?? process.cwd(),
309
- permissionMode: 'plan',
310
- ...(modelFor(opts.adapter, opts.template) ? { model: modelFor(opts.adapter, opts.template) } : {}),
311
- }),
348
+ running,
312
349
  new Promise<never>((_, reject) => {
313
350
  timer = setTimeout(() => {
314
351
  // A hung session would otherwise hold the whole plan open forever.
315
352
  opts.adapter.kill?.(task)
316
353
  reject(new Error(`${opts.template} ran longer than ${Math.round(timeoutMs / 60_000)}m and was stopped`))
317
354
  }, timeoutMs)
355
+ // Stopped by id. The planner only cancels a step while it is the one
356
+ // session of its template, so no other session shares the id.
357
+ onAbort = () => {
358
+ opts.adapter.kill?.(task)
359
+ reject(new StepCancelled(opts.template))
360
+ }
361
+ opts.signal?.addEventListener('abort', onAbort, { once: true })
318
362
  }),
319
363
  ])
320
364
  } finally {
321
365
  if (timer) clearTimeout(timer)
366
+ if (onAbort) opts.signal?.removeEventListener('abort', onAbort)
322
367
  stop?.()
323
368
  }
324
369
 
@@ -0,0 +1,228 @@
1
+ import { describe, it, expect, afterEach } from 'vitest'
2
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { dirname, join } from 'node:path'
5
+ import { readProjectFacts } from './project-facts.js'
6
+
7
+ /**
8
+ * The facts `init` writes into `.opencastle/`, read from small project trees
9
+ * shaped like the real ones they stand for.
10
+ */
11
+
12
+ let root = ''
13
+
14
+ function project(files: Record<string, string>): string {
15
+ root = mkdtempSync(join(tmpdir(), 'oc-facts-'))
16
+ for (const [path, text] of Object.entries(files)) {
17
+ mkdirSync(dirname(join(root, path)), { recursive: true })
18
+ writeFileSync(join(root, path), text)
19
+ }
20
+ return root
21
+ }
22
+
23
+ afterEach(() => {
24
+ if (root) rmSync(root, { recursive: true, force: true })
25
+ root = ''
26
+ })
27
+
28
+ const pkg = (body: object): string => JSON.stringify(body)
29
+
30
+ describe('routes', () => {
31
+ it('reads Next.js App Router pages and route handlers, without groups, slots or private folders', async () => {
32
+ const r = project({
33
+ 'package.json': pkg({ dependencies: { next: '^15.1.0' } }),
34
+ 'app/page.tsx': '',
35
+ 'app/(marketing)/pricing/page.tsx': '',
36
+ 'app/blog/[slug]/page.mdx': '',
37
+ 'app/@modal/login/page.tsx': '',
38
+ 'app/_components/card/page.tsx': '',
39
+ 'app/api/posts/route.ts': 'export async function GET() {}\nexport const POST = handler',
40
+ 'pages/api/legacy.ts': 'export default function handler() {}',
41
+ })
42
+ const facts = await readProjectFacts(r, { frameworks: ['next'] })
43
+ expect(facts.pages).toEqual([{ root: 'app/', routes: ['/', '/blog/[slug]', '/login', '/pricing'] }])
44
+ expect(facts.api).toEqual([
45
+ { route: '/api/legacy', methods: [], file: 'pages/api/legacy.ts' },
46
+ { route: '/api/posts', methods: ['GET', 'POST'], file: 'app/api/posts/route.ts' },
47
+ ])
48
+ expect(facts.stack).toEqual([{ layer: 'Framework', name: 'Next.js', version: '15.1.0' }])
49
+ expect(facts.devPort).toBe(3000)
50
+ })
51
+
52
+ it('leaves out Astro files whose path has a part starting with an underscore', async () => {
53
+ const r = project({
54
+ 'package.json': pkg({ dependencies: { astro: '5.0.0' } }),
55
+ 'src/pages/index.astro': '',
56
+ 'src/pages/posts/[slug].astro': '',
57
+ 'src/pages/posts/_components/Card.astro': '',
58
+ 'src/pages/_utils/group.ts': 'export function group() {}',
59
+ 'src/pages/rss.xml.ts': 'export const GET = () => new Response()',
60
+ })
61
+ const facts = await readProjectFacts(r, { frameworks: ['astro'] })
62
+ expect(facts.pages[0].routes).toEqual(['/', '/posts/[slug]'])
63
+ expect(facts.api.map((a) => [a.route, a.methods])).toEqual([['/rss.xml', ['GET']]])
64
+ })
65
+
66
+ it('reads SvelteKit pages and server routes', async () => {
67
+ const r = project({
68
+ 'package.json': pkg({}),
69
+ 'src/routes/+page.svelte': '',
70
+ 'src/routes/about/+page.svelte': '',
71
+ 'src/routes/api/items/+server.ts': 'export async function GET() {}\nexport async function DELETE() {}',
72
+ })
73
+ const facts = await readProjectFacts(r, { frameworks: ['sveltekit'] })
74
+ expect(facts.pages[0]).toEqual({ root: 'src/routes/', routes: ['/', '/about'] })
75
+ expect(facts.api).toEqual([{ route: '/api/items', methods: ['GET', 'DELETE'], file: 'src/routes/api/items/+server.ts' }])
76
+ })
77
+
78
+ it('finds routes in each app of a monorepo', async () => {
79
+ const r = project({
80
+ 'package.json': pkg({ name: 'mono' }),
81
+ 'apps/web/package.json': pkg({ name: '@x/web', dependencies: { next: '15.0.0' } }),
82
+ 'apps/web/src/app/page.tsx': '',
83
+ 'apps/web/src/app/settings/page.tsx': '',
84
+ })
85
+ const facts = await readProjectFacts(r, { frameworks: ['next'] })
86
+ expect(facts.pages).toEqual([{ root: 'apps/web/src/app/', routes: ['/', '/settings'] }])
87
+ expect(facts.workspaces).toEqual([{ path: 'apps/web/', name: '@x/web', purpose: 'Next.js app' }])
88
+ })
89
+
90
+ it('reads Express-style routes when there are no route files', async () => {
91
+ const r = project({
92
+ 'package.json': pkg({ dependencies: { express: '4.19.0' } }),
93
+ 'src/server.js': "app.get('/health', h)\napp.post('/notes', h)\nrouter.delete('/notes/:id', h)",
94
+ })
95
+ const facts = await readProjectFacts(r, { frameworks: ['express'] })
96
+ expect(facts.api.map((a) => `${a.methods.join(',')} ${a.route}`)).toEqual(['GET /health', 'POST /notes', 'DELETE /notes/:id'])
97
+ })
98
+ })
99
+
100
+ describe('data', () => {
101
+ it('lists Prisma models and its migrations', async () => {
102
+ const r = project({
103
+ 'package.json': pkg({ dependencies: { '@prisma/client': '^5.2.0' } }),
104
+ 'prisma/schema.prisma': 'model User {\n id Int @id\n}\n\nmodel Post {\n id Int @id\n}\nenum Role { A }\n',
105
+ 'prisma/migrations/20240101_init/migration.sql': '',
106
+ 'prisma/migrations/20240202_posts/migration.sql': '',
107
+ 'lib/db.ts': "import { PrismaClient } from '@prisma/client'",
108
+ 'app/page.tsx': "import type { User } from '@prisma/client'",
109
+ })
110
+ const facts = await readProjectFacts(r, { databases: ['prisma'] })
111
+ expect(facts.models).toEqual({ source: 'prisma/schema.prisma', names: ['User', 'Post'] })
112
+ expect(facts.migrations).toEqual({ dir: 'prisma/migrations/', count: 2, latest: ['20240101_init', '20240202_posts'] })
113
+ // The file that sets the client up comes before the pages that use it.
114
+ expect(facts.importers.prisma[0]).toBe('lib/db.ts')
115
+ })
116
+
117
+ it('lists Drizzle tables from every schema file', async () => {
118
+ const r = project({
119
+ 'package.json': pkg({}),
120
+ 'packages/db/src/schema.ts': 'export const Post = pgTable("post", {})',
121
+ 'packages/db/src/auth-schema.ts': 'export const user = pgTable("user", {})\nexport const session = pgTable("session", {})',
122
+ })
123
+ const facts = await readProjectFacts(r, { databases: ['drizzle'] })
124
+ expect(facts.models?.names.sort()).toEqual(['post', 'session', 'user'])
125
+ })
126
+
127
+ it('lists Supabase tables from its migrations', async () => {
128
+ const r = project({
129
+ 'package.json': pkg({}),
130
+ 'supabase/migrations/20240101000000_init.sql': 'create table public.profiles (id uuid);\nCREATE TABLE IF NOT EXISTS "orders" ();',
131
+ })
132
+ const facts = await readProjectFacts(r, { databases: ['supabase'] })
133
+ expect(facts.models).toEqual({ source: 'supabase/migrations/', names: ['profiles', 'orders'] })
134
+ })
135
+ })
136
+
137
+ describe('everything else', () => {
138
+ it('takes variable names from the example file and never reads .env', async () => {
139
+ const r = project({
140
+ 'package.json': pkg({}),
141
+ '.env': 'SECRET_ONLY_IN_ENV=hunter2\n',
142
+ '.env.example': 'DATABASE_URL=\nexport STRIPE_KEY=sk_test\n# COMMENTED=1\n',
143
+ })
144
+ const facts = await readProjectFacts(r, {})
145
+ expect(facts.envVars).toEqual({ source: '.env.example', names: ['DATABASE_URL', 'STRIPE_KEY'] })
146
+ expect(JSON.stringify(facts)).not.toContain('SECRET_ONLY_IN_ENV')
147
+ expect(JSON.stringify(facts)).not.toContain('hunter2')
148
+ })
149
+
150
+ it('reads Tailwind breakpoints, but not the container sizes', async () => {
151
+ const r = project({
152
+ 'package.json': pkg({}),
153
+ 'tailwind.config.js': 'module.exports = { theme: { container: { screens: { "2xl": "1400px" } }, extend: { screens: { "3xl": "1920px" } } } }',
154
+ })
155
+ const facts = await readProjectFacts(r, { styling: ['tailwind'] })
156
+ const values = Object.fromEntries(facts.breakpoints!.values)
157
+ expect(values['2xl']).toBe('1536px')
158
+ expect(values['3xl']).toBe('1920px')
159
+ })
160
+
161
+ it('resolves pnpm catalog versions from a workspace package', async () => {
162
+ const r = project({
163
+ 'package.json': pkg({ name: 'mono' }),
164
+ 'pnpm-workspace.yaml': 'packages:\n - apps/*\ncatalog:\n next: ^16.0.1\n "@prisma/client": 6.1.0\n',
165
+ 'apps/web/package.json': pkg({ dependencies: { next: 'catalog:', '@prisma/client': 'catalog:' } }),
166
+ })
167
+ const facts = await readProjectFacts(r, { frameworks: ['next'], databases: ['prisma'] })
168
+ expect(facts.stack).toEqual([
169
+ { layer: 'Framework', name: 'Next.js', version: '16.0.1' },
170
+ { layer: 'Database', name: 'Prisma', version: '6.1.0' },
171
+ ])
172
+ })
173
+
174
+ it('describes the project from the README introduction only', async () => {
175
+ const intro = project({
176
+ 'package.json': pkg({ name: 'x' }),
177
+ 'README.md': '# X\n\n[![ci](https://x/badge.svg)](https://x)\n\nX turns [notes](https://n) into tasks.\n\n## Install\n\nRun this:\n',
178
+ })
179
+ expect((await readProjectFacts(intro, {})).description).toBe('X turns notes into tasks.')
180
+ rmSync(intro, { recursive: true, force: true })
181
+
182
+ const howTo = project({
183
+ 'package.json': pkg({ name: 'y' }),
184
+ 'README.md': '# Y\n\nThere are two ways to start:\n\n## Setup\n\nY is great.\n',
185
+ })
186
+ expect((await readProjectFacts(howTo, {})).description).toBeUndefined()
187
+ })
188
+
189
+ it('takes a port from the dev script before the framework default', async () => {
190
+ const r = project({ 'package.json': pkg({ scripts: { dev: 'next dev -p 4000' } }) })
191
+ expect((await readProjectFacts(r, { frameworks: ['next'] })).devPort).toBe(4000)
192
+ })
193
+
194
+ it('reads what CI runs, the Node version and the coverage the tests require', async () => {
195
+ const r = project({
196
+ 'package.json': pkg({ engines: { node: '>=20' }, devDependencies: { vitest: '2.0.0' } }),
197
+ '.github/workflows/ci.yml': [
198
+ 'jobs:',
199
+ ' test:',
200
+ ' steps:',
201
+ ' - run: pnpm install --frozen-lockfile',
202
+ ' - run: pnpm lint',
203
+ ' - name: Test',
204
+ ' run: |',
205
+ ' pnpm test --coverage',
206
+ ' echo done',
207
+ ].join('\n'),
208
+ 'vitest.config.ts': 'export default { test: { coverage: { thresholds: { lines: 80, branches: 70 } } } }',
209
+ })
210
+ const facts = await readProjectFacts(r, { packageManager: 'pnpm' })
211
+ expect(facts.ciCommands).toEqual(['pnpm lint', 'pnpm test --coverage'])
212
+ expect(facts.nodeVersion).toBe('>=20')
213
+ expect(facts.coverage).toEqual(['lines 80', 'branches 70'])
214
+ })
215
+
216
+ it('names test frameworks from package.json only, and finds the test files', async () => {
217
+ const r = project({
218
+ 'package.json': pkg({ devDependencies: { vitest: '^2.0.0' } }),
219
+ 'vitest.config.ts': '',
220
+ 'src/a.test.ts': '',
221
+ 'e2e/login.spec.ts': '',
222
+ })
223
+ const facts = await readProjectFacts(r, { testing: ['vitest', 'chrome-devtools'] })
224
+ expect(facts.testFrameworks).toEqual(['Vitest'])
225
+ expect(facts.testConfigs).toEqual(['vitest.config.ts'])
226
+ expect(facts.testFiles.sort()).toEqual(['e2e/login.spec.ts', 'src/a.test.ts'])
227
+ })
228
+ })