wicked-crew 0.17.0 → 0.17.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 (71) hide show
  1. package/README.md +27 -9
  2. package/dist/api/chat-jobs.d.ts +163 -0
  3. package/dist/api/chat-jobs.d.ts.map +1 -0
  4. package/dist/api/chat-jobs.js +767 -0
  5. package/dist/api/chat-jobs.js.map +1 -0
  6. package/dist/api/chat-proposals.d.ts +149 -3
  7. package/dist/api/chat-proposals.d.ts.map +1 -1
  8. package/dist/api/chat-proposals.js +831 -11
  9. package/dist/api/chat-proposals.js.map +1 -1
  10. package/dist/api/delivery-assurance.d.ts.map +1 -1
  11. package/dist/api/delivery-assurance.js +5 -2
  12. package/dist/api/delivery-assurance.js.map +1 -1
  13. package/dist/api/product.d.ts +79 -2
  14. package/dist/api/product.d.ts.map +1 -1
  15. package/dist/api/product.js +145 -66
  16. package/dist/api/product.js.map +1 -1
  17. package/dist/api/recording.d.ts +60 -3
  18. package/dist/api/recording.d.ts.map +1 -1
  19. package/dist/api/recording.js +51 -38
  20. package/dist/api/recording.js.map +1 -1
  21. package/dist/api/routes.d.ts +76 -7
  22. package/dist/api/routes.d.ts.map +1 -1
  23. package/dist/api/routes.js +697 -51
  24. package/dist/api/routes.js.map +1 -1
  25. package/dist/api/run-timing-index.d.ts +12 -1
  26. package/dist/api/run-timing-index.d.ts.map +1 -1
  27. package/dist/api/run-timing-index.js +35 -0
  28. package/dist/api/run-timing-index.js.map +1 -1
  29. package/dist/api/server.d.ts.map +1 -1
  30. package/dist/api/server.js +3 -1
  31. package/dist/api/server.js.map +1 -1
  32. package/dist/apps/exec/texts.d.ts +1 -1
  33. package/dist/core/adapter.d.ts +11 -1
  34. package/dist/core/adapter.d.ts.map +1 -1
  35. package/dist/core/adapter.js +29 -1
  36. package/dist/core/adapter.js.map +1 -1
  37. package/dist/core/builtin-catalog.d.ts.map +1 -1
  38. package/dist/core/builtin-catalog.js +2 -0
  39. package/dist/core/builtin-catalog.js.map +1 -1
  40. package/dist/core/deliver-text.d.ts +42 -6
  41. package/dist/core/deliver-text.d.ts.map +1 -1
  42. package/dist/core/deliver-text.js +204 -27
  43. package/dist/core/deliver-text.js.map +1 -1
  44. package/dist/core/deliver.d.ts.map +1 -1
  45. package/dist/core/deliver.js +28 -7
  46. package/dist/core/deliver.js.map +1 -1
  47. package/dist/core/qe-acceptance-setting.d.ts.map +1 -1
  48. package/dist/core/qe-acceptance-setting.js +6 -0
  49. package/dist/core/qe-acceptance-setting.js.map +1 -1
  50. package/dist/team/routes.d.ts +10 -0
  51. package/dist/team/routes.d.ts.map +1 -1
  52. package/dist/team/routes.js +27 -0
  53. package/dist/team/routes.js.map +1 -1
  54. package/dist/workflow-catalog/build-v2.d.ts +90 -0
  55. package/dist/workflow-catalog/build-v2.d.ts.map +1 -0
  56. package/dist/workflow-catalog/build-v2.js +527 -0
  57. package/dist/workflow-catalog/build-v2.js.map +1 -0
  58. package/dist/workflow-catalog/catalog-data-v2.d.ts +12 -0
  59. package/dist/workflow-catalog/catalog-data-v2.d.ts.map +1 -0
  60. package/dist/workflow-catalog/catalog-data-v2.js +2582 -0
  61. package/dist/workflow-catalog/catalog-data-v2.js.map +1 -0
  62. package/dist/workflow-catalog/seeds-v2.d.ts +91 -0
  63. package/dist/workflow-catalog/seeds-v2.d.ts.map +1 -0
  64. package/dist/workflow-catalog/seeds-v2.js +2 -0
  65. package/dist/workflow-catalog/seeds-v2.js.map +1 -0
  66. package/dist/workflow-catalog/shape.d.ts +97 -0
  67. package/dist/workflow-catalog/shape.d.ts.map +1 -0
  68. package/dist/workflow-catalog/shape.js +97 -0
  69. package/dist/workflow-catalog/shape.js.map +1 -0
  70. package/endpoint-manifest.json +33 -3
  71. package/package.json +23 -4
@@ -68,9 +68,12 @@ import { TestSetIndex } from '../qe/test-sets.js';
68
68
  import { estateExe, parseEstateTotals, readBlastRadiusPages, resolveProjectGraphBinding } from '../projects/graph.js';
69
69
  import { registerProjectRoutes } from '../projects/routes.js';
70
70
  import { registerProjectAggregateRoutes } from './project-aggregates.js';
71
- import { registerProductRoutes } from './product.js';
71
+ import { composeLaunch, composePreflight, registerProductRoutes } from './product.js';
72
+ import { buildWorkflowCatalogV2, parseCommand, resolveOption } from '../workflow-catalog/build-v2.js';
73
+ import { DEFAULT_PROJECT_ID } from '../projects/default-project.js';
74
+ import { checkLaunchShape, LaunchShapeSchema, launchShapeOf, servedFor, withBriefLines } from '../workflow-catalog/shape.js';
72
75
  import { registerPresetRoutes } from '../presets/routes.js';
73
- import { registerTeamRoutes } from '../team/routes.js';
76
+ import { busRows, openPlanGateRev, registerTeamRoutes, workPlanAccepted } from '../team/routes.js';
74
77
  import { registerCampaignRoutes } from '../campaigns/routes.js';
75
78
  import { registerGovernanceWikiRoutes } from './governance-wiki.js';
76
79
  import { DEFAULT_STEERING_TYPE, STEERING_TYPE_VALUES, STEERING_TYPES, registerGovernanceSteeringRoutes, } from './governance-steering.js';
@@ -82,7 +85,7 @@ import { registerDefaultEvalRoutes, runAndRecord } from '../evals/routes.js';
82
85
  import { prepareRunEvalsLaunch, RUN_EVALS_WORKFLOW } from '../evals/workflow.js';
83
86
  import { defaultReplaySet } from '../evals/replay.js';
84
87
  import { gardenRootFor } from '../learn/scheduler.js';
85
- import { DEMO_PRESET, demoLaunchRoots, registerDemoDocumentRoute, registerDemoRoutes, registerWalkthroughRoutes, walkthroughAcceptance } from './recording.js';
88
+ import { DEMO_PRESET, demoLaunch, demoLaunchRoots, registerDemoDocumentRoute, registerDemoRoutes, registerWalkthroughRoutes, walkthroughAcceptance } from './recording.js';
86
89
  import { projectDocsRoot } from '../interactive/project-root.js';
87
90
  import { registerSkillsRoutes } from './skills.js';
88
91
  import { registerSourceRoutes } from '../sources/routes.js';
@@ -121,7 +124,9 @@ const BRIEF_COPY_MAX = 512 * 1024;
121
124
  import { registerInteractiveDocDelete } from '../interactive/doc-delete-routes.js';
122
125
  import { registerInteractiveDocChecks } from '../interactive/doc-checks-routes.js';
123
126
  import { crewStateHome, stateHomeOfDb } from '../projects/state-home.js';
124
- import { ChatProposals, LaunchOnceRegistry, RecordingStubDispatcher, runCostFromEvents } from './chat-proposals.js';
127
+ import { demoShowOf, factsOf, inputLines, jobLaunchCommon, personPid, requestDigest, SELF_SEATED } from './chat-jobs.js';
128
+ import { CATALOG_V2_CARDS } from '../workflow-catalog/catalog-data-v2.js';
129
+ import { ChatProposals, LaunchOnceRegistry, proposalRunId, RecordingStubDispatcher, RevisionEditsSchema, runCostFromEvents } from './chat-proposals.js';
125
130
  import { CATALOG_SEEDS } from '../workflow-catalog/catalog-data.js';
126
131
  import { registerInteractiveDocList } from '../interactive/doc-list-routes.js';
127
132
  import { REVIEWS_DIRNAME } from '../interactive/review-ledger.js';
@@ -221,11 +226,6 @@ function codeGraphDbOr503(repo, reply) {
221
226
  return null;
222
227
  }
223
228
  }
224
- /**
225
- * `true` after answering **409** when the repo's registered folder is gone, BEFORE anything spawns
226
- * there: Node reports a missing spawn `cwd` as `spawn <binary> ENOENT`, which named an installed
227
- * binary as the fault (rig, tiny-math). The words are the finding's, the same everywhere.
228
- */
229
229
  function refusedMissingFolder(repo, reply) {
230
230
  const missing = repoFolderMissing(repo);
231
231
  if (missing === null)
@@ -236,6 +236,22 @@ function refusedMissingFolder(repo, reply) {
236
236
  function message(err) {
237
237
  return err instanceof Error ? err.message : String(err);
238
238
  }
239
+ /**
240
+ * What the shared launch function answers (DES-CHAT-FIRST-001 C3): the status and body `POST /runs` sends. Shaped like
241
+ * the reply the route body was written against, so the launch policy reads the same in one place for every launcher.
242
+ */
243
+ export class LaunchReply {
244
+ statusCode = 200;
245
+ payload = undefined;
246
+ code(statusCode) {
247
+ this.statusCode = statusCode;
248
+ return this;
249
+ }
250
+ send(payload) {
251
+ this.payload = payload;
252
+ return this;
253
+ }
254
+ }
239
255
  /**
240
256
  * Turns a failed parse into a 400 body, naming any field the schema does not know.
241
257
  *
@@ -560,6 +576,8 @@ export const LaunchSchema = z.strictObject({
560
576
  * and the engine refuses either on a run whose workflow does not require QE acceptance. */
561
577
  skipQeAcceptance: z.strictObject({ reason: z.string().trim().min(1).max(2000) }).optional(),
562
578
  forceQeAcceptance: z.boolean().optional(),
579
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.4) What this launch is the shape of; judged against the current catalog. */
580
+ shape: LaunchShapeSchema.optional(),
563
581
  }).refine((b) => b.skipQeAcceptance === undefined || b.forceQeAcceptance !== true, {
564
582
  path: ['forceQeAcceptance'],
565
583
  error: 'skipQeAcceptance and forceQeAcceptance are mutually exclusive — skip it with a reason, or force it',
@@ -594,12 +612,16 @@ export const LaunchSchema = z.strictObject({
594
612
  * The ENGINE refuses each at any other gate (a 409 naming the gate it answers) — and `rejudge`
595
613
  * while no judge seat is eligible ({@link GateInfo.rejudge} says beforehand). */
596
614
  export const ESCALATION_ACTIONS = ['extend', 'targeted', 'accept_partial', 'accept_suggestion', 'rejudge', 'retry_rules'];
597
- /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) At a `rules_unchecked` gate (a steering rule no judge
598
- * ruled on): `retry_rules` (an escalation arm above) re-runs the rule check on the same work, the
599
- * step's seat not run again; `skip_rules` skips unchecked rules, each with a written reason
600
- * (`skipRules: [{id, reason}]`, required), then re-runs it. A skip is labelled on the run, the gate
601
- * and the delivery receipts. The engine refuses both at any other gate, and a skip of a rule that
602
- * is not unchecked (a broken rule denies). Skipping is the human operator's call alone. */
615
+ /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) At a gate the steering-rule check holds or denies:
616
+ * `retry_rules` (an escalation arm above) re-runs the rule check on the same work, the step's seat
617
+ * not run again; `skip_rules` skips held rules (unchecked, a waiver to confirm, or, rev 2 / api-types
618
+ * 0.193.0, disputed: no council ruling), each with a written reason (`skipRules: [{id, reason}]`,
619
+ * required), then re-runs it. A skip is labelled on the run, the gate and the delivery receipts.
620
+ * Since wicked-core-ts 0.15.30 the engine takes both wherever a rule layer is in the gated unit's
621
+ * denial record (behind a reviewer's FAIL, at `review_adjudication`), refuses them at any other
622
+ * gate, and refuses a skip of a rule that is not held (a broken rule denies, a council's broken
623
+ * ruling too): crew forwards both unfiltered, so the engine is the one check, and its refusal is
624
+ * the 409. Skipping is the human operator's call alone. */
603
625
  export const SKIP_RULES_ACTION = 'skip_rules';
604
626
  /** (core#820) A consent gate's answer token: `consent:<choice id>` approves that row of the dry-run
605
627
  * plan (the engine refuses an id its plan does not offer); `reject` stays the decline. */
@@ -657,6 +679,9 @@ export const GateSchema = z.strictObject({
657
679
  /** api-types 0.44.0 — the gate this decision answers (its unit `ord`). A mismatch with the run's
658
680
  * open gate is a 409 `gate_changed`: the decision was made on a gate that is no longer open. */
659
681
  ord: z.int().nonnegative().optional(),
682
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.6) At a `plan_approval` gate: the plan revision this answer was made on.
683
+ * Passed with `ord` into the engine's own serialized decision, which refuses a stale one (`gate_changed`). */
684
+ planRev: z.int().nonnegative().optional(),
660
685
  /** (api-types 0.156.0, DES-VOICE) The person answered by voice and confirmed it on screen: recorded on the
661
686
  * `gate.decided` audit line and the decided-gate history ("by voice, confirmed"). It grants nothing. */
662
687
  input: z.literal('voice').optional(),
@@ -665,14 +690,14 @@ export const GateSchema = z.strictObject({
665
690
  * declined. Absent = every drafted rule lands, as before. 409 `no_draft` unless the run waits at its
666
691
  * steering-author propose gate with a readable draft; 400 with anything but a plain approve. */
667
692
  keepRules: z.array(z.string().min(1).max(256)).max(500).optional(),
668
- /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) With `action: 'skip_rules'`: the unchecked rules to
669
- * skip, each with the person's written reason. */
693
+ /** (DES-RULE-CHECK-001 S2, api-types 0.190.0) With `action: 'skip_rules'`: the held rules to skip
694
+ * (unchecked, waived or disputed), each with the person's written reason. */
670
695
  skipRules: z
671
696
  .array(z.strictObject({ id: z.string().trim().min(1).max(256), reason: z.string().trim().min(1).max(2000) }))
672
697
  .min(1)
673
698
  .max(500)
674
699
  .optional(),
675
- }).refine((b) => (b.action === SKIP_RULES_ACTION) === (b.skipRules !== undefined), { path: ['skipRules'], error: 'skip_rules needs `skipRules`: [{id, reason}] for each unchecked rule you skip, each with your written reason; skipRules goes with skip_rules only' }).refine((b) => b.action !== SKIP_RULES_ACTION || (b.approve && b.amend === undefined && b.amendScope === undefined && b.plan === undefined), { path: ['action'], error: 'skip_rules takes approve: true and no amend, amendScope or plan — the reasons ride skipRules' }).refine((b) => b.skipRules === undefined || new Set(b.skipRules.map((r) => r.id)).size === b.skipRules.length, { path: ['skipRules'], error: 'skipRules names a rule twice' }).refine((b) => b.keepRules === undefined || (b.approve && (b.action === undefined || b.action === 'approve') && b.plan === undefined), { path: ['keepRules'], error: 'keepRules goes with a plain approve (no action other than approve, no plan) of a steering-author propose gate' }).refine((b) => b.action === undefined
700
+ }).refine((b) => (b.action === SKIP_RULES_ACTION) === (b.skipRules !== undefined), { path: ['skipRules'], error: 'skip_rules needs `skipRules`: [{id, reason}] for each rule you skip (unchecked, waived or disputed), each with your written reason; skipRules goes with skip_rules only' }).refine((b) => b.action !== SKIP_RULES_ACTION || (b.approve && b.amend === undefined && b.amendScope === undefined && b.plan === undefined), { path: ['action'], error: 'skip_rules takes approve: true and no amend, amendScope or plan — the reasons ride skipRules' }).refine((b) => b.skipRules === undefined || new Set(b.skipRules.map((r) => r.id)).size === b.skipRules.length, { path: ['skipRules'], error: 'skipRules names a rule twice' }).refine((b) => b.keepRules === undefined || (b.approve && (b.action === undefined || b.action === 'approve') && b.plan === undefined), { path: ['keepRules'], error: 'keepRules goes with a plain approve (no action other than approve, no plan) of a steering-author propose gate' }).refine((b) => b.action === undefined
676
701
  || (b.action === 'approve' || b.action === 'edit_plan' || b.action === 'amend_intent' || b.action === OPERATOR_JUDGMENT_ACTION || b.action === SKIP_QE_ACTION || b.action === SKIP_RULES_ACTION || isEscalationAction(b.action)) === b.approve, { path: ['action'], error: '`action` disagrees with `approve`: request_changes and reject require approve: false; approve, edit_plan, amend_intent, operator_judgment, skip_qe, skip_rules, extend, targeted, accept_partial, accept_suggestion, rejudge, retry_rules and consent:<id> require approve: true' }).refine(
677
702
  // (operator ruling 2026-10-21) The override's rationale IS its record: a blank one is a 400 here,
678
703
  // before the engine is asked.
@@ -839,6 +864,21 @@ export const ChatOpenSchema = z.strictObject({
839
864
  /** (api-types 0.169.0, DES-CHAT-ARTIFACTS-001 §6.3) "Ask about this" on a document no open chat holds: seed the
840
865
  * chat's repositories from the document's recorded binding, after an access check. */
841
866
  seedFromArtifact: z.string().max(200).optional(),
867
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.6) A `/` pick or a command with no chat open: the chat opens with this
868
+ * person-made proposal in it; its id and the proposal's derive from (the person, `requestId`). */
869
+ seed: z.strictObject({
870
+ card: z.string().trim().min(1).max(120),
871
+ option: z.string().trim().min(1).max(80).nullable().optional(),
872
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
873
+ words: z.string().max(8000).optional(),
874
+ source: z.enum(['pick', 'command']),
875
+ }).optional(),
876
+ requestId: z.string().trim().min(1).max(128).optional(),
877
+ /** (api-types 0.192.0) What the client renders (`['job']`). */
878
+ accepts: z.array(z.literal('job')).max(4).optional(),
879
+ }).refine((b) => b.seed === undefined || (b.requestId !== undefined && b.chatId === undefined), {
880
+ path: ['seed'],
881
+ error: 'seed needs requestId and no chatId: the chat id derives from you and the request',
842
882
  });
843
883
  /**
844
884
  * The `singleSeat` disclosure (crew#641, hole closed in crew#650) — built in ONE place so the 201
@@ -977,6 +1017,8 @@ runtime = {}) {
977
1017
  ? { context: true, proposals: true, create: true, refine: true, theme: true, demo: true, stub: true, stubOps }
978
1018
  : { context: true, proposals: true, create: realCreate, refine: false, theme: false, demo: false };
979
1019
  const proposalLaunchers = new LaunchOnceRegistry();
1020
+ /** (DES-CATALOG-002 §4.6) Job proposals in a chat: on wherever chat proposals are. */
1021
+ const chatJobProposalsOn = chatArtifactFlags.proposals;
980
1022
  if (chatArtifactsStub) {
981
1023
  // Under the registered `chats` entry (a new top-level state-home entry would make core refuse every launch), and
982
1024
  // not a `.jsonl` there (the boot sweep clears orphaned transcripts by that suffix).
@@ -1363,6 +1405,13 @@ runtime = {}) {
1363
1405
  const landingFailed = runTimingIndex.landingFailedOf(view.session.id);
1364
1406
  if (landingFailed !== undefined)
1365
1407
  view.session.landing_failed = landingFailed;
1408
+ // DES-CATALOG-002 §4.4: the shape it was launched as and the chat proposal whose Go launched it — ABSENT otherwise.
1409
+ const launchedShape = runTimingIndex.shapeOf(view.session.id);
1410
+ if (launchedShape !== undefined)
1411
+ view.session.shape = launchedShape;
1412
+ const fromProposal = runTimingIndex.fromProposalOf(view.session.id);
1413
+ if (fromProposal !== undefined)
1414
+ view.session.from_proposal = fromProposal;
1366
1415
  // crew#552: the onboarding run a chained capture was launched from — ABSENT otherwise.
1367
1416
  const chainedFrom = runTimingIndex.chainedFromOf(view.session.id);
1368
1417
  if (chainedFrom !== undefined)
@@ -1541,6 +1590,12 @@ runtime = {}) {
1541
1590
  voice: app.hasRoute({ method: 'POST', url: `${V}/voice/transcribe` }),
1542
1591
  // (api-types 0.168.0, wf-catalog) The categorised workflow catalog with the operator's usage.
1543
1592
  workflowCatalog: app.hasRoute({ method: 'GET', url: `${V}/workflows/catalog` }),
1593
+ // DES-CATALOG-002 §4.1: `?v=2` on the same route, and `shape` on every launch route.
1594
+ workflowCatalogV2: app.hasRoute({ method: 'GET', url: `${V}/workflows/catalog` }),
1595
+ launchShape: true,
1596
+ // DES-CATALOG-002 §4.6: person-made and revised job proposals, the revising hold, plan answers bound to planRev.
1597
+ chatJobProposals: chatJobProposalsOn,
1598
+ reshapeRun: chatJobProposalsOn,
1544
1599
  // (api-types 0.169.0, DES-CHAT-ARTIFACTS-001 §14) Per operation: A1 serves `context` (the chat sees the open
1545
1600
  // artifact and the runs the person names; `seedFromArtifact`); A2 (0.170.0) `proposals`. The operations are later
1546
1601
  // slices (all on, with `stub`, in the test configuration).
@@ -2288,29 +2343,55 @@ runtime = {}) {
2288
2343
  return { issues: [], appendedChars: 0, error: `linked issues could not be read: ${message(err)} — a launch now runs on the intent alone` };
2289
2344
  }
2290
2345
  });
2291
- // Launch a run (replaces POST /sessions). `clisJson` defaults to the roster;
2292
- // `sessionId` is minted if the client omits it.
2293
- app.post(`${V}/runs`, {
2294
- config: {
2295
- manifest: {
2296
- requestType: 'LaunchRunBody',
2297
- responseType: 'LaunchRunResponse',
2298
- // 404/409: unknown project / unknown campaignId (wicked-studio#27) /
2299
- // archived-or-synthesized project + busy engine + the state-home blocker
2300
- // (`state_home_unregistered`) + a roster with no eligible seat (`no_eligible_seat`,
2301
- // wicked-core#461 — see the catch below); 400: zod reject or a retryOf naming no
2302
- // existing run; 422: the base-skill intake refusal (`base_skill_refused`, crew#554);
2303
- // 501: campaignId attach on an engine addon without the campaign bindings ("upgrade
2304
- // the engine").
2305
- statusCodes: [201, 400, 404, 409, 422, 501],
2306
- },
2307
- },
2308
- }, async (req, reply) => {
2346
+ /**
2347
+ * (DES-CHAT-FIRST-001 C3, DES-CATALOG-002 §4.6) THE launch: the whole launch policy and provenance path of
2348
+ * `POST /runs`, shared by that route and every other launcher of a run (a chat job proposal's Go, a reshape). The
2349
+ * route parses nothing itself: the body is checked here, by the same schema, so no launcher has a side path.
2350
+ * `internal` carries what only crew may set (never a client field): the proposal a run was launched from.
2351
+ */
2352
+ /** What a shape is judged against: the engine's served defs, presets and phase catalog (DES-CATALOG-002 §4.4). */
2353
+ const shapeReads = {
2354
+ defs: () => adapter.listWorkflows(),
2355
+ presets: (projectId) => adapter.listPresets(projectId),
2356
+ entries: () => adapter.catalog(),
2357
+ };
2358
+ const launchRun = async (raw, ctx) => {
2359
+ const reply = new LaunchReply();
2360
+ const req = { body: raw, log: ctx.log, actor: ctx.actor };
2309
2361
  const parsed = LaunchSchema.safeParse(req.body);
2310
2362
  if (!parsed.success) {
2311
2363
  return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
2312
2364
  }
2313
- const b = parsed.data;
2365
+ const b = { ...parsed.data };
2366
+ // DES-CATALOG-002 §4.4: the words as the person gave them, before crew's framing line (the envelope's `words`, which
2367
+ // a reshape relaunches from), with any block an earlier launch appended taken out.
2368
+ const envelopeWords = stripLinkedIssues(stripRulesBrief(b.problem));
2369
+ // The shape as judged, re-judged just before the engine is called (the awaits between can see a preset saved).
2370
+ let shapeChecked = null;
2371
+ // DES-CATALOG-002 §4.4: a shape is judged against the CURRENT catalog and this launch's own target before anything is
2372
+ // read or committed; its framing line (and depth) goes first in the brief, crew's, never the client's.
2373
+ if (b.shape !== undefined) {
2374
+ const target = ctx.target === 'compose'
2375
+ ? { kind: 'compose' }
2376
+ : b.workflow === DEMO_PRESET
2377
+ ? { kind: 'demo' }
2378
+ : { kind: 'run', workflow: b.workflow };
2379
+ if (ctx.target !== 'compose' && b.plan !== undefined) {
2380
+ return reply.code(400).send({ code: 'shape_mismatch', error: 'a shape names a card, and a launch with its own plan runs no card' });
2381
+ }
2382
+ let served;
2383
+ try {
2384
+ served = await servedFor(shapeReads, b.projectId);
2385
+ }
2386
+ catch (err) {
2387
+ return reply.code(409).send({ code: 'catalog_unavailable', error: message(err) });
2388
+ }
2389
+ const verdict = checkLaunchShape(launchShapeOf(b.shape), target, served);
2390
+ if (!verdict.ok)
2391
+ return reply.code(verdict.code).send(verdict.body);
2392
+ shapeChecked = { shape: launchShapeOf(b.shape), target, resolution: verdict.resolved.resolved.resolution };
2393
+ b.problem = withBriefLines(b.problem, verdict.lines);
2394
+ }
2314
2395
  // The demo preset launches only from POST /projects/:id/demo (api/recording.ts), which mints the run's
2315
2396
  // demo root and brief first: launched here directly it would have neither.
2316
2397
  if (b.workflow === DEMO_PRESET && (b.sessionId === undefined || !demoLaunchRoots.has(b.sessionId))) {
@@ -2695,6 +2776,20 @@ runtime = {}) {
2695
2776
  if (live !== null)
2696
2777
  return reply.code(409).send({ code: 'chat_busy', error: `This chat already has a job running (${live}). Wait, or stop that run.` });
2697
2778
  }
2779
+ // DES-CATALOG-002 §4.4 (codex r1): the effective resolution a shape was judged by is read again right before the
2780
+ // engine resolves the preset, so a preset saved during this launch's awaits refuses it rather than running a shape
2781
+ // the person did not see. (The engine has no snapshot binding; every chat-launched job is also held at its plan.)
2782
+ if (shapeChecked !== null) {
2783
+ try {
2784
+ const again = checkLaunchShape(shapeChecked.shape, shapeChecked.target, await servedFor(shapeReads, b.projectId));
2785
+ if (!again.ok || again.resolved.resolved.resolution !== shapeChecked.resolution) {
2786
+ return reply.code(409).send({ code: 'catalog_changed', error: 'the catalog changed while this was starting; check the job again' });
2787
+ }
2788
+ }
2789
+ catch (err) {
2790
+ return reply.code(409).send({ code: 'catalog_unavailable', error: message(err) });
2791
+ }
2792
+ }
2698
2793
  try {
2699
2794
  const runId = await adapter.launchRun(input);
2700
2795
  // crew#641/#642 (item 5): when a run is promoted from a chat, record how many seats
@@ -2763,6 +2858,30 @@ runtime = {}) {
2763
2858
  ...(b.actor !== undefined ? { actor: b.actor } : {}),
2764
2859
  // crew#627: which linked issues the daemon read into the problem, and which it could not.
2765
2860
  ...(linkedIssues !== undefined ? { linkedIssues } : {}),
2861
+ // DES-CATALOG-002 §4.4: the shape it was launched as, what it was launched with, and the proposal behind it.
2862
+ ...(b.shape !== undefined ? { shape: launchShapeOf(b.shape) } : {}),
2863
+ ...(ctx.fromProposal !== undefined ? { fromProposal: ctx.fromProposal } : {}),
2864
+ envelope: {
2865
+ words: envelopeWords,
2866
+ ...(b.repoRef !== undefined ? { repoRef: b.repoRef } : {}),
2867
+ ...(b.projectId !== undefined ? { projectId: b.projectId } : {}),
2868
+ ...(b.clisJson !== undefined ? { clisJson: b.clisJson } : {}),
2869
+ ...(b.primary !== undefined ? { primary: b.primary } : {}),
2870
+ ...(input.humanConfirm !== undefined ? { humanConfirm: input.humanConfirm } : {}),
2871
+ deliver,
2872
+ ...(b.deliverGate !== undefined ? { deliverGate: b.deliverGate } : {}),
2873
+ ...(b.chatId !== undefined ? { chatId: b.chatId } : {}),
2874
+ ...(b.skipQeAcceptance !== undefined ? { skipQeAcceptance: b.skipQeAcceptance } : {}),
2875
+ ...(b.forceQeAcceptance === true ? { forceQeAcceptance: true } : {}),
2876
+ ...(b.reducedAssurance === true ? { reducedAssurance: true } : {}),
2877
+ ...(b.power !== undefined ? { power: b.power } : {}),
2878
+ ...(b.revisesPr !== undefined ? { revisesPr: b.revisesPr } : {}),
2879
+ ...(b.campaignId !== undefined ? { campaignId: b.campaignId } : {}),
2880
+ ...(b.groupLabel !== undefined ? { groupLabel: b.groupLabel } : {}),
2881
+ ...(revisesPr !== undefined ? { baseRef: revisesPr.headRef } : {}),
2882
+ ...(b.shape !== undefined ? { shape: launchShapeOf(b.shape) } : {}),
2883
+ ...(ctx.fromProposal !== undefined ? { fromProposal: ctx.fromProposal } : {}),
2884
+ },
2766
2885
  });
2767
2886
  // Stamp the index live so the field is served without waiting for a daemon restart.
2768
2887
  if (chatSeatCount !== undefined && chatGrounded !== undefined) {
@@ -2883,6 +3002,136 @@ runtime = {}) {
2883
3002
  const busy = /busy|in flight|already/i.test(msg);
2884
3003
  return reply.code(busy ? 409 : 400).send({ error: msg });
2885
3004
  }
3005
+ };
3006
+ // Launch a run (replaces POST /sessions). `clisJson` defaults to the roster;
3007
+ // `sessionId` is minted if the client omits it.
3008
+ app.post(`${V}/runs`, {
3009
+ config: {
3010
+ manifest: {
3011
+ requestType: 'LaunchRunBody',
3012
+ responseType: 'LaunchRunResponse',
3013
+ // 404/409: unknown project / unknown campaignId (wicked-studio#27) /
3014
+ // archived-or-synthesized project + busy engine + the state-home blocker
3015
+ // (`state_home_unregistered`) + a roster with no eligible seat (`no_eligible_seat`,
3016
+ // wicked-core#461 — see the catch below); 400: zod reject or a retryOf naming no
3017
+ // existing run; 422: the base-skill intake refusal (`base_skill_refused`, crew#554);
3018
+ // 501: campaignId attach on an engine addon without the campaign bindings ("upgrade
3019
+ // the engine").
3020
+ statusCodes: [201, 400, 404, 409, 422, 501],
3021
+ },
3022
+ },
3023
+ }, async (req, reply) => {
3024
+ const out = await launchRun(req.body, { actor: actorOf(req), log: req.log });
3025
+ return reply.code(out.statusCode).send(out.payload);
3026
+ });
3027
+ /**
3028
+ * (DES-CATALOG-002 §4.6) The `job` launcher: a chat job proposal's Go, one launcher per launch kind, each with the
3029
+ * identity derived from the proposal (`sessionId` = its run id, so a retry finds and adopts it), the chat filing, the
3030
+ * shape, and the plan held (a repository job launched from a chat always stops at its first plan, whatever the
3031
+ * person's posture, so power mode is off for it).
3032
+ */
3033
+ const jobRefusalText = (payload) => {
3034
+ const b = payload;
3035
+ return `${typeof b?.error === 'string' ? b.error : 'the launch was refused'}${typeof b?.code === 'string' ? ` (${b.code})` : ''}`;
3036
+ };
3037
+ proposalLaunchers.register('job', {
3038
+ find: async (identity) => (await adapter.sessions()).includes(identity.runId),
3039
+ live: async (runId) => {
3040
+ const v = (await adapter.sessionsDetail()).find((x) => x.session.id === runId);
3041
+ return v !== undefined && !['completed', 'cancelled', 'failed'].includes(String(v.session.status));
3042
+ },
3043
+ launch: async (d) => {
3044
+ const p = d.resolution;
3045
+ if (p.shape === undefined || p.catalogRev === undefined)
3046
+ throw new Error('this proposal has no shape to launch');
3047
+ const ctx = { actor: d.actor, log: app.log };
3048
+ const projectId = p.filedIn.projectId;
3049
+ const words = (p.brief ?? p.words ?? '').trim();
3050
+ const served = await servedFor(shapeReads, projectId ?? undefined);
3051
+ const resolved = resolveOption(p.shape.card, p.shape.option, served);
3052
+ if (resolved === null)
3053
+ throw new Error(`${p.what.label} is no longer in the catalog`);
3054
+ const selfSeated = resolved.workflow !== null && SELF_SEATED.has(resolved.workflow);
3055
+ // The seats the person saw: the lead, and the roster narrowed to the proposal's keys.
3056
+ const lead = p.seats?.lead ?? undefined;
3057
+ const keys = p.seats?.keys ?? [];
3058
+ // A reshape inherits the held run's roster configuration; its membership is still the proposal's seats (codex r2).
3059
+ let inherited = null;
3060
+ if (p.relaunch?.clisJson !== undefined) {
3061
+ try {
3062
+ const parsedRoster = JSON.parse(p.relaunch.clisJson);
3063
+ if (Array.isArray(parsedRoster))
3064
+ inherited = parsedRoster;
3065
+ }
3066
+ catch {
3067
+ inherited = null;
3068
+ }
3069
+ }
3070
+ const current = launchRosterNaming(rosterWithStanding(), lead);
3071
+ // Inherited configuration for the seats it names; the current roster's entry for a seat added since (codex r3).
3072
+ const roster = inherited === null ? current : [...inherited, ...current.filter((s) => !inherited.some((i) => i.key === s.key))];
3073
+ const narrowed = keys.length > 0 ? roster.filter((s) => keys.includes(String(s.key))) : roster;
3074
+ const missingSeat = keys.find((k) => !roster.some((s) => String(s.key) === k));
3075
+ if (missingSeat !== undefined)
3076
+ throw new Error(`${missingSeat} is not on this daemon's roster; change who works on it`);
3077
+ const common = jobLaunchCommon(p, { runId: d.identity.runId, chatId: d.chatId }, {
3078
+ ...((inherited !== null || narrowed.length !== roster.length) && narrowed.length > 0 ? { clisJson: JSON.stringify(narrowed) } : {}),
3079
+ selfSeated,
3080
+ });
3081
+ if (p.launch === 'run' || p.launch === undefined) {
3082
+ if (resolved.workflow === null)
3083
+ throw new Error(`${p.what.label} has no workflow to run`);
3084
+ const lines = inputLines(p);
3085
+ const out = await launchRun({
3086
+ problem: [words === '' ? p.what.label : words, ...(lines.length > 0 ? [`Inputs:\n${lines.map((l) => `- ${l}`).join('\n')}`] : [])].join('\n\n'),
3087
+ workflow: resolved.workflow,
3088
+ ...(p.repoRefs?.[0] !== undefined ? { repoRef: p.repoRefs[0] } : {}),
3089
+ ...(projectId !== null && projectId !== DEFAULT_PROJECT_ID ? { projectId } : {}),
3090
+ ...common,
3091
+ humanConfirm: 'before:1',
3092
+ power: false,
3093
+ channel: 'studio',
3094
+ // §2.5: a reshape's replacement keeps the held run's delivery and grouping.
3095
+ ...(p.relaunch?.deliver !== undefined ? { deliver: p.relaunch.deliver } : {}),
3096
+ ...(p.relaunch?.deliverGate !== undefined && p.relaunch.deliver !== 'none' ? { deliverGate: p.relaunch.deliverGate } : {}),
3097
+ ...(p.relaunch?.revisesPr !== undefined && p.relaunch.deliver === 'pr' && p.repoRefs?.[0] !== undefined ? { revisesPr: p.relaunch.revisesPr } : {}),
3098
+ }, { ...ctx, fromProposal: d.pid });
3099
+ if (out.statusCode !== 201)
3100
+ throw new Error(jobRefusalText(out.payload));
3101
+ return;
3102
+ }
3103
+ if (p.launch === 'compose') {
3104
+ const req = p.inputs?.['requirements'];
3105
+ if (projectId === null || req === undefined || req.kind !== 'requirements')
3106
+ throw new Error('Backlog needs a project and the requirements you pick');
3107
+ const out = await composeLaunch(adapter, launchRun, projectId, { requirements: req.refs, ...(words !== '' ? { instructions: words } : {}), shape: common['shape'] }, ctx, {
3108
+ fromProposal: d.pid,
3109
+ humanConfirm: 'before:1',
3110
+ common,
3111
+ });
3112
+ if (out.code !== 202)
3113
+ throw new Error(jobRefusalText(out.body));
3114
+ return;
3115
+ }
3116
+ if (p.launch === 'demo') {
3117
+ const v = (id) => {
3118
+ const x = p.inputs?.[id];
3119
+ return x !== undefined && (x.kind === 'text' || x.kind === 'url') ? x.value : undefined;
3120
+ };
3121
+ // What to show is the person's own field, with the corrections carried (§4.6 rule 6).
3122
+ // What to show: the person's first words, their show field and the corrections, together (codex r3); its length
3123
+ // was checked before Start was offered (codex r4), never clipped here.
3124
+ const show = demoShowOf(p);
3125
+ const out = await demoLaunch(launchRun, projectId ?? DEFAULT_PROJECT_ID, { url: v('url') ?? '', audience: v('audience') ?? '', show, shape: common['shape'] }, ctx, {
3126
+ fromProposal: d.pid,
3127
+ common,
3128
+ });
3129
+ if (out.code !== 201)
3130
+ throw new Error(jobRefusalText(out.body));
3131
+ return;
3132
+ }
3133
+ throw new Error(`a ${p.launch} job does not start from a chat`);
3134
+ },
2886
3135
  });
2887
3136
  // Run list (replaces GET /sessions). Actionable-first; reconciles the gate and elicitation caches
2888
3137
  // so that terminal-run entries are pruned even when their terminal CoreEvent was missed.
@@ -3505,12 +3754,44 @@ runtime = {}) {
3505
3754
  ...(runtime.entityCount !== undefined ? { entityCount: runtime.entityCount } : {}),
3506
3755
  ...(runtime.freshenCheckout !== undefined ? { freshen: runtime.freshenCheckout } : {}),
3507
3756
  });
3757
+ /** (DES-CATALOG-002 §4.6) Chats whose client renders job proposals (`accepts: ['job']`), by its newest declaration. */
3758
+ const chatAccepts = new Map();
3759
+ /** A seed as the person route's body (one spelling, so its request digest is the same on every retry). */
3760
+ const seedBody = (seed, requestId) => ({
3761
+ card: seed.card,
3762
+ ...(seed.option !== undefined ? { option: seed.option } : {}),
3763
+ ...(seed.depth !== undefined ? { depth: seed.depth } : {}),
3764
+ ...(seed.words !== undefined ? { words: seed.words } : {}),
3765
+ source: seed.source,
3766
+ requestId,
3767
+ });
3768
+ /** The seeded chat's person-made proposal (`POST /chats {seed}`), made or found by its request id. */
3769
+ const seedProposal = async (chatId, seed, requestId, actor) => {
3770
+ const instance = chatHistory?.stateOf(chatId)?.instance ?? null;
3771
+ const out = await chatProposals.propose(chatId, seedBody(seed, requestId), actor, instance);
3772
+ if (out.code >= 300) {
3773
+ const b = out.body;
3774
+ app.log.warn(`[proposals] chat ${chatId}: its seed proposal was refused (${String(b.code ?? out.code)})`);
3775
+ return { refused: { code: typeof b.code === 'string' ? b.code : 'seed_refused', error: typeof b.error === 'string' ? b.error : 'the seed proposal was refused' } };
3776
+ }
3777
+ return { view: out.body.view };
3778
+ };
3779
+ /** A seed's card, checked before a chat is opened for it (a hidden card only by its alias). `null` = it resolves. */
3780
+ const seedCardRefusal = (card) => {
3781
+ if (card.startsWith('/'))
3782
+ return parseCommand(card) === null ? `no job has the command ${card.slice(0, 80)}` : null;
3783
+ const c = CATALOG_V2_CARDS.find((x) => x.id === card);
3784
+ if (c === undefined)
3785
+ return `there is no job called “${card.slice(0, 80)}”`;
3786
+ return c.hidden === true ? `${c.title} is reached only by its own command` : null;
3787
+ };
3508
3788
  app.post(`${V}/chats`, {
3509
3789
  config: {
3510
3790
  manifest: {
3511
3791
  requestType: 'ChatOpenBody',
3512
3792
  responseType: 'ChatOpenResponse',
3513
- statusCodes: [201, 400, 403, 404, 409, 500, 501],
3793
+ // 200: a seeded retry answers the chat its request already opened (api-types 0.192.0).
3794
+ statusCodes: [200, 201, 400, 403, 404, 409, 500, 501],
3514
3795
  },
3515
3796
  },
3516
3797
  }, async (req, reply) => {
@@ -3519,7 +3800,43 @@ runtime = {}) {
3519
3800
  return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
3520
3801
  }
3521
3802
  const b = parsed.data;
3522
- const chatId = b.chatId ?? randomUUID();
3803
+ // DES-CATALOG-002 §4.6: a seeded open is a person's, refused before a chat exists or a seat warms; its chat id
3804
+ // derives from (the person, the request), so a retry after a lost response lands on the same chat and proposal.
3805
+ let seedActor = null;
3806
+ let seedChatId;
3807
+ if (b.seed !== undefined) {
3808
+ if (!chatJobProposalsOn)
3809
+ return reply.code(400).send({ error: 'this daemon does not take job proposals from a chat' });
3810
+ seedActor = actorOf(req);
3811
+ if (!isHumanOperator(seedActor)) {
3812
+ audit.record('chat.proposal.refused', seedActor, { detail: { reason: 'not_a_person', what: 'seed' } });
3813
+ return reply.code(403).send({ code: 'proposal_refused', error: `only a person starts a chat with a job (you are ${seedActor.kind}/${seedActor.trust}). Nothing was opened.` });
3814
+ }
3815
+ const bad = seedCardRefusal(b.seed.card);
3816
+ if (bad !== null)
3817
+ return reply.code(400).send({ code: 'card_unknown', error: bad });
3818
+ seedChatId = proposalRunId(`seed\u0000${seedActor.id}\u0000${b.requestId}`);
3819
+ // A retry: this request's chat exists (open, or kept in history after a close or a restart). Answer it and its
3820
+ // proposal, completing the proposal while the chat is open; never open the id again (codex r1).
3821
+ const open = askPaths.get(seedChatId) !== undefined || chatScopes.get(seedChatId) !== undefined;
3822
+ if (open || chatHistory?.stateOf(seedChatId) !== undefined) {
3823
+ let view = chatProposals.viewOfPid(seedChatId, personPid(seedChatId, seedActor.id, b.requestId));
3824
+ // The same request id with another seed is not a retry (codex r2).
3825
+ if (view !== null && view.proposal.request?.digest !== requestDigest(seedBody(b.seed, b.requestId))) {
3826
+ return reply.code(409).send({ code: 'request_reused', error: 'this requestId already started a chat with another job', chatId: seedChatId });
3827
+ }
3828
+ if (view === null && open) {
3829
+ const seeded = await seedProposal(seedChatId, b.seed, b.requestId, seedActor);
3830
+ if ('refused' in seeded)
3831
+ return reply.code(409).send({ ...seeded.refused, chatId: seedChatId });
3832
+ view = seeded.view;
3833
+ }
3834
+ return reply.code(200).send({ chatId: seedChatId, seats: [], scope: chatScopes.get(seedChatId) ?? null, refused: [], ...(view !== null ? { proposal: view } : {}), adopted: true });
3835
+ }
3836
+ }
3837
+ const chatId = seedChatId ?? b.chatId ?? randomUUID();
3838
+ if (b.accepts !== undefined)
3839
+ chatAccepts.set(chatId, b.accepts.includes('job'));
3523
3840
  const requestedRefs = [...(b.repoRef !== undefined ? [b.repoRef] : []), ...(b.repoRefs ?? [])];
3524
3841
  // The scope kind as the open resolves it: the request's, unless an Ask-about-this seed names the repositories.
3525
3842
  let scopeKind = b.scopeKind;
@@ -3871,11 +4188,15 @@ runtime = {}) {
3871
4188
  // prominently so the caller does not have to reason about the refused[] array.
3872
4189
  const warm = seats.filter((s) => s.ok);
3873
4190
  const singleSeat = warm.length === 1 ? singleSeatDisclosure(warm[0].cliKey, refused, 'open') : undefined;
4191
+ // DES-CATALOG-002 §4.6: the seeded chat's proposal, made once the chat exists (idempotent by its request id).
4192
+ const seeded = b.seed !== undefined && seedActor !== null ? await seedProposal(chatId, b.seed, b.requestId, seedActor) : null;
4193
+ const seedOut = seeded === null ? {} : 'view' in seeded ? { proposal: seeded.view } : { seedRefused: seeded.refused };
3874
4194
  return reply.code(201).send({
3875
4195
  chatId,
3876
4196
  seats,
3877
4197
  scope,
3878
4198
  refused,
4199
+ ...seedOut,
3879
4200
  ...(workflow !== undefined ? { workflow: workflow.name } : {}),
3880
4201
  ...(projectAttachError !== undefined ? { projectAttachError } : {}),
3881
4202
  ...(singleSeat !== undefined ? { singleSeat } : {}),
@@ -3916,6 +4237,8 @@ runtime = {}) {
3916
4237
  attachments: z.array(z.string().min(1).max(64)).optional(),
3917
4238
  /** (api-types 0.169.0, DES-CHAT-ARTIFACTS-001 §5.1) What studio shows beside the message. */
3918
4239
  context: ChatMessageContextSchema.optional(),
4240
+ /** (api-types 0.192.0, DES-CATALOG-002 §4.6) What the client renders (`['job']`): the newest declaration wins. */
4241
+ accepts: z.array(z.literal('job')).max(4).optional(),
3919
4242
  });
3920
4243
  // DES-CHAT-ARTIFACTS-001 §5.1 (A1): what a turn's block reads — the docs roots, the decorated runs (project,
3921
4244
  // document and chat ids), unit outputs and the acceptance line. One set of deps, so the block and the run pages
@@ -3934,6 +4257,36 @@ runtime = {}) {
3934
4257
  // records go to the live transcript, or the kept history copy once the chat has ended.
3935
4258
  // A dollar figure only from a run whose EVERY dispatched attempt of every agent step reported a price (DES §4.2).
3936
4259
  const proposalCosts = async (view) => runCostFromEvents(view, (await adapter.runEvents(view.session.id)));
4260
+ /**
4261
+ * (DES-CATALOG-002 §2.5) A run is reshapeable only while it waits at its first WORK-plan approval (a PA's scope-only
4262
+ * rev 1 may be accepted): the gate's ord and plan revision as read, which the Reject is then bound to.
4263
+ */
4264
+ const reshapeEligibility = async (runId) => {
4265
+ const after = (why) => ({ refusal: { code: 409, body: { code: 'reshape_after_work', error: `run ${runId} ${why}: change it with the plan's own edit, or start a new job` } } });
4266
+ const run = (await adapter.sessionsDetail()).find((v) => v.session.id === runId);
4267
+ if (run === undefined)
4268
+ return { refusal: { code: 404, body: { error: 'Run not found' } } };
4269
+ if (run.session.status !== 'awaiting_human')
4270
+ return after('is not waiting at its plan');
4271
+ const held = await gateOfRecord(run, undefined);
4272
+ if ('refusal' in held || held.gateKind !== 'plan_approval' || held.gated === undefined)
4273
+ return after('is not waiting at its plan');
4274
+ const rows = await busRows(adapter.busDbPath, runId);
4275
+ if (workPlanAccepted(rows))
4276
+ return after('is past its first plan approval');
4277
+ const planRev = openPlanGateRev(rows);
4278
+ if (planRev === undefined)
4279
+ return after('holds a plan whose version could not be read');
4280
+ return { ord: held.gated.ord, planRev };
4281
+ };
4282
+ /** The held plan answered Reject (`reshaped`) for a reshape, bound to the ord and revision just read. */
4283
+ const reshapeReject = async (runId, actor, pid) => {
4284
+ const elig = await reshapeEligibility(runId);
4285
+ if ('refusal' in elig)
4286
+ return elig.refusal;
4287
+ const out = await decideGate(runId, { approve: false, action: 'reject', amend: 'reshaped', ord: elig.ord, planRev: elig.planRev }, actor, { reshape: pid });
4288
+ return out.code === 200 ? null : { code: out.code, body: (out.body ?? {}) };
4289
+ };
3937
4290
  const chatProposals = new ChatProposals({
3938
4291
  flags: () => chatArtifactFlags,
3939
4292
  catalog: CATALOG_SEEDS,
@@ -3980,6 +4333,46 @@ runtime = {}) {
3980
4333
  },
3981
4334
  runCostUsd: proposalCosts,
3982
4335
  registry: proposalLaunchers,
4336
+ // DES-CATALOG-002 §4.6: job proposals, resolved against the catalog a launch in the chat's project reads.
4337
+ jobs: () => chatJobProposalsOn,
4338
+ reshapeReject,
4339
+ preflight: async (p) => {
4340
+ // The project it files into still takes runs: an archived one refuses every new attachment (codex r6).
4341
+ if (p.filedIn.projectId !== null && p.filedIn.projectId !== DEFAULT_PROJECT_ID) {
4342
+ const project = await adapter.projectGet(p.filedIn.projectId).catch(() => null);
4343
+ if (project === null)
4344
+ return `the project ${p.filedIn.label} is no longer on this daemon`;
4345
+ if (project.status === 'archived')
4346
+ return `the project ${p.filedIn.label} is archived; restore it first`;
4347
+ }
4348
+ // A repository job's repository is still registered and its folder is still there (the launch's own refusal,
4349
+ // checked before a reshape answers its held plan; codex r5).
4350
+ const repoRef = p.repoRefs?.[0];
4351
+ // A compose reads its requirements' own repositories (checked below), not the chat's (pi r6).
4352
+ if (repoRef !== undefined && p.launch !== 'compose') {
4353
+ const entry = (await adapter.listRepos().catch(() => [])).find((r) => r.id === repoRef);
4354
+ if (entry === undefined)
4355
+ return `${p.repos[0] ?? repoRef} is no longer registered on this daemon`;
4356
+ const missing = repoFolderMissing(entry);
4357
+ if (missing !== null)
4358
+ return String(repoFolderMissingBody(missing).error ?? `${entry.name}'s folder is missing`);
4359
+ }
4360
+ if (p.launch !== 'compose')
4361
+ return null;
4362
+ const req = p.inputs?.['requirements'];
4363
+ if (p.filedIn.projectId === null)
4364
+ return 'a backlog needs a project';
4365
+ if (req === undefined || req.kind !== 'requirements')
4366
+ return 'pick the requirements first';
4367
+ const steer = (p.brief ?? p.words ?? '').trim();
4368
+ if (steer.length > 500)
4369
+ return 'A backlog takes a steer of at most 500 characters: say it shorter';
4370
+ return composePreflight(adapter, p.filedIn.projectId, req.refs, steer === '' ? undefined : steer);
4371
+ },
4372
+ qeOff: async () => addonSupportsQeOverride() && (await qeAcceptanceNow()) === 'off',
4373
+ acceptsJobs: (chatId) => chatAccepts.get(chatId) === true,
4374
+ served: (projectId) => servedFor(shapeReads, projectId ?? undefined),
4375
+ turnLive: (chatId, turnId) => chatTurns.turnsOf(chatId).some((t) => t.turnId === turnId),
3983
4376
  broadcast: (frame) => runtime.broadcast?.(frame),
3984
4377
  audit: (event, actor, detail) => {
3985
4378
  audit.record(event, actor, { detail });
@@ -3999,6 +4392,8 @@ runtime = {}) {
3999
4392
  if (!parsed.success) {
4000
4393
  return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
4001
4394
  }
4395
+ if (parsed.data.accepts !== undefined)
4396
+ chatAccepts.set(id, parsed.data.accepts.includes('job'));
4002
4397
  // DES-ASK-TEAM-CHAT-001 §3, §5.1 (ASK-C1): the first message of a chat LAUNCHES one team path
4003
4398
  // — a user-composed plan of one `understand` step with its gate raised to the turn gate, one
4004
4399
  // reviewer asked for, the eligible roster as `clis`, the operator's choice as `primary`; every
@@ -4089,6 +4484,10 @@ runtime = {}) {
4089
4484
  chatTranscripts?.appendUser(id, turnId, text, voice, attached.map(attachmentWire), contextAllowed);
4090
4485
  if (turnBinding !== null)
4091
4486
  chatTranscripts?.appendContext(id, turnId, turnBinding);
4487
+ // DES-CATALOG-002 §4.6: the person's message holds the chat's open job proposal while its seat turn may revise
4488
+ // it (Go waits: 409 `proposal_revising`), written under the lock Go takes.
4489
+ if (contextAllowed)
4490
+ void chatProposals.holdForMessage(id, turnId).catch((err) => req.log.warn(`[proposals] chat ${id}: the hold for turn ${turnId} could not be written: ${message(err)}`));
4092
4491
  // The recorder's audience is the turn's AS THE TURN INDEX HOLDS IT NOW: the eligible roster
4093
4492
  // for a random pick, or the PA the relay narrowed it to during the engine awaits above
4094
4493
  // (`path.started` / `path.repicked` may land before this record exists — ASK-C2, codex on
@@ -4410,8 +4809,62 @@ runtime = {}) {
4410
4809
  audience: z.string().max(800).optional(),
4411
4810
  show: z.string().max(4000).optional(),
4412
4811
  helpers: z.array(z.string().min(1).max(64)).max(8).optional(),
4812
+ // (api-types 0.192.0, DES-CATALOG-002 §4.6) a job's edits, merged by the revision rules before Go.
4813
+ option: z.string().trim().min(1).max(80).nullable().optional(),
4814
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
4815
+ repoRef: z.string().trim().min(1).max(200).optional(),
4816
+ seats: z.array(z.string().min(1).max(64)).min(1).max(8).optional(),
4817
+ inputs: RevisionEditsSchema.shape.inputs,
4413
4818
  }).optional(),
4414
4819
  });
4820
+ /** (api-types 0.192.0) `POST /chats/:id/proposals`: a person-made proposal, or a revision of the open one. */
4821
+ const PersonProposalSchema = z.union([
4822
+ z.strictObject({
4823
+ card: z.string().trim().min(1).max(120),
4824
+ option: z.string().trim().min(1).max(80).nullable().optional(),
4825
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
4826
+ words: z.string().max(8000).optional(),
4827
+ source: z.enum(['pick', 'command', 'question', 'suggestion', 'swap']),
4828
+ requestId: z.string().trim().min(1).max(128),
4829
+ }),
4830
+ z.strictObject({
4831
+ revises: z.string().trim().min(1).max(400),
4832
+ edits: RevisionEditsSchema,
4833
+ source: z.enum(['swap', 'suggestion', 'question']),
4834
+ requestId: z.string().trim().min(1).max(128),
4835
+ words: z.string().max(2000).optional(),
4836
+ }),
4837
+ ]);
4838
+ /** The checks every person route makes before a proposal is read: the capability, a person, the chat is theirs. */
4839
+ const personChatGate = (req, id, what) => {
4840
+ const actor = actorOf(req);
4841
+ if (!isHumanOperator(actor)) {
4842
+ audit.record('chat.proposal.refused', actor, { detail: { chatId: id, reason: 'not_a_person', what } });
4843
+ return { refusal: { code: 403, body: { code: 'proposal_refused', error: `only a person ${what} (you are ${actor.kind}/${actor.trust}). Nothing was started.` } } };
4844
+ }
4845
+ const viewer = security.authMode === 'required' ? actor.id : null;
4846
+ if (!CHAT_ID.test(id) || chatHistory === null || !chatHistory.visibleTo(id, viewer)) {
4847
+ return { refusal: { code: 404, body: { error: `no chat ${id} on this daemon` } } };
4848
+ }
4849
+ return { actor, instance: chatHistory.stateOf(id)?.instance ?? null };
4850
+ };
4851
+ app.post(`${V}/chats/:id/proposals`, { config: { manifest: { requestType: 'PersonProposalBody | PersonRevisionBody', responseType: 'PersonProposalResponse', statusCodes: [200, 201, 400, 403, 404, 409] } } }, async (req, reply) => {
4852
+ const { id } = req.params;
4853
+ if (!chatArtifactFlags.proposals || !chatJobProposalsOn)
4854
+ return reply.code(404).send({ error: 'this daemon does not take job proposals from a chat' });
4855
+ const gate = personChatGate(req, id, 'proposes a job');
4856
+ if ('refusal' in gate)
4857
+ return reply.code(gate.refusal.code).send(gate.refusal.body);
4858
+ const parsed = PersonProposalSchema.safeParse(req.body);
4859
+ if (!parsed.success)
4860
+ return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
4861
+ const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
4862
+ const body = 'revises' in parsed.data
4863
+ ? clean({ ...parsed.data, edits: clean(parsed.data.edits) })
4864
+ : clean(parsed.data);
4865
+ const out = await chatProposals.propose(id, body, gate.actor, gate.instance);
4866
+ return reply.code(out.code).send(out.body);
4867
+ });
4415
4868
  app.post(`${V}/chats/:id/proposals/:pid`, { config: { manifest: { requestType: 'ChatProposalDecisionBody', responseType: 'ChatProposalDecisionResponse', statusCodes: [200, 400, 403, 404, 409, 502] } } }, async (req, reply) => {
4416
4869
  const { id, pid } = req.params;
4417
4870
  if (!chatArtifactFlags.proposals)
@@ -4752,6 +5205,10 @@ runtime = {}) {
4752
5205
  const chat = chatHistory.visibleTo(id, viewer)
4753
5206
  ? chatHistory.entry(id, askPaths.get(id)?.pa ?? null, (cid) => askPaths.get(cid) !== undefined || chatScopes.get(cid) !== undefined)
4754
5207
  : null;
5208
+ // DES-CATALOG-002 §4.6: a read that finds a job proposal held by a turn that is gone (failed, expired, or forgotten
5209
+ // by a restart) releases it with its note first, so the proposal reads startable again.
5210
+ if (chat !== null)
5211
+ await chatProposals.reopenStale(id).catch(() => false);
4755
5212
  const messages = chat === null ? null : chatHistory.messages(id);
4756
5213
  if (chat === null || messages === null)
4757
5214
  return reply.code(404).send({ error: `no chat ${id} in this daemon's history` });
@@ -5159,6 +5616,17 @@ runtime = {}) {
5159
5616
  */
5160
5617
  async function gateForDecision(run, namedOrd, opts = {}) {
5161
5618
  const decided = await gateOfRecord(run, namedOrd);
5619
+ // DES-CATALOG-002 §4.6 (codex r1): a plan held for a run launched from a chat proposal is approved only by an
5620
+ // answer bound to its version (`POST /runs/:id/gate` with `planRev`); every other approving path (a gated resume or
5621
+ // reassign, a plan edit at the gate, a standing order) is refused there. Declining stays open.
5622
+ if (!('refusal' in decided) && opts.declining !== true && opts.versioned !== true && decided.gateKind === 'plan_approval'
5623
+ && runTimingIndex.fromProposalOf(run.session.id) !== undefined) {
5624
+ return { refusal: { code: 409, body: {
5625
+ code: 'gate_changed',
5626
+ error: 'This plan was started from a chat proposal: approve it through its gate with the plan version you read (planRev).',
5627
+ ...(await currentPlanOf(run.session.id, false)),
5628
+ } } };
5629
+ }
5162
5630
  // crew#1157: every APPROVING path (the gate route, standing orders, a gated resume or reassign, a
5163
5631
  // plan edit at the gate, the next message of a chat) is judged here, so no path approves a held
5164
5632
  // plan change on an analysis run. Declining stays open.
@@ -5330,9 +5798,32 @@ runtime = {}) {
5330
5798
  // Decision integrity (api-types 0.44.0; crew#1083 rounds 3–5): the gate this decision answers
5331
5799
  // is the RECORD's — read first thing inside the lock, so the gated unit and its delivery
5332
5800
  // checks below are the ones the record confirms ({@link gateForDecision}).
5333
- const decided = await gateForDecision(run, parsed.data.ord, { declining: !parsed.data.approve });
5334
- if ('refusal' in decided)
5335
- return decided.refusal;
5801
+ const decided = await gateForDecision(run, parsed.data.ord, { declining: !parsed.data.approve, versioned: true });
5802
+ if ('refusal' in decided) {
5803
+ const r = decided.refusal.body;
5804
+ return r?.code === 'gate_changed' ? { code: decided.refusal.code, body: { ...(await currentPlanOf(id, false)), ...r } } : decided.refusal;
5805
+ }
5806
+ // DES-CATALOG-002 §4.6: a plan-gate answer is bound to the plan on screen. A run launched from a chat proposal
5807
+ // REQUIRES `planRev` there, whichever client answers; a send-back needs it on any run. The engine compares it
5808
+ // (and `ord`) inside its own serialized decision, so a re-plan landing after this read still loses.
5809
+ if (decided.gateKind === 'plan_approval') {
5810
+ const fromProposal = runTimingIndex.fromProposalOf(id);
5811
+ // A Reject cancels the run whatever revision it holds, so only an approving answer or a send-back needs it.
5812
+ const bindsPlan = parsed.data.approve || parsed.data.action === 'request_changes';
5813
+ if (parsed.data.planRev === undefined && fromProposal !== undefined && bindsPlan) {
5814
+ return { code: 409, body: {
5815
+ code: 'gate_changed',
5816
+ error: 'Gate changed: this run was started from a chat proposal, so a plan answer must name the plan version it was made on (planRev). Read the plan again and answer it.',
5817
+ ...(await currentPlanOf(id)),
5818
+ } };
5819
+ }
5820
+ if (parsed.data.planRev !== undefined && !adapterSupportsPlanSendBack()) {
5821
+ return { code: 501, body: { error: 'Answering a plan by its version needs a wicked-core-ts that checks it (Core.supportsPlanSendBack); upgrade the engine' } };
5822
+ }
5823
+ }
5824
+ else if (parsed.data.planRev !== undefined) {
5825
+ return { code: 409, body: { code: 'gate_changed', error: 'Gate changed: this answer names a plan version, but the open gate is not a plan approval. Read the gate again.', ...(await currentPlanOf(id)) } };
5826
+ }
5336
5827
  // (crew#1139) A note on a plan approval needs an engine that lands it. An older one refuses it with
5337
5828
  // words that predate notes ("send the edited steps"), so the daemon says what to do instead.
5338
5829
  if (parsed.data.approve && decided.gateKind === 'plan_approval' && (parsed.data.amend ?? '').trim() !== ''
@@ -5385,9 +5876,21 @@ runtime = {}) {
5385
5876
  // confirm, which records it as the judge when this approve answers a `judge_unavailable`
5386
5877
  // gate ("judged by operator").
5387
5878
  adapter.recordGateActor?.(id, `${actor.id} (${actor.kind})`);
5388
- const status = await adapter.confirmGate(id, parsed.data.approve,
5389
- // (DES-RULE-CHECK-001 S2) The engine takes a rule skip's reasons in `amend` as JSON.
5390
- parsed.data.action === SKIP_RULES_ACTION ? skipRulesAmend(parsed.data.skipRules ?? []) : parsed.data.amend, parsed.data.action, parsed.data.amendScope, parsed.data.plan !== undefined ? toLaunchPlan(parsed.data.plan) : undefined);
5879
+ // The expected ord and plan revision ride as the trailing argument only when sent (an answer without them keeps
5880
+ // the confirm's existing arity; DES-CATALOG-002 §4.6).
5881
+ const expect = parsed.data.planRev !== undefined ? { ...(gated !== undefined ? { ord: gated.ord } : parsed.data.ord !== undefined ? { ord: parsed.data.ord } : {}), planRev: parsed.data.planRev } : undefined;
5882
+ const confirmArgs = [
5883
+ id,
5884
+ parsed.data.approve,
5885
+ // (DES-RULE-CHECK-001 S2) The engine takes a rule skip's reasons in `amend` as JSON.
5886
+ parsed.data.action === SKIP_RULES_ACTION ? skipRulesAmend(parsed.data.skipRules ?? []) : parsed.data.amend,
5887
+ parsed.data.action,
5888
+ parsed.data.amendScope,
5889
+ parsed.data.plan !== undefined ? toLaunchPlan(parsed.data.plan) : undefined,
5890
+ ];
5891
+ if (expect !== undefined)
5892
+ confirmArgs.push(expect);
5893
+ const status = await adapter.confirmGate(...confirmArgs);
5391
5894
  // WHO approved/rejected — the gate-decision audit (task #88). The engine
5392
5895
  // records THAT the gate resolved (interaction_requests / gateDecided);
5393
5896
  // only this HTTP layer knows the authenticated principal behind it.
@@ -5415,6 +5918,7 @@ runtime = {}) {
5415
5918
  ...(parsed.data.amendScope !== undefined ? { amendScope: parsed.data.amendScope } : {}),
5416
5919
  ...(parsed.data.plan !== undefined ? { planSteps: parsed.data.plan.steps.length } : {}),
5417
5920
  ...(parsed.data.ord !== undefined ? { ord: parsed.data.ord } : {}),
5921
+ ...(parsed.data.planRev !== undefined ? { planRev: parsed.data.planRev } : {}),
5418
5922
  ...(parsed.data.input !== undefined ? { input: parsed.data.input } : {}),
5419
5923
  ...extraDetail,
5420
5924
  status,
@@ -5461,10 +5965,31 @@ runtime = {}) {
5461
5965
  if (err instanceof PlanLaunchUnsupportedError || err instanceof PlanGateNoteUnsupportedError) {
5462
5966
  return { code: 501, body: { error: message(err) } };
5463
5967
  }
5968
+ // DES-CATALOG-002 §4.6: the engine's own stale-answer refusal (`gate_changed: …`) is the typed 409, with the
5969
+ // plan the gate holds now, so the person reads it again.
5970
+ if (/^gate_changed\b/u.test(message(err))) {
5971
+ return { code: 409, body: { code: 'gate_changed', error: `Gate changed: ${message(err).replace(/^gate_changed:?\s*/u, '')} — read the plan again and answer it.`, ...(await currentPlanOf(id)) } };
5972
+ }
5464
5973
  return { code: 409, body: { error: message(err) } };
5465
5974
  }
5466
5975
  });
5467
5976
  }
5977
+ /** (DES-CATALOG-002 §4.6) The plan a gate holds now, for a `gate_changed` answer: its ord and revision, best-effort. */
5978
+ async function currentPlanOf(runId, readGate = true) {
5979
+ try {
5980
+ // The caller that already read the open gate (and names its ord) asks for the plan revision only.
5981
+ const recorded = readGate ? await recordedOpenGate(runId) : null;
5982
+ const rev = openPlanGateRev(await busRows(adapter.busDbPath, runId));
5983
+ return { ...(recorded?.state === 'open' ? { openOrd: recorded.ord } : {}), ...(rev !== undefined ? { planRev: rev } : {}) };
5984
+ }
5985
+ catch {
5986
+ return {};
5987
+ }
5988
+ }
5989
+ /** Whether the linked engine checks `expectOrd` / `expectPlanRev` (`Core.supportsPlanSendBack`). */
5990
+ function adapterSupportsPlanSendBack() {
5991
+ return typeof adapter.supportsPlanSendBack === 'function' && adapter.supportsPlanSendBack();
5992
+ }
5468
5993
  // The steering gate (§11.1). approve+amend = approve-with-steer; approve:false = reject (cancels).
5469
5994
  app.post(`${V}/runs/:id/gate`, {
5470
5995
  config: {
@@ -5481,6 +6006,91 @@ runtime = {}) {
5481
6006
  const out = await decideGate(id, req.body, actorOf(req));
5482
6007
  return reply.code(out.code).send(out.body);
5483
6008
  });
6009
+ /**
6010
+ * (DES-CATALOG-002 §2.5, api-types 0.192.0) Start a run held at its FIRST work-plan approval again as another card or
6011
+ * option: the crew-made reshape proposal, validated, the held gate answered Reject (`reshaped`) and the replacement
6012
+ * launched from the held run's envelope, all under the chat's lock (`ChatProposals.reshape`).
6013
+ */
6014
+ const ReshapeSchema = z.strictObject({
6015
+ card: z.string().trim().min(1).max(120),
6016
+ option: z.string().trim().min(1).max(80).nullable().optional(),
6017
+ depth: z.enum(['quick', 'standard', 'deep']).nullable().optional(),
6018
+ inputs: RevisionEditsSchema.shape.inputs,
6019
+ requestId: z.string().trim().min(1).max(128).regex(/^[A-Za-z0-9._-]+$/),
6020
+ /** The person's press on the reshape question: the loss ids it was shown. */
6021
+ confirmLoss: z.array(z.string().min(1).max(40)).min(1).max(12).optional(),
6022
+ });
6023
+ app.post(`${V}/runs/:id/reshape`, { config: { manifest: { requestType: 'ReshapeRunBody', responseType: 'ReshapeRunResponse', statusCodes: [200, 400, 403, 404, 409, 502] } } }, async (req, reply) => {
6024
+ const { id } = req.params;
6025
+ if (!chatJobProposalsOn)
6026
+ return reply.code(404).send({ error: 'this daemon does not start runs again from a chat' });
6027
+ const parsed = ReshapeSchema.safeParse(req.body);
6028
+ if (!parsed.success)
6029
+ return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
6030
+ const envelope = runTimingIndex.envelopeOf(id);
6031
+ const fromProposal = runTimingIndex.fromProposalOf(id);
6032
+ const chatId = envelope?.chatId ?? runTimingIndex.chatIdFor(id);
6033
+ if (envelope === undefined || fromProposal === undefined || chatId === undefined) {
6034
+ return reply.code(409).send({ code: 'reshape_not_chat', error: `run ${id} was not started from a chat proposal: start the other job in a chat instead` });
6035
+ }
6036
+ const gate = personChatGate(req, chatId, 'starts a run again');
6037
+ if ('refusal' in gate)
6038
+ return reply.code(gate.refusal.code).send(gate.refusal.body);
6039
+ const run = (await adapter.sessionsDetail()).find((v) => v.session.id === id);
6040
+ if (run === undefined)
6041
+ return reply.code(404).send({ error: 'Run not found' });
6042
+ const pid = `${chatId}:reshape:${id}:${parsed.data.requestId}`;
6043
+ // Eligible only while the run waits at its first WORK-plan approval (a PA's scope-only rev 1 may be accepted); a
6044
+ // retry after THIS reshape's own Reject (recorded on its proposal) goes on to its launch (codex r2).
6045
+ if (chatProposals.proposalOfPid(chatId, pid)?.heldRejected !== true) {
6046
+ const elig = await reshapeEligibility(id);
6047
+ if ('refusal' in elig)
6048
+ return reply.code(elig.refusal.code).send(elig.refusal.body);
6049
+ }
6050
+ const old = chatProposals.proposalOfPid(chatId, fromProposal);
6051
+ const base = old !== null && old.shape !== undefined ? factsOf(old) : null;
6052
+ const facts = {
6053
+ card: parsed.data.card,
6054
+ option: parsed.data.option ?? undefined,
6055
+ depth: parsed.data.depth ?? null,
6056
+ words: base?.words ?? envelope.words,
6057
+ details: base?.details ?? [],
6058
+ repoRef: base?.repoRef ?? envelope.repoRef ?? null,
6059
+ projectId: base?.projectId ?? envelope.projectId ?? null,
6060
+ lead: base?.lead ?? envelope.primary ?? null,
6061
+ seats: base?.seats ?? null,
6062
+ inputs: { ...(base?.inputs ?? {}), ...(parsed.data.inputs ?? {}) },
6063
+ // A QE skip given for the held run is not carried: the new shape's checks are its own.
6064
+ skipQe: null,
6065
+ by: 'person',
6066
+ source: 'reshape',
6067
+ };
6068
+ const out = await chatProposals.reshape(chatId, {
6069
+ pid,
6070
+ oldRunId: id,
6071
+ parentPid: fromProposal,
6072
+ facts,
6073
+ edits: {
6074
+ card: parsed.data.card,
6075
+ ...(parsed.data.option !== undefined ? { option: parsed.data.option } : {}),
6076
+ ...(parsed.data.depth !== undefined ? { depth: parsed.data.depth } : {}),
6077
+ ...(parsed.data.inputs !== undefined ? { inputs: parsed.data.inputs } : {}),
6078
+ },
6079
+ reducedAssurance: envelope.reducedAssurance === true,
6080
+ relaunch: {
6081
+ deliver: envelope.deliver,
6082
+ ...(envelope.deliverGate !== undefined ? { deliverGate: envelope.deliverGate } : {}),
6083
+ ...(envelope.campaignId !== undefined ? { campaignId: envelope.campaignId } : {}),
6084
+ ...(envelope.groupLabel !== undefined ? { groupLabel: envelope.groupLabel } : {}),
6085
+ ...(envelope.revisesPr !== undefined ? { revisesPr: envelope.revisesPr } : {}),
6086
+ ...(envelope.forceQeAcceptance === true ? { forceQeAcceptance: true } : {}),
6087
+ ...(envelope.clisJson !== undefined ? { clisJson: envelope.clisJson } : {}),
6088
+ },
6089
+ request: { id: parsed.data.requestId, digest: requestDigest({ card: parsed.data.card, option: parsed.data.option ?? null, depth: parsed.data.depth ?? null, inputs: parsed.data.inputs ?? null }) },
6090
+ confirmLoss: parsed.data.confirmLoss ?? [],
6091
+ }, gate.actor, gate.instance);
6092
+ return reply.code(out.code).send(out.body);
6093
+ });
5484
6094
  // Cancel a running or paused run (distinct third action, §11.1).
5485
6095
  // (api-types 0.161.0, DES-VOICE) An optional body: the person's `reason` (said or typed) and `input: "voice"`, both
5486
6096
  // kept on the `run.cancelled` audit line. A bodiless cancel is unchanged; voice is a person's only (403).
@@ -6784,23 +7394,39 @@ runtime = {}) {
6784
7394
  // wf-catalog (api-types 0.168.0): the workflows as a categorised catalog with the requesting
6785
7395
  // operator's usage. Metadata is the ONE data module (`workflow-catalog/catalog-data.ts`); what a
6786
7396
  // workflow is and does stays on its def; usage is derived from the runs and the launch trail.
6787
- app.get(`${V}/workflows/catalog`, { config: { manifest: { responseType: 'WorkflowCatalogResponse', statusCodes: [200, 400] } } }, async (req, reply) => {
7397
+ app.get(`${V}/workflows/catalog`, { config: { manifest: { responseType: 'WorkflowCatalogResponse | WorkflowCatalogV2Response', statusCodes: [200, 400, 503] } } }, async (req, reply) => {
6788
7398
  const raw = req.query?.projectId;
6789
7399
  if (raw !== undefined && (typeof raw !== 'string' || raw.length > 200)) {
6790
7400
  return reply.code(400).send({ error: '`projectId` must be a string' });
6791
7401
  }
7402
+ // DES-CATALOG-002 §4.1: `v=2` answers the catalog by verb; anything else but an absent `v` is a 400, so v1 stays
7403
+ // exactly as it was for every caller that sends none.
7404
+ const version = req.query?.v;
7405
+ if (version !== undefined && version !== '1' && version !== '2') {
7406
+ return reply.code(400).send({ error: '`v` must be 1 or 2' });
7407
+ }
6792
7408
  const projectId = typeof raw === 'string' && raw !== '' ? raw : null;
6793
7409
  const { workflows } = await adapter.workflowCatalog();
6794
7410
  let presets = [];
7411
+ // v2 serves only presets it actually read (an unknown project's global ones included); no read at all is a 503.
7412
+ let presetsRead = true;
6795
7413
  try {
6796
7414
  presets = await adapter.listPresets(projectId ?? undefined);
6797
7415
  }
6798
7416
  catch (err) {
6799
7417
  // An unknown project: the global presets (built-in attribution and saved ones still hold, agy r1).
6800
7418
  // An engine without presets lists the served defs only. Either way, said once in the log.
6801
- app.log.warn(`workflows/catalog: the presets could not be read${projectId !== null ? ` for project ${projectId}` : ''} (${message(err)}); listing ${projectId !== null ? 'the global ones' : 'the served workflows only'}`);
6802
- if (projectId !== null)
6803
- presets = await adapter.listPresets().catch(() => []);
7419
+ app.log.warn(`workflows/catalog: the presets could not be read${projectId !== null ? ` for project ${projectId}` : ''} (${message(err)}); v1 lists ${projectId !== null ? 'the global ones' : 'the served workflows only'}, v2 answers 503 if no presets read succeeds`);
7420
+ presetsRead = false;
7421
+ if (projectId !== null) {
7422
+ try {
7423
+ presets = await adapter.listPresets();
7424
+ presetsRead = true;
7425
+ }
7426
+ catch {
7427
+ presets = [];
7428
+ }
7429
+ }
6804
7430
  }
6805
7431
  const views = await adapter.sessionsDetail();
6806
7432
  // codex r1: date terminal runs that have no `run.ended` entry from their event log, as GET /runs
@@ -6818,6 +7444,26 @@ runtime = {}) {
6818
7444
  retryOf: retryIndex.retryOfFor(view.session.id),
6819
7445
  principal: runTimingIndex.principalFor(view.session.id),
6820
7446
  }));
7447
+ if (version === '2') {
7448
+ // v2 fails closed (codex r2): a catalog read without the project's presets or the phase catalog would show checks
7449
+ // and a revision a launch could not honour. v1 keeps its fallback below.
7450
+ let entries;
7451
+ try {
7452
+ entries = await adapter.catalog();
7453
+ }
7454
+ catch (err) {
7455
+ return reply.code(503).send({ code: 'catalog_unavailable', error: `the catalog could not be read: ${message(err)}` });
7456
+ }
7457
+ if (!presetsRead)
7458
+ return reply.code(503).send({ code: 'catalog_unavailable', error: 'the presets could not be read' });
7459
+ return buildWorkflowCatalogV2({
7460
+ defs: workflows, presets, entries, actorId: me, projectId,
7461
+ runs: runs.map((r) => {
7462
+ const shape = runTimingIndex.shapeOf(r.id);
7463
+ return shape === undefined ? r : { ...r, shape: { card: shape.card, option: shape.option } };
7464
+ }),
7465
+ });
7466
+ }
6821
7467
  const body = buildWorkflowCatalog({
6822
7468
  defs: workflows, presets, runs, actorId: me, projectId,
6823
7469
  // The same rule as `GET /health.capabilities.apps.turns`.
@@ -8538,12 +9184,12 @@ runtime = {}) {
8538
9184
  // crew#371: a project's requirements / domain / coverage, folded over its repos' own reads.
8539
9185
  registerProjectAggregateRoutes(app, adapter);
8540
9186
  // crew#372: draft a product plan from selected requirements, as a governed run via POST /runs.
8541
- registerProductRoutes(app, adapter);
9187
+ registerProductRoutes(app, adapter, launchRun);
8542
9188
  // ── Capture (Studio OS behaviour 8) — notes and photos → a project-filed run whose output is
8543
9189
  // proposals in the queue above; the launch is POST /runs itself (api/capture.ts).
8544
9190
  registerCaptureRoutes(app);
8545
9191
  // The Demo experience (studio#373): the demo preset's launch, view, files and script edit.
8546
- registerDemoRoutes(app, adapter);
9192
+ registerDemoRoutes(app, adapter, launchRun);
8547
9193
  // WT-W3: the storyline PUT checks the open gate through the same resolution the gate routes use.
8548
9194
  registerWalkthroughRoutes(app, adapter, { resolveOpenGate, audit });
8549
9195
  // ── Presets (DES-TEAMING-002 §8.4, seam C2) — saved phase selections in the engine's store;