opencastle 0.36.0 → 0.36.2

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 (99) hide show
  1. package/dist/cli/convoy/engine.d.ts.map +1 -1
  2. package/dist/cli/convoy/engine.js +0 -7
  3. package/dist/cli/convoy/engine.js.map +1 -1
  4. package/dist/cli/convoy/engine.test.js +0 -1
  5. package/dist/cli/convoy/engine.test.js.map +1 -1
  6. package/dist/cli/convoy/event-emission.test.d.ts +2 -0
  7. package/dist/cli/convoy/event-emission.test.d.ts.map +1 -0
  8. package/dist/cli/convoy/event-emission.test.js +73 -0
  9. package/dist/cli/convoy/event-emission.test.js.map +1 -0
  10. package/dist/cli/convoy/event-schemas.d.ts.map +1 -1
  11. package/dist/cli/convoy/event-schemas.js +0 -25
  12. package/dist/cli/convoy/event-schemas.js.map +1 -1
  13. package/dist/cli/convoy/events.test.js +2 -2
  14. package/dist/cli/convoy/events.test.js.map +1 -1
  15. package/dist/cli/convoy/last-run.d.ts +53 -0
  16. package/dist/cli/convoy/last-run.d.ts.map +1 -0
  17. package/dist/cli/convoy/last-run.js +54 -0
  18. package/dist/cli/convoy/last-run.js.map +1 -0
  19. package/dist/cli/convoy/last-run.test.d.ts +2 -0
  20. package/dist/cli/convoy/last-run.test.d.ts.map +1 -0
  21. package/dist/cli/convoy/last-run.test.js +110 -0
  22. package/dist/cli/convoy/last-run.test.js.map +1 -0
  23. package/dist/cli/convoy/spec-types.d.ts +8 -2
  24. package/dist/cli/convoy/spec-types.d.ts.map +1 -1
  25. package/dist/cli/convoy/store.d.ts +3 -2
  26. package/dist/cli/convoy/store.d.ts.map +1 -1
  27. package/dist/cli/convoy/store.js +33 -8
  28. package/dist/cli/convoy/store.js.map +1 -1
  29. package/dist/cli/convoy/store.test.js +76 -13
  30. package/dist/cli/convoy/store.test.js.map +1 -1
  31. package/dist/cli/convoy/types.d.ts +0 -35
  32. package/dist/cli/convoy/types.d.ts.map +1 -1
  33. package/dist/cli/convoy/types.js +0 -4
  34. package/dist/cli/convoy/types.js.map +1 -1
  35. package/dist/cli/convoy-args.test.d.ts +2 -0
  36. package/dist/cli/convoy-args.test.d.ts.map +1 -0
  37. package/dist/cli/convoy-args.test.js +132 -0
  38. package/dist/cli/convoy-args.test.js.map +1 -0
  39. package/dist/cli/convoy-cmd.d.ts +25 -0
  40. package/dist/cli/convoy-cmd.d.ts.map +1 -1
  41. package/dist/cli/convoy-cmd.js +155 -19
  42. package/dist/cli/convoy-cmd.js.map +1 -1
  43. package/dist/cli/publish-workflow.test.js +12 -0
  44. package/dist/cli/publish-workflow.test.js.map +1 -1
  45. package/dist/cli/run/adapters/codex.d.ts.map +1 -1
  46. package/dist/cli/run/adapters/codex.js +8 -1
  47. package/dist/cli/run/adapters/codex.js.map +1 -1
  48. package/dist/cli/run/adapters/permission-modes.d.ts +20 -0
  49. package/dist/cli/run/adapters/permission-modes.d.ts.map +1 -0
  50. package/dist/cli/run/adapters/permission-modes.js +82 -0
  51. package/dist/cli/run/adapters/permission-modes.js.map +1 -0
  52. package/dist/cli/run/adapters/permission-modes.test.d.ts +2 -0
  53. package/dist/cli/run/adapters/permission-modes.test.d.ts.map +1 -0
  54. package/dist/cli/run/adapters/permission-modes.test.js +95 -0
  55. package/dist/cli/run/adapters/permission-modes.test.js.map +1 -0
  56. package/dist/cli/run/schema.d.ts.map +1 -1
  57. package/dist/cli/run/schema.js +69 -0
  58. package/dist/cli/run/schema.js.map +1 -1
  59. package/dist/cli/run/schema.test.js +62 -0
  60. package/dist/cli/run/schema.test.js.map +1 -1
  61. package/dist/cli/run-dry-run.test.d.ts +2 -0
  62. package/dist/cli/run-dry-run.test.d.ts.map +1 -0
  63. package/dist/cli/run-dry-run.test.js +83 -0
  64. package/dist/cli/run-dry-run.test.js.map +1 -0
  65. package/dist/cli/run-executor-flags.test.d.ts +2 -0
  66. package/dist/cli/run-executor-flags.test.d.ts.map +1 -0
  67. package/dist/cli/run-executor-flags.test.js +31 -0
  68. package/dist/cli/run-executor-flags.test.js.map +1 -0
  69. package/dist/cli/run.d.ts +40 -0
  70. package/dist/cli/run.d.ts.map +1 -1
  71. package/dist/cli/run.js +198 -24
  72. package/dist/cli/run.js.map +1 -1
  73. package/package.json +1 -1
  74. package/src/cli/convoy/TELEMETRY.md +0 -2
  75. package/src/cli/convoy/engine.test.ts +0 -1
  76. package/src/cli/convoy/engine.ts +0 -7
  77. package/src/cli/convoy/event-emission.test.ts +79 -0
  78. package/src/cli/convoy/event-schemas.ts +0 -25
  79. package/src/cli/convoy/events.test.ts +2 -2
  80. package/src/cli/convoy/last-run.test.ts +130 -0
  81. package/src/cli/convoy/last-run.ts +87 -0
  82. package/src/cli/convoy/spec-types.ts +8 -2
  83. package/src/cli/convoy/store.test.ts +87 -13
  84. package/src/cli/convoy/store.ts +40 -12
  85. package/src/cli/convoy/types.ts +0 -10
  86. package/src/cli/convoy-args.test.ts +156 -0
  87. package/src/cli/convoy-cmd.ts +162 -19
  88. package/src/cli/publish-workflow.test.ts +13 -0
  89. package/src/cli/run/adapters/codex.ts +9 -1
  90. package/src/cli/run/adapters/permission-modes.test.ts +114 -0
  91. package/src/cli/run/adapters/permission-modes.ts +89 -0
  92. package/src/cli/run/schema.test.ts +72 -0
  93. package/src/cli/run/schema.ts +71 -0
  94. package/src/cli/run-dry-run.test.ts +97 -0
  95. package/src/cli/run-executor-flags.test.ts +38 -0
  96. package/src/cli/run.ts +242 -29
  97. package/src/dashboard/dist/index.html +1 -1
  98. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  99. package/src/dashboard/src/pages/index.astro +1 -1
@@ -17,7 +17,7 @@ import type {
17
17
  TaskStepRecord,
18
18
  } from './types.js'
19
19
 
20
- const SCHEMA_VERSION = 12
20
+ const SCHEMA_VERSION = 13
21
21
 
22
22
  // ── Size limits (bytes) ────────────────────────────────────────────────────────
23
23
  const LIMIT_SPEC_YAML = 256 * 1024 // 256 KB
@@ -68,6 +68,8 @@ export interface ConvoyStore {
68
68
  ): void
69
69
  getConvoy(id: string): ConvoyRecord | undefined
70
70
  getLatestConvoy(): ConvoyRecord | undefined
71
+ /** The newest convoy that is not a member of a pipeline. */
72
+ getLatestStandaloneConvoy(): ConvoyRecord | undefined
71
73
  updateConvoyStatus(
72
74
  id: string,
73
75
  status: ConvoyStatus,
@@ -83,7 +85,7 @@ export interface ConvoyStore {
83
85
  | 'on_exhausted' | 'injected' | 'provenance' | 'idempotency_key'
84
86
  | 'current_step' | 'total_steps' | 'review_level' | 'review_verdict'
85
87
  | 'review_tokens' | 'review_model' | 'panel_attempts' | 'dispute_id'
86
- | 'drift_score' | 'drift_retried' | 'discovered_issues' | 'compaction_count'
88
+ | 'drift_score' | 'drift_retried'
87
89
  > & { outputs?: string | null; inputs?: string | null },
88
90
  ): void
89
91
  insertInjectedTask(record: TaskRecord): void
@@ -115,7 +117,6 @@ export interface ConvoyStore {
115
117
  convoyId: string,
116
118
  fields: Partial<Pick<TaskRecord, 'drift_score' | 'drift_retried'>>,
117
119
  ): void
118
- updateTaskCompaction(taskId: string, convoyId: string, compactionCount: number): void
119
120
  updateTaskDisputeStatus(taskId: string, convoyId: string, status: ConvoyTaskStatus, disputeId: string): void
120
121
  getReadyTasks(convoyId: string): TaskRecord[]
121
122
  insertTaskStep(record: Omit<TaskStepRecord, 'id'>): number
@@ -262,10 +263,8 @@ class ConvoyStoreImpl implements ConvoyStore {
262
263
  dispute_id TEXT,
263
264
  drift_score REAL,
264
265
  drift_retried INTEGER NOT NULL DEFAULT 0,
265
- compaction_count INTEGER NOT NULL DEFAULT 0,
266
266
  outputs TEXT,
267
267
  inputs TEXT,
268
- discovered_issues TEXT,
269
268
  contract_result TEXT,
270
269
  PRIMARY KEY (id, convoy_id)
271
270
  );
@@ -430,6 +429,10 @@ class ConvoyStoreImpl implements ConvoyStore {
430
429
  migrateSchema(this.db, this.dbPath, 11, 12)
431
430
  version = 12
432
431
  }
432
+ if (version === 12) {
433
+ migrateSchema(this.db, this.dbPath, 12, 13)
434
+ version = 13
435
+ }
433
436
  }
434
437
 
435
438
  insertConvoy(
@@ -464,6 +467,23 @@ class ConvoyStoreImpl implements ConvoyStore {
464
467
  .get() as ConvoyRecord | undefined
465
468
  }
466
469
 
470
+ /**
471
+ * The newest convoy nobody else is driving.
472
+ *
473
+ * A convoy with a `pipeline_id` is a member of a chain, and resuming it on its
474
+ * own runs one link while the orchestrator that owns the rest stays stopped.
475
+ * `resume` needs the newest run it may legitimately take over, which is this
476
+ * one — not simply the newest row.
477
+ */
478
+ getLatestStandaloneConvoy(): ConvoyRecord | undefined {
479
+ return this.db
480
+ .prepare(
481
+ 'SELECT *, total_cost_usd_num AS total_cost_usd FROM convoy' +
482
+ ' WHERE pipeline_id IS NULL ORDER BY created_at DESC LIMIT 1',
483
+ )
484
+ .get() as ConvoyRecord | undefined
485
+ }
486
+
467
487
  updateConvoyStatus(
468
488
  id: string,
469
489
  status: ConvoyStatus,
@@ -518,7 +538,7 @@ class ConvoyStoreImpl implements ConvoyStore {
518
538
  | 'on_exhausted' | 'injected' | 'provenance' | 'idempotency_key'
519
539
  | 'current_step' | 'total_steps' | 'review_level' | 'review_verdict'
520
540
  | 'review_tokens' | 'review_model' | 'panel_attempts' | 'dispute_id'
521
- | 'drift_score' | 'drift_retried' | 'discovered_issues' | 'compaction_count'
541
+ | 'drift_score' | 'drift_retried'
522
542
  > & { outputs?: string | null; inputs?: string | null },
523
543
  ): void {
524
544
  this.db
@@ -724,12 +744,6 @@ class ConvoyStoreImpl implements ConvoyStore {
724
744
  this.db.prepare(`UPDATE task SET ${sets.join(', ')} WHERE id = :id AND convoy_id = :convoy_id`).run(params)
725
745
  }
726
746
 
727
- updateTaskCompaction(taskId: string, convoyId: string, compactionCount: number): void {
728
- this.db
729
- .prepare('UPDATE task SET compaction_count = :compaction_count WHERE id = :id AND convoy_id = :convoy_id')
730
- .run({ id: taskId, convoy_id: convoyId, compaction_count: compactionCount })
731
- }
732
-
733
747
  updateTaskDisputeStatus(taskId: string, convoyId: string, status: ConvoyTaskStatus, disputeId: string): void {
734
748
  this.db
735
749
  .prepare(
@@ -1427,6 +1441,20 @@ export function migrateSchema(db: DatabaseSync, dbPath: string, fromVersion: num
1427
1441
  WHERE idempotency_key IS NOT NULL;
1428
1442
  `)
1429
1443
  }
1444
+ if (v === 12) {
1445
+ // The last of the "intelligence suite" (see docs/plans/2026-07-25-strategic
1446
+ // -refactoring-plan.md, phase 4b). That pass deleted the six modules and the
1447
+ // config keys they exposed; these two columns outlived it, written as a
1448
+ // literal 0 and a literal null on every task insert and read by nothing.
1449
+ //
1450
+ // DROP COLUMN rather than a table rebuild: neither column is indexed or
1451
+ // referenced, and the engine already refuses to run below SQLite 3.35,
1452
+ // which is the version that introduced it.
1453
+ db.exec(`
1454
+ ALTER TABLE task DROP COLUMN compaction_count;
1455
+ ALTER TABLE task DROP COLUMN discovered_issues;
1456
+ `)
1457
+ }
1430
1458
  db.exec('COMMIT')
1431
1459
  } catch (err) {
1432
1460
  try { db.exec('ROLLBACK') } catch { /* ignore */ }
@@ -75,10 +75,8 @@ export interface TaskRecord {
75
75
  dispute_id: string | null
76
76
  drift_score: number | null
77
77
  drift_retried: number
78
- compaction_count: number
79
78
  outputs?: string | null // JSON array of TaskOutput
80
79
  inputs?: string | null // JSON array of TaskInput
81
- discovered_issues?: string | null // JSON array
82
80
  contract_result?: string | null // JSON ContractResult
83
81
  }
84
82
 
@@ -341,7 +339,6 @@ export type ConvoyEventType =
341
339
  | { type: 'artifact_limit_reached'; data?: { task_id?: string; limit?: number; current?: number } }
342
340
  | { type: 'agent_identity_captured'; data?: { agent?: string; task_id?: string } }
343
341
  | { type: 'agent_identity_rejected'; data?: { agent?: string; task_id?: string; reason?: string } }
344
- | { type: 'weak_area_skipped'; data?: { agent?: string; weak_areas?: string[]; task_files?: string[] } }
345
342
  | { type: 'swarm_concurrency_update'; data?: { new_concurrency?: number; reason?: string } }
346
343
  | { type: 'post_convoy_hook_failed'; data?: { hook?: string; error?: string } }
347
344
  | { type: 'session'; data?: { agent?: string; model?: string; task?: string; outcome?: string; duration_min?: number } }
@@ -357,12 +354,9 @@ export type ConvoyEventType =
357
354
  | { type: 'watch_cycle_end'; data?: { cycle_number?: number; status?: string } }
358
355
  | { type: 'watch_stopped'; data?: { reason?: string } }
359
356
  | { type: 'worker_killed'; data?: { reason?: string; worker_id?: string; task_id?: string } }
360
- | { type: 'discovered_issue'; data?: { task_id?: string; title?: string; file?: string; description?: string; severity?: string } }
361
357
  | { type: 'contract_violation'; data?: { task_id?: string; agent?: string; missing?: string[]; warnings?: string[] } }
362
358
  | { type: 'review_stage_completed'; data?: { stage: string; verdict: string; tokens: number; task_id?: string; model?: string } }
363
359
  | { type: 'partition_violation'; data?: { task_id?: string; allowed?: string[]; actual?: string[]; violations?: string[] } }
364
- | { type: 'context_compacted'; data?: { task_id?: string; compaction_count?: number; summary_path?: string; model?: string; tokens_used?: number } }
365
- | { type: 'skill_refinement_proposed'; data?: { skill_name?: string; proposal_path?: string; failure_count?: number; confidence?: string } }
366
360
  | { type: 'tdd_check_passed'; data?: { task_id?: string; new_source_files?: number; existing_test_files?: number } }
367
361
  | { type: 'tdd_check_failed'; data?: { task_id?: string; missing_test_files?: string[]; new_source_files?: number } }
368
362
  | { type: 'tdd_check_skipped'; data?: { task_id?: string; reason?: string; agent?: string } }
@@ -397,7 +391,6 @@ export const KNOWN_EVENT_TYPES: Set<string> = new Set<ConvoyEventType['type']>([
397
391
  'artifact_limit_reached',
398
392
  'agent_identity_captured',
399
393
  'agent_identity_rejected',
400
- 'weak_area_skipped',
401
394
  'swarm_concurrency_update',
402
395
  'post_convoy_hook_failed',
403
396
  'session',
@@ -410,12 +403,9 @@ export const KNOWN_EVENT_TYPES: Set<string> = new Set<ConvoyEventType['type']>([
410
403
  'watch_cycle_end',
411
404
  'watch_stopped',
412
405
  'worker_killed',
413
- 'discovered_issue',
414
406
  'contract_violation',
415
407
  'review_stage_completed',
416
408
  'partition_violation',
417
- 'context_compacted',
418
- 'skill_refinement_proposed',
419
409
  'tdd_check_passed',
420
410
  'tdd_check_failed',
421
411
  'tdd_check_skipped',
@@ -0,0 +1,156 @@
1
+ /**
2
+ * How `opencastle convoy` reads what you typed.
3
+ *
4
+ * The defect: the task was taken from the first argument alone, so an unquoted
5
+ * request lost every word after the first. `opencastle convoy add rate limiting
6
+ * to the API` planned a feature called "add", with no error, and went on to
7
+ * spend a full PRD round-trip on it.
8
+ */
9
+ import { describe, it, expect } from 'vitest'
10
+ import { positionalWords, splitTaskFlags } from './convoy-cmd.js'
11
+
12
+ describe('positionalWords', () => {
13
+ it('keeps every word of an unquoted task', () => {
14
+ expect(positionalWords(['add', 'rate', 'limiting', 'to', 'the', 'API'])).toEqual([
15
+ 'add',
16
+ 'rate',
17
+ 'limiting',
18
+ 'to',
19
+ 'the',
20
+ 'API',
21
+ ])
22
+ })
23
+
24
+ it('keeps a quoted task as the single word it already is', () => {
25
+ expect(positionalWords(['add rate limiting'])).toEqual(['add rate limiting'])
26
+ })
27
+
28
+ it('drops boolean flags wherever they appear', () => {
29
+ expect(positionalWords(['--verbose', 'fix', 'the', 'bug', '--dry-run'])).toEqual([
30
+ 'fix',
31
+ 'the',
32
+ 'bug',
33
+ ])
34
+ })
35
+
36
+ it('drops a flag value with its flag, so it cannot join the task', () => {
37
+ // The failure this prevents: planning "fix the login bug codex".
38
+ expect(positionalWords(['fix', 'the', 'login', 'bug', '--adapter', 'codex'])).toEqual([
39
+ 'fix',
40
+ 'the',
41
+ 'login',
42
+ 'bug',
43
+ ])
44
+ })
45
+
46
+ it('handles a value-taking flag in front of the task', () => {
47
+ expect(positionalWords(['-a', 'claude', 'ship', 'the', 'thing'])).toEqual([
48
+ 'ship',
49
+ 'the',
50
+ 'thing',
51
+ ])
52
+ })
53
+
54
+ it('does not swallow a word after a boolean flag', () => {
55
+ expect(positionalWords(['--verbose', 'ship'])).toEqual(['ship'])
56
+ })
57
+
58
+ it('returns nothing for a flags-only invocation', () => {
59
+ expect(positionalWords(['--json'])).toEqual([])
60
+ })
61
+
62
+ it('treats a value that looks like a word as a value, not a task word', () => {
63
+ expect(positionalWords(['--permission-mode', 'plan', 'do', 'work'])).toEqual(['do', 'work'])
64
+ })
65
+ })
66
+
67
+ describe('the task the planner is given', () => {
68
+ /** What the dispatcher passes to `pipeline` as `--text`. */
69
+ const taskText = (args: string[]): string => positionalWords(args).join(' ')
70
+
71
+ it('reassembles an unquoted request in order', () => {
72
+ expect(taskText(['add', 'rate', 'limiting', 'to', 'the', 'API'])).toBe(
73
+ 'add rate limiting to the API',
74
+ )
75
+ })
76
+
77
+ it('is identical for the quoted and unquoted forms of the same request', () => {
78
+ expect(taskText(['add', 'rate', 'limiting'])).toBe(taskText(['add rate limiting']))
79
+ })
80
+
81
+ it('is unaffected by where the flags sit', () => {
82
+ const want = 'refactor the auth module'
83
+ expect(taskText(['refactor', 'the', 'auth', 'module', '--verbose'])).toBe(want)
84
+ expect(taskText(['--verbose', 'refactor', 'the', 'auth', 'module'])).toBe(want)
85
+ expect(taskText(['refactor', '--verbose', 'the', 'auth', 'module'])).toBe(want)
86
+ })
87
+ })
88
+
89
+ describe('status words stay a status query', () => {
90
+ /** The dispatcher's rule: a status word alone, with no other words after it. */
91
+ const STATUS_WORDS = ['status', 'state', 'info', 'ls', 'list']
92
+ const isStatusQuery = (args: string[]): boolean => {
93
+ const words = positionalWords(args)
94
+ return words.length === 1 && STATUS_WORDS.includes(words[0])
95
+ }
96
+
97
+ it('treats a bare status word as a status query', () => {
98
+ for (const w of STATUS_WORDS) expect(isStatusQuery([w])).toBe(true)
99
+ })
100
+
101
+ it('still does so when flags accompany it', () => {
102
+ expect(isStatusQuery(['status', '--json'])).toBe(true)
103
+ })
104
+
105
+ it('treats a status word that opens a sentence as a task', () => {
106
+ // "status" alone means "where do things stand"; "status page for the admin"
107
+ // is a feature, and planning it must not be hijacked.
108
+ expect(isStatusQuery(['status', 'page', 'for', 'the', 'admin'])).toBe(false)
109
+ expect(isStatusQuery(['list', 'all', 'users', 'in', 'the', 'dashboard'])).toBe(false)
110
+ })
111
+ })
112
+
113
+ describe('splitTaskFlags', () => {
114
+ it('forwards a flag the planner reads, with its value', () => {
115
+ // The defect: --adapter was dropped, and the run used the auto-detected
116
+ // adapter while saying nothing about it.
117
+ expect(splitTaskFlags(['add', 'caching', '--adapter', 'codex'])).toEqual({
118
+ forward: ['--adapter', 'codex'],
119
+ unknown: [],
120
+ })
121
+ })
122
+
123
+ it('forwards the short form and its value too', () => {
124
+ expect(splitTaskFlags(['ship', '-a', 'claude']).forward).toEqual(['-a', 'claude'])
125
+ })
126
+
127
+ it('forwards boolean flags without eating the next word', () => {
128
+ expect(splitTaskFlags(['ship', '--verbose', 'it']).forward).toEqual(['--verbose'])
129
+ })
130
+
131
+ it('reports a flag nobody on this path reads instead of dropping it', () => {
132
+ // --json belongs to the status screen; forwarding it would earn an
133
+ // "Unknown option" from the planner, and dropping it hid the mistake.
134
+ expect(splitTaskFlags(['add', 'caching', '--json']).unknown).toEqual(['--json'])
135
+ })
136
+
137
+ it('reports a misspelled flag rather than running without it', () => {
138
+ expect(splitTaskFlags(['add', 'caching', '--adaptr', 'codex']).unknown).toEqual(['--adaptr'])
139
+ })
140
+
141
+ it('does not mistake an unknown flag value for another unknown flag', () => {
142
+ expect(splitTaskFlags(['x', '--report-dir', 'out']).unknown).toEqual(['--report-dir'])
143
+ })
144
+
145
+ it('forwards several flags at once, keeping order', () => {
146
+ const { forward, unknown } = splitTaskFlags([
147
+ 'build', 'it', '--verbose', '--adapter', 'codex', '--skip-validation',
148
+ ])
149
+ expect(forward).toEqual(['--verbose', '--adapter', 'codex', '--skip-validation'])
150
+ expect(unknown).toEqual([])
151
+ })
152
+
153
+ it('finds nothing to forward or refuse in a bare task', () => {
154
+ expect(splitTaskFlags(['add', 'caching'])).toEqual({ forward: [], unknown: [] })
155
+ })
156
+ })
@@ -1,6 +1,7 @@
1
1
  import { resolve } from 'node:path'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { createConvoyStore } from './convoy/store.js'
4
+ import { selectLastRun } from './convoy/last-run.js'
4
5
  import { c } from './prompt.js'
5
6
  import type { CliContext } from './types.js'
6
7
 
@@ -29,16 +30,124 @@ const CONVOY_HELP = `
29
30
  opencastle convoy run -f <spec> Execute a spec you wrote by hand
30
31
 
31
32
  Options:
32
- --dry-run Plan only; do not execute
33
- --verbose Stream agent output
34
- --json Machine-readable status
35
- --help, -h Show this help
33
+ --dry-run Plan only; do not execute
34
+ --verbose Stream agent output
35
+ --adapter, -a <name> Agent runtime to plan and run with
36
+ --skip-validation Skip PRD and spec validation passes
37
+ --json Machine-readable status
38
+ --help, -h Show this help
36
39
 
37
40
  run and plan take their own options — try: opencastle convoy run --help
38
41
 
39
42
  This namespace is experimental and may change or be removed.
40
43
  `
41
44
 
45
+ /**
46
+ * Flags that take a separate value token.
47
+ *
48
+ * Needed to tell a task's words from a flag's argument. `opencastle convoy fix
49
+ * the login bug --adapter codex` must plan "fix the login bug" and not "fix the
50
+ * login bug codex".
51
+ *
52
+ * `bin/cli.mjs` has already split any `--flag=value` form before this runs, so
53
+ * only the space form reaches here.
54
+ */
55
+ const FLAGS_WITH_VALUES = new Set([
56
+ '--adapter',
57
+ '-a',
58
+ '--file',
59
+ '-f',
60
+ '--prd',
61
+ '--complexity',
62
+ '--output-prd',
63
+ '--output-spec',
64
+ '--concurrency',
65
+ '-c',
66
+ '--permission-mode',
67
+ '--report-dir',
68
+ '--formula',
69
+ '--set',
70
+ '--watch-config',
71
+ '--convoy',
72
+ '--resolution',
73
+ ])
74
+
75
+ /**
76
+ * Flags the planner reads, forwarded from the task path.
77
+ *
78
+ * `opencastle convoy "add rate limiting" --adapter codex` used to run on the
79
+ * auto-detected adapter and say nothing: the task path kept an allowlist of two
80
+ * flags and silently discarded everything else. A flag that is accepted and
81
+ * ignored is the defect `bin/cli.mjs` refuses unknown options to prevent, and
82
+ * its comment exempts `convoy` on the grounds that this file validates its own
83
+ * input — which, on this path, it did not.
84
+ *
85
+ * `--text` is not here because the task itself supplies it, and `--prd` is not
86
+ * because `SUBCOMMAND_FLAGS` sends it to `convoy plan` with a pointer.
87
+ */
88
+ const TASK_FLAGS = new Set([
89
+ '--adapter',
90
+ '-a',
91
+ '--verbose',
92
+ '--dry-run',
93
+ '--dryRun',
94
+ '--skip-validation',
95
+ '--complexity',
96
+ '--output-prd',
97
+ '--output-spec',
98
+ ])
99
+
100
+ /**
101
+ * The words of the task, with the flags and their values taken out.
102
+ *
103
+ * A shell splits an unquoted task into one argument per word, and this command
104
+ * used to read only the first of them: `opencastle convoy add rate limiting to
105
+ * the API` planned a feature called "add". No error — it went on to spend a full
106
+ * PRD round-trip on the wrong request, and the quoted form that works is the
107
+ * only one our own "Start one:" hint shows.
108
+ *
109
+ * Flag values come out with their flag, so `--adapter codex` cannot contribute
110
+ * the word "codex" to a task description.
111
+ */
112
+ export function positionalWords(args: string[]): string[] {
113
+ const out: string[] = []
114
+ for (let i = 0; i < args.length; i++) {
115
+ const arg = args[i]
116
+ if (arg.startsWith('-')) {
117
+ if (FLAGS_WITH_VALUES.has(arg)) i++
118
+ continue
119
+ }
120
+ out.push(arg)
121
+ }
122
+ return out
123
+ }
124
+
125
+ /**
126
+ * The flags of a task invocation, split into what the planner gets and what
127
+ * nobody recognises.
128
+ *
129
+ * Returning the unknown ones rather than dropping them is the whole point: they
130
+ * become an error naming what was accepted, instead of a run that quietly did
131
+ * something other than what was asked.
132
+ */
133
+ export function splitTaskFlags(args: string[]): { forward: string[]; unknown: string[] } {
134
+ const forward: string[] = []
135
+ const unknown: string[] = []
136
+ for (let i = 0; i < args.length; i++) {
137
+ const arg = args[i]
138
+ if (!arg.startsWith('-')) continue
139
+ if (TASK_FLAGS.has(arg)) {
140
+ forward.push(arg)
141
+ // A value-taking flag carries its value across with it.
142
+ if (FLAGS_WITH_VALUES.has(arg) && i + 1 < args.length) forward.push(args[++i])
143
+ continue
144
+ }
145
+ unknown.push(arg)
146
+ if (FLAGS_WITH_VALUES.has(arg)) i++
147
+ }
148
+ return { forward, unknown }
149
+ }
150
+
42
151
  /** Delegate to an existing command module, passing through remaining args. */
43
152
  async function delegate(mod: string, ctx: CliContext, args: string[]): Promise<void> {
44
153
  const loaded = (await import(`./${mod}.js`)) as {
@@ -51,12 +160,23 @@ interface LastRun {
51
160
  id: string
52
161
  name: string
53
162
  status: string
163
+ /** Which orchestrator owns it — `resume` hands a pipeline to a different one. */
164
+ kind: 'pipeline' | 'convoy'
54
165
  total: number
55
166
  done: number
56
167
  failed: number
57
168
  pending: number
58
169
  }
59
170
 
171
+ /**
172
+ * The same run `opencastle convoy resume` would continue.
173
+ *
174
+ * Read through `selectLastRun` rather than `getLatestConvoy`, which is what this
175
+ * used to call. The two answers differed whenever a project had run a pipeline:
176
+ * this screen named the newest convoy and advised `resume`, and `resume` then
177
+ * reopened the pipeline instead. Advice that names a different run than the
178
+ * command acts on is worse than no advice.
179
+ */
60
180
  function readLastRun(projectRoot: string): LastRun | null {
61
181
  const dbPath = resolve(projectRoot, '.opencastle', 'convoy.db')
62
182
  if (!existsSync(dbPath)) return null
@@ -67,13 +187,22 @@ function readLastRun(projectRoot: string): LastRun | null {
67
187
  return null
68
188
  }
69
189
  try {
70
- const convoy = store.getLatestConvoy()
71
- if (!convoy) return null
72
- const tasks = store.getTasksByConvoy(convoy.id)
190
+ const last = selectLastRun(store)
191
+ if (!last) return null
192
+
193
+ // A pipeline's progress is the progress of every convoy in it, so the counts
194
+ // come from all of them rather than from a single spec's task list.
195
+ const convoyIds =
196
+ last.kind === 'pipeline'
197
+ ? store.getConvoysByPipeline(last.record.id).map((c) => c.id)
198
+ : [last.record.id]
199
+ const tasks = convoyIds.flatMap((id) => store.getTasksByConvoy(id))
200
+
73
201
  return {
74
- id: convoy.id,
75
- name: convoy.name,
76
- status: convoy.status,
202
+ id: last.record.id,
203
+ name: last.record.name,
204
+ status: last.record.status,
205
+ kind: last.kind,
77
206
  total: tasks.length,
78
207
  done: tasks.filter((t) => t.status === 'done').length,
79
208
  failed: tasks.filter((t) => t.status === 'failed' || t.status === 'gate-failed').length,
@@ -104,7 +233,10 @@ function renderStatus(last: LastRun | null, json: boolean): void {
104
233
  last.status === 'done' ? c.green('✓') : last.status === 'running' ? c.cyan('▶') : c.yellow('!')
105
234
 
106
235
  console.log(`\n 🚚 ${c.bold('Convoy')} ${c.dim('(experimental)')}\n`)
107
- console.log(` ${mark} ${c.bold(last.name)} ${c.dim(`— ${last.status}`)}`)
236
+ console.log(
237
+ ` ${mark} ${c.bold(last.name)} ${c.dim(`— ${last.status}`)}` +
238
+ (last.kind === 'pipeline' ? c.dim(' (pipeline)') : ''),
239
+ )
108
240
  console.log(
109
241
  ` ${last.done}/${last.total} done` +
110
242
  (last.failed ? c.yellow(`, ${last.failed} failed`) : '') +
@@ -112,10 +244,13 @@ function renderStatus(last: LastRun | null, json: boolean): void {
112
244
  )
113
245
  console.log('')
114
246
 
115
- if (last.failed > 0) {
247
+ // `retry` reopens the failed tasks of a single convoy. A pipeline is a chain
248
+ // of them, and `resume` is what carries the chain on past a failed link — so
249
+ // advising `retry` here named a verb that would have run one link in isolation.
250
+ if (last.failed > 0 && last.kind === 'convoy') {
116
251
  console.log(` ${c.bold('Next:')} ${c.cyan('opencastle convoy retry')}`)
117
252
  console.log(` ${c.dim('re-runs only the failed tasks')}`)
118
- } else if (last.pending > 0 || last.status === 'running') {
253
+ } else if (last.failed > 0 || last.pending > 0 || last.status === 'running') {
119
254
  console.log(` ${c.bold('Next:')} ${c.cyan('opencastle convoy resume')}`)
120
255
  console.log(` ${c.dim('continues from the last checkpoint')}`)
121
256
  } else {
@@ -137,10 +272,7 @@ export default async function convoy(ctx: CliContext): Promise<void> {
137
272
  return
138
273
  }
139
274
 
140
- // `--json` belongs to the status path; forwarding it to the planner would only
141
- // earn an "Unknown option" from an arg parser that has never heard of it.
142
- const PLANNER_FLAGS = new Set(['--dry-run', '--verbose'])
143
- const passthrough = args.filter((a) => PLANNER_FLAGS.has(a))
275
+ const positionals = positionalWords(args)
144
276
 
145
277
  switch (sub) {
146
278
  case undefined:
@@ -204,7 +336,7 @@ export default async function convoy(ctx: CliContext): Promise<void> {
204
336
  // a feature request. `convoy status` used to spend 95 seconds generating a PRD
205
337
  // for a feature called "status" — and it is the obvious thing to type, since
206
338
  // the bare command prints a status report.
207
- if (['status', 'state', 'info', 'ls', 'list'].includes(sub)) {
339
+ if (['status', 'state', 'info', 'ls', 'list'].includes(sub) && positionals.length === 1) {
208
340
  renderStatus(readLastRun(process.cwd()), args.includes('--json'))
209
341
  return
210
342
  }
@@ -212,5 +344,16 @@ export default async function convoy(ctx: CliContext): Promise<void> {
212
344
  // Anything else is a task description: plan it, then execute. `pipeline` takes
213
345
  // it as a flag value, so name it — passing it positionally made the one command
214
346
  // this tool prints under "Start one:" fail with "Unknown option".
215
- await delegate('pipeline', ctx, ['--text', sub, ...passthrough])
347
+ //
348
+ // Every word, not just the first. An unquoted task arrives as one argument per
349
+ // word, and taking `sub` alone silently planned the first of them.
350
+ const { forward, unknown } = splitTaskFlags(args)
351
+ if (unknown.length > 0) {
352
+ const accepted = [...TASK_FLAGS].sort().join(' ')
353
+ console.error(` ${c.red('✗')} Unknown option for a convoy task: ${unknown[0]}`)
354
+ console.error(` ${c.dim('Accepts:')} ${accepted} --help`)
355
+ console.error(` ${c.dim('For run or plan options:')} opencastle convoy run --help`)
356
+ process.exit(1)
357
+ }
358
+ await delegate('pipeline', ctx, ['--text', positionals.join(' '), ...forward])
216
359
  }
@@ -70,4 +70,17 @@ describe('the publish workflow', () => {
70
70
  expect(publish).toBeGreaterThanOrEqual(0)
71
71
  expect(tag).toBeGreaterThan(publish)
72
72
  })
73
+
74
+ it('writes a tag and never a branch', () => {
75
+ // `main` is protected by a ruleset with an empty bypass list, so a push to
76
+ // it is rejected — and the step that tried it ran *after* the publish had
77
+ // already succeeded. 0.36.0 reached npm while the repository kept no record
78
+ // of it: no tag, no release, and a version the next run would try again.
79
+ const pushes = steps
80
+ .flatMap(s => [...(s.run ?? '').matchAll(/git push origin ([^\s"']*"?[^\s"']*)/g)])
81
+ .map(m => m[1])
82
+ expect(pushes.length, 'nothing pushes at all — has the tag step gone?').toBeGreaterThan(0)
83
+ const toBranch = pushes.filter(ref => !/tag|TAG|v?\$\{/.test(ref))
84
+ expect(toBranch, `pushes a branch the ruleset will reject: ${toBranch.join(', ')}`).toEqual([])
85
+ })
73
86
  })
@@ -3,6 +3,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { tmpdir } from 'node:os'
5
5
  import type { Task, ExecuteOptions, ExecuteResult } from '../../convoy/spec-types.js'
6
+ import { codexSandboxFor } from './permission-modes.js'
6
7
 
7
8
  /** Adapter name */
8
9
  export const name = 'codex'
@@ -28,12 +29,19 @@ export async function execute(task: Task, options: ExecuteOptions = {}): Promise
28
29
  const tempDir = mkdtempSync(join(tmpdir(), 'opencastle-codex-'))
29
30
  const lastMessagePath = join(tempDir, 'last-message.txt')
30
31
 
32
+ // The sandbox the worker runs in, from the requested permission mode. This
33
+ // was hardcoded to `workspace-write`, so `--permission-mode plan` — or
34
+ // `default`, which is meant to leave a non-interactive worker writing nothing
35
+ // — produced a worker with full write access to the workspace anyway.
36
+ // `acceptEdits` and no mode at all both still mean `workspace-write`.
37
+ const sandbox = codexSandboxFor(options.permissionMode)
38
+
31
39
  const args = [
32
40
  '-a',
33
41
  'never',
34
42
  'exec',
35
43
  '-s',
36
- 'workspace-write',
44
+ sandbox,
37
45
  '--color',
38
46
  'never',
39
47
  '--skip-git-repo-check',