wicked-crew 0.18.17 → 0.18.18

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 (125) hide show
  1. package/dist/api/capture.d.ts.map +1 -1
  2. package/dist/api/capture.js +5 -0
  3. package/dist/api/capture.js.map +1 -1
  4. package/dist/api/chat-jobs.d.ts +28 -0
  5. package/dist/api/chat-jobs.d.ts.map +1 -1
  6. package/dist/api/chat-jobs.js +74 -7
  7. package/dist/api/chat-jobs.js.map +1 -1
  8. package/dist/api/chat-proposals.d.ts +39 -3
  9. package/dist/api/chat-proposals.d.ts.map +1 -1
  10. package/dist/api/chat-proposals.js +122 -17
  11. package/dist/api/chat-proposals.js.map +1 -1
  12. package/dist/api/chat-scope.d.ts.map +1 -1
  13. package/dist/api/chat-scope.js +2 -0
  14. package/dist/api/chat-scope.js.map +1 -1
  15. package/dist/api/post-hoc-deliver.d.ts +9 -0
  16. package/dist/api/post-hoc-deliver.d.ts.map +1 -1
  17. package/dist/api/post-hoc-deliver.js +32 -3
  18. package/dist/api/post-hoc-deliver.js.map +1 -1
  19. package/dist/api/roster-standing.d.ts +7 -0
  20. package/dist/api/roster-standing.d.ts.map +1 -1
  21. package/dist/api/roster-standing.js +32 -2
  22. package/dist/api/roster-standing.js.map +1 -1
  23. package/dist/api/routes.d.ts +6 -6
  24. package/dist/api/routes.d.ts.map +1 -1
  25. package/dist/api/routes.js +398 -183
  26. package/dist/api/routes.js.map +1 -1
  27. package/dist/api/run-files.d.ts.map +1 -1
  28. package/dist/api/run-files.js +41 -2
  29. package/dist/api/run-files.js.map +1 -1
  30. package/dist/api/seat-agents.d.ts +3 -1
  31. package/dist/api/seat-agents.d.ts.map +1 -1
  32. package/dist/api/seat-agents.js +8 -2
  33. package/dist/api/seat-agents.js.map +1 -1
  34. package/dist/api/seat-images.d.ts +54 -0
  35. package/dist/api/seat-images.d.ts.map +1 -1
  36. package/dist/api/seat-images.js +132 -8
  37. package/dist/api/seat-images.js.map +1 -1
  38. package/dist/api/seat-standing.d.ts +3 -0
  39. package/dist/api/seat-standing.d.ts.map +1 -1
  40. package/dist/api/seat-standing.js +5 -0
  41. package/dist/api/seat-standing.js.map +1 -1
  42. package/dist/api/server.d.ts.map +1 -1
  43. package/dist/api/server.js +3 -1
  44. package/dist/api/server.js.map +1 -1
  45. package/dist/api/system-snapshot.d.ts.map +1 -1
  46. package/dist/api/system-snapshot.js +1 -0
  47. package/dist/api/system-snapshot.js.map +1 -1
  48. package/dist/api/ui-text.d.ts +2 -0
  49. package/dist/api/ui-text.d.ts.map +1 -1
  50. package/dist/api/ui-text.js +2 -0
  51. package/dist/api/ui-text.js.map +1 -1
  52. package/dist/apps-server/server/lib/bundle/server.mjs +123 -0
  53. package/dist/core/adapter.d.ts +21 -1
  54. package/dist/core/adapter.d.ts.map +1 -1
  55. package/dist/core/adapter.js +86 -7
  56. package/dist/core/adapter.js.map +1 -1
  57. package/dist/core/deliver-exclusions.d.ts +29 -0
  58. package/dist/core/deliver-exclusions.d.ts.map +1 -1
  59. package/dist/core/deliver-exclusions.js +44 -0
  60. package/dist/core/deliver-exclusions.js.map +1 -1
  61. package/dist/core/deliver-text.d.ts.map +1 -1
  62. package/dist/core/deliver-text.js +11 -2
  63. package/dist/core/deliver-text.js.map +1 -1
  64. package/dist/core/deliver.d.ts +30 -1
  65. package/dist/core/deliver.d.ts.map +1 -1
  66. package/dist/core/deliver.js +167 -17
  67. package/dist/core/deliver.js.map +1 -1
  68. package/dist/core/job-seats.d.ts +23 -0
  69. package/dist/core/job-seats.d.ts.map +1 -0
  70. package/dist/core/job-seats.js +38 -0
  71. package/dist/core/job-seats.js.map +1 -0
  72. package/dist/core/launch-posture.d.ts +75 -0
  73. package/dist/core/launch-posture.d.ts.map +1 -0
  74. package/dist/core/launch-posture.js +88 -0
  75. package/dist/core/launch-posture.js.map +1 -0
  76. package/dist/core/pr-checks-helper.d.ts +51 -0
  77. package/dist/core/pr-checks-helper.d.ts.map +1 -0
  78. package/dist/core/pr-checks-helper.js +172 -0
  79. package/dist/core/pr-checks-helper.js.map +1 -0
  80. package/dist/insights/review-service.d.ts +10 -0
  81. package/dist/insights/review-service.d.ts.map +1 -1
  82. package/dist/insights/review-service.js +27 -3
  83. package/dist/insights/review-service.js.map +1 -1
  84. package/dist/learnings/recall.d.ts +11 -1
  85. package/dist/learnings/recall.d.ts.map +1 -1
  86. package/dist/learnings/recall.js +20 -4
  87. package/dist/learnings/recall.js.map +1 -1
  88. package/dist/learnings/replacement-lineage.d.ts +22 -0
  89. package/dist/learnings/replacement-lineage.d.ts.map +1 -0
  90. package/dist/learnings/replacement-lineage.js +41 -0
  91. package/dist/learnings/replacement-lineage.js.map +1 -0
  92. package/dist/schedules/routes.d.ts.map +1 -1
  93. package/dist/schedules/routes.js +5 -0
  94. package/dist/schedules/routes.js.map +1 -1
  95. package/dist/setup/delivery-readiness.d.ts +117 -0
  96. package/dist/setup/delivery-readiness.d.ts.map +1 -0
  97. package/dist/setup/delivery-readiness.js +262 -0
  98. package/dist/setup/delivery-readiness.js.map +1 -0
  99. package/dist/setup/known.d.ts +27 -0
  100. package/dist/setup/known.d.ts.map +1 -1
  101. package/dist/setup/known.js +47 -0
  102. package/dist/setup/known.js.map +1 -1
  103. package/dist/setup/routes.d.ts +5 -3
  104. package/dist/setup/routes.d.ts.map +1 -1
  105. package/dist/setup/routes.js +9 -3
  106. package/dist/setup/routes.js.map +1 -1
  107. package/dist/studio/apps-standalone/fixture.js +3 -3
  108. package/dist/studio/assets/{KnowledgeGraph-BekDGaZW.js → KnowledgeGraph-JfsMExo3.js} +1 -1
  109. package/dist/studio/assets/{index-D5r5wtIa.js → index-pq0QeOmo.js} +294 -294
  110. package/dist/studio/editors/wicked-apps/editor.json +1 -1
  111. package/dist/studio/editors/wicked-apps/index.html +1 -1
  112. package/dist/studio/editors/wicked-deck/editor.json +1 -1
  113. package/dist/studio/editors/wicked-deck/index.html +1 -1
  114. package/dist/studio/editors/wicked-doc/editor.json +1 -1
  115. package/dist/studio/editors/wicked-doc/index.html +1 -1
  116. package/dist/studio/editors/wicked-insights/editor.json +1 -1
  117. package/dist/studio/editors/wicked-insights/index.html +1 -1
  118. package/dist/studio/editors/wicked-page/editor.json +1 -1
  119. package/dist/studio/editors/wicked-page/index.html +1 -1
  120. package/dist/studio/editors/wicked-video/editor.json +1 -1
  121. package/dist/studio/editors/wicked-video/index.html +1 -1
  122. package/dist/studio/index.html +1 -1
  123. package/dist/studio/testid-inventory.json +39 -3
  124. package/endpoint-manifest.json +11 -1
  125. package/package.json +4 -4
@@ -13,7 +13,7 @@ import { promises as fsp } from 'node:fs';
13
13
  import { basename, isAbsolute, join, relative, resolve } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { videoPalette } from '../appearance/video-palette.js';
16
- import { CampaignsUnsupportedError, ChatUnsupportedError, CoreAdapter, ElicitationUnsupportedError, GovernanceReplayUnsupportedError, PlanGateNoteUnsupportedError, PlanLaunchUnsupportedError, SteeringUnsupportedError, addonSupportsQeOverride, addonSupportsReducedAssurance, humanGatePhaseIds, settingsFilePath, wickedDir } from '../core/adapter.js';
16
+ import { CampaignsUnsupportedError, ChatUnsupportedError, CoreAdapter, ElicitationUnsupportedError, GovernanceReplayUnsupportedError, PlanGateNoteUnsupportedError, PlanLaunchUnsupportedError, SteeringUnsupportedError, addonSupportsQeOverride, addonSupportsReducedAssurance, humanGatePhaseIds, readNewWorkSeats, settingsFilePath, wickedDir } from '../core/adapter.js';
17
17
  import { codeGraphDb, codeGraphErrorStatus, repoFolderMissing, repoFolderMissingBody } from '../core/repoPaths.js';
18
18
  import { resolveCursorUnit } from '../core/cursor.js';
19
19
  /** Create `dir` (private) when missing and answer it — a read root must exist when a run launches. */
@@ -56,6 +56,8 @@ import { attemptUnavailableReason, capturedAttempts, outputUnavailableReason, re
56
56
  import { execCapped, ExecOutputTooLarge } from '../core/exec.js';
57
57
  import { callEstateTool, EstateMcpError, ESTATE_INSTALL_HINT, memoryStoreInfo } from '../core/estate-mcp-client.js';
58
58
  import { NO_LEARNINGS_WORKFLOWS } from '../learnings/service.js';
59
+ import { APPROVED_MEMORY_PREFIX } from '../learnings/recall.js';
60
+ import { REPLACES_KEY, refuseStaleReplacement, replacesOf } from '../learnings/replacement-lineage.js';
59
61
  import { matchRulesForJob, stripRulesBrief, withRulesBrief } from '../decisions/rules-brief.js';
60
62
  import { SeatHealthTracker } from './seat-health.js';
61
63
  import { applyWorkerConfigRoot, signedInHeuristic } from './seat-signin.js';
@@ -66,7 +68,7 @@ import { chatSeatAdmission, homeless } from './seat-standing.js';
66
68
  import { seatGovernanceDiagnostics, seatGovernanceWarnings, } from './seat-governance.js';
67
69
  import { seatWorkDefaultNow } from './seat-work-default.js';
68
70
  import { ROSTER_REFRESH_WAIT_MS, rosterWithStandingFactory } from './roster-standing.js';
69
- import { SeatContainerStatus, isContainerLoginCli, isContainerSeatFloor, isHostSeatFloor, loginDetail, registerSeatContainerLoginRoutes, seatLoginDepsFor, } from './seat-container-login.js';
71
+ import { SeatContainerStatus, isContainerLoginCli, isContainerSeatFloor, isHostSeatFloor, registerSeatContainerLoginRoutes, seatLoginDepsFor, } from './seat-container-login.js';
70
72
  import { ChatTurnIndex } from './chat-turns.js';
71
73
  import { CHAT_ID, chatJobTurnLines, chatMakeDigest, ChatScopeIndex, chatScopeDeps, chatScopeStatement, prepareChatScratch, removeChatScratch, namedKindRefusal, resolveChatScope, } from './chat-scope.js';
72
74
  import { buildRequirementsMaps, publishRequirementsMaps, REQUIREMENTS_MAP_DIR } from './chat-requirements.js';
@@ -117,8 +119,10 @@ import { withPhaseSkillGaps } from '../skills/phase-skill-gaps.js';
117
119
  import { STATE_HOME_BLOCKER_CODE, STATE_HOME_REMEDY, isEngineStateHomeRefusal, stateHomeBlockerBody, } from '../projects/state-home-preflight.js';
118
120
  import { BASE_SKILL_POLICIES, BASE_SKILL_REF_SHAPE, baseSkillRemedy } from '../skills/base-skill.js';
119
121
  import { REQUIRED_GARDEN_VERSION } from '../skills/plugin-source.js';
122
+ import { isSeatKeyList } from '../core/job-seats.js';
120
123
  import { engineRosterJson, noEligibleSeatBody, parseNoEligibleSeat, toEngineSeat } from '../core/engine-roster.js';
121
124
  import { launchAssuranceNotice } from '../core/assurance.js';
125
+ import { launchPosture } from '../core/launch-posture.js';
122
126
  import { launchRequiresQe, mayRequireQe, qeAcceptanceMode, qeSettingSkipReason } from '../core/qe-acceptance-setting.js';
123
127
  import { aggregateReceipt, postHocDeliveryAssurance, qeAcceptanceFromView, qeAcceptanceRefusal, QE_ACCEPTANCE_REQUIRED_CODE, receiptOf, qeAcceptanceNotRequired, qeDecisionBypasses, qeDecisionOf, qeAcceptanceSkippedAtGate, unreadableQeAcceptance, } from './delivery-assurance.js';
124
128
  import { ProjectSettingsStore } from '../projects/settings.js';
@@ -144,7 +148,7 @@ const BRIEF_COPY_MAX = 512 * 1024;
144
148
  import { registerInteractiveDocDelete } from '../interactive/doc-delete-routes.js';
145
149
  import { registerInteractiveDocChecks } from '../interactive/doc-checks-routes.js';
146
150
  import { crewStateHome, stateHomeOfDb } from '../projects/state-home.js';
147
- import { demoShowOf, factsOf, inputLines, jobInputsOfProposal, jobLaunchCommon, personPid, requestDigest, SELF_SEATED } from './chat-jobs.js';
151
+ import { demoShowOf, factsOf, inputLines, jobInputsOfProposal, jobLaunchCommon, jobLaunchRoster, personPid, requestDigest, SELF_SEATED } from './chat-jobs.js';
148
152
  import { DocumentsRefused, documentsClause, RUN_DOCS_TOKENS_MAX, stagedDocumentsOf, stageRunDocuments } from './run-documents.js';
149
153
  import { checkSourcePick, projectSources, RUN_SOURCES_MAX, runSourcesDeps, webScopeReason } from './run-sources.js';
150
154
  import { CATALOG_V2_CARDS } from '../workflow-catalog/catalog-data-v2.js';
@@ -167,7 +171,8 @@ import { ATTACHMENT_LIMITS, ATTACHMENT_MAX_MESSAGE_BYTES, AttachmentError, ChatA
167
171
  import { CHAT_HISTORY_MAX_LIMIT, ChatHistoryStore, decodeCursor } from './chat-history.js';
168
172
  import { PROBE_TIMEOUT_MS, SYSTEM_BUDGET_MS, SYSTEM_STATS_DAYS, SYSTEM_STATS_TTL_MS, WeekFoldCache, assembleSnapshot, buildNeeds, buildClis, buildGovernance, diskRow, estateReadonlyCall, infraRow, judgeGaps, livenessThresholds, loadRow, probeBroker, probeBus, probeEstate, probeInteractive, probeVault, readBridgeLockAsync, readWeek, runLiveness, settleWithin, skillsRow, sortRuns, stateHomeRow, reposRow, unfinished, } from './system-snapshot.js';
169
173
  import { CLUSTER_TIMEOUT_MS, ClusterStatusReader, clusterDiagnostics, clusterRows } from './cluster-status.js';
170
- import { idleClis, parseSeatImageStatus, probeSeatImages, SeatImageRebuilder } from './seat-images.js';
174
+ import { deliveryRow, readDeliveryReadiness } from '../setup/delivery-readiness.js';
175
+ import { idleClis, probeSeatImages, SeatImageRebuilder, seatImageStatusVia } from './seat-images.js';
171
176
  import { RunCostCache } from './needs.js';
172
177
  import { governanceStoreFix, legacyHomeOutboxPath } from '../core/governance-store.js';
173
178
  import { UsageError, replayOutboxInto } from '../cli/governance.js';
@@ -475,25 +480,24 @@ const ExcludeLinkedIssuesSchema = z
475
480
  .optional();
476
481
  /**
477
482
  * F43: the seats a chat job (or a chat document's helpers) may name, and the ones its Start re-checks, in roster order:
478
- * the seats that can work now (enabled for council, work-eligible, not signed out) under the default launch rule
479
- * ({@link defaultLaunchRoster}: no opt-in seat unless it is the only one left). Filtered first, so a seat the predicate
480
- * drops never hides the fallback. The standing rows carry no `optIn` (only `GET /roster` marks it, `markOptIn`), so the
481
- * opt-in rule reads the key.
483
+ * the seats that can work now (enabled for council, work-eligible, not signed out), opt-in seats INCLUDED (crew#1590):
484
+ * naming or picking one is the opt-in. The default launch rule ({@link defaultLaunchRoster}: no opt-in seat unless it
485
+ * is the only one left) applies where nobody chose, the pool work is drawn from (`jobSeatPool`).
482
486
  */
483
487
  export function proposalRoster(standing) {
484
488
  const canWork = standing.filter((s) => s.enabled_for_council && s.seat_eligible_for_work !== false && s.auth !== 'signed_out');
485
- return defaultLaunchRoster(canWork).map((s) => ({ key: String(s.key), name: s.display_name || String(s.key) }));
489
+ return canWork.map((s) => ({ key: String(s.key), name: s.display_name || String(s.key) }));
486
490
  }
487
491
  /**
488
492
  * The default launch roster ({@link defaultLaunchRoster}: no opt-in seats) — plus the opt-in seat a
489
- * launch NAMES as its lead (`primary`): naming it is the opt-in.
493
+ * launch NAMES as its lead (`primary`), and (crew#1590) any other seat it names (`named`: a chat job's card seats):
494
+ * naming it is the opt-in.
490
495
  */
491
- export function launchRosterNaming(roster, primary) {
496
+ export function launchRosterNaming(roster, primary, named = []) {
492
497
  const base = defaultLaunchRoster(roster);
493
- if (primary === undefined || base.some((s) => s.key === primary))
494
- return base;
495
- const named = roster.find((s) => s.key === primary);
496
- return named === undefined ? base : [...base, named];
498
+ const wanted = [primary, ...named].filter((k) => k !== undefined && !base.some((s) => s.key === k));
499
+ const extra = wanted.map((k) => roster.find((s) => s.key === k)).filter((s) => s !== undefined);
500
+ return extra.length === 0 ? base : [...base, ...new Set(extra)];
497
501
  }
498
502
  /**
499
503
  * Why `primary` cannot lead a launch on `clisJson`'s roster, or `null` when it can (DES-TEAMING-002
@@ -2804,8 +2808,6 @@ runtime = {}) {
2804
2808
  }
2805
2809
  if (b.entityMode !== undefined)
2806
2810
  input.entityMode = b.entityMode;
2807
- if (b.humanConfirm !== undefined)
2808
- input.humanConfirm = b.humanConfirm;
2809
2811
  // F-E2E-030: only the explicit `'auto'` opts out of the engine's deliver gate. `'human'` and
2810
2812
  // an omitted field both leave `autoDeliver` off the input — the gate is the engine's default,
2811
2813
  // so the wire never has to say "gate me" to be gated.
@@ -2835,7 +2837,6 @@ runtime = {}) {
2835
2837
  '(unless the launch explicitly skips QE acceptance with a reason: skipQeAcceptance)',
2836
2838
  });
2837
2839
  }
2838
- input.autoDeliver = true;
2839
2840
  }
2840
2841
  if (b.repoRef !== undefined)
2841
2842
  input.repoRef = b.repoRef;
@@ -2860,95 +2861,35 @@ runtime = {}) {
2860
2861
  input.projectGraph = decision.binding;
2861
2862
  req.log.info({ runId: input.sessionId, projectId: b.projectId, repoRef: b.repoRef ?? null }, `run ${input.sessionId}: ${decision.reason}`);
2862
2863
  }
2863
- // The delivery contract (crew#393): a completed code run must end with a reviewable
2864
- // deliverable, or an explicit, recorded decision not to. So the deliver option is resolved
2865
- // HERE, at the boundary, for every launch:
2866
- // - explicit 'pr' / 'none' wins (the operator decided);
2867
- // - omitted + repo-scoped + a CODE-WORK workflow (the def carries at least one
2868
- // `executes_code` phase that is NOT an evaluator — feature/bug/migration and a Tool
2869
- // phase that writes, not chat/onboarding/recon, and not domain-extraction, whose only
2870
- // code phase is the `coverage` EVALUATOR, which executes code solely to write its own
2871
- // report into the tree for its validator — nothing to deliver) ⇒ the
2872
- // daemon's `deliverDefault` setting ('pr' unless the operator flipped it) — the default
2873
- // that keeps run 83052f0b's work from stranding invisibly again. The code-work guard is
2874
- // the issue's own scope ("default deliver:'pr' for CODE-WORK launches"): a read-only
2875
- // workflow leaves a clean worktree, and the deliver script FAILS a clean worktree loudly
2876
- // ("nothing to deliver", crew#317) — defaulting it on would flip every repo-scoped chat
2877
- // from completed to failed;
2878
- // - omitted otherwise ⇒ 'none': a repo-less run has no worktree to lift, and a free-text
2879
- // run has no def to append the deliver phase to (the adapter REFUSES deliver:'pr'
2880
- // without a workflow rather than silently dropping it, so defaulting it on would turn
2881
- // a legal launch into a 400).
2882
- // The adapter input spells 'none' as an omitted field; the audit entry below records the
2883
- // RESOLVED value either way, plus whether it was defaulted.
2884
- let deliver;
2885
- let deliverDefaulted = false;
2886
- if (b.deliver !== undefined) {
2887
- deliver = b.deliver;
2888
- }
2889
- else if (b.repoRef !== undefined && b.workflow !== undefined) {
2890
- // Unknown def ⇒ no default (the launch fails at workflow resolution with its own error —
2891
- // defaulting 'pr' onto it would swap that for a misleading deliver-flavored one).
2892
- const def = adapter.getWorkflow(b.workflow);
2893
- const codeWork = def !== null &&
2894
- def.phases.some((p) => p.executes_code === true && p.role !== 'evaluator');
2895
- deliver =
2896
- codeWork && (await adapter.getSettings()).deliverDefault !== 'none' ? 'pr' : 'none';
2897
- deliverDefaulted = true;
2898
- }
2899
- else {
2900
- deliver = 'none';
2901
- deliverDefaulted = true;
2902
- }
2864
+ // (studio#1150) The launch's human gates — power, the posture the engine keeps, delivery and its gate — are ONE
2865
+ // decision (`core/launch-posture.ts`), the same one `POST /runs/preview` answers for this body, so a launch form
2866
+ // shows what the run keeps. The rules (crew#393 delivery, DES-POWER-MODE, F-E2E-030) are documented there.
2867
+ const posture = await launchPosture(b, postureFacts, { powerRequired: ctx.powerRequired });
2868
+ let deliver = posture.resolvedDeliver;
2869
+ const deliverDefaulted = posture.deliverDefaulted;
2903
2870
  if (deliver === 'pr')
2904
2871
  input.deliver = 'pr';
2872
+ if (posture.autoDeliver)
2873
+ input.autoDeliver = true;
2905
2874
  // wicked-core#850 EX-01/EX-02: forwarded only when the caller sent it — crew never waives
2906
2875
  // assurance on anyone's behalf (a one-CLI launch that did not is TOLD so in its answer, below).
2907
2876
  if (b.reducedAssurance === true)
2908
2877
  input.reducedAssurance = true;
2909
- // (program DES-POWER-MODE, operator ruling 2026-10-29) POWER MODE is the default way a job runs:
2910
- // the launch's own word, else the `powerModeDefault` setting (on when unset). Only a repo-scoped
2911
- // plan or preset launch can run as one orchestrator session, and only on an engine that carries it
2912
- // (any other launch is phased, said in the answer). A power launch has no plan-approval gate:
2913
- // the only human gate is deliver, plus what policy requires (a high-risk plan still holds).
2914
- let powerNotice = null;
2915
- let humanConfirmNotice = null;
2916
- // The caller's word, else the setting (read only when the launch did not say).
2917
- const powerWanted = b.power ?? (b.repoRef !== undefined && (b.workflow !== undefined || b.plan !== undefined)
2918
- ? ((await adapter.getSettings()).powerModeDefault ?? true)
2919
- : false);
2920
- if (powerWanted) {
2921
- // A plan, or a workflow the engine resolves to a PRESET (a registered def is planned the legacy way
2922
- // and has no orchestrator build): only those run in power mode, so only those lose run-level gates.
2923
- const isPreset = b.plan !== undefined || (b.workflow !== undefined && await namesPreset(b.workflow, b.projectId));
2924
- if (b.repoRef === undefined || !isPreset) {
2925
- powerNotice = 'power mode runs a repo-scoped plan or preset launch; this launch runs phased';
2926
- }
2927
- else if (!powerSupported()) {
2928
- powerNotice = 'this engine has no power mode; the launch runs phased';
2929
- }
2930
- else if (ctx.powerRequired === true && ((await adapter.getSettings()).powerModeDefault ?? true) === false) {
2931
- // A chat job's power Start follows the setting up to the engine call (it may have been turned off meanwhile).
2932
- powerNotice = 'Power mode for new jobs is off on this daemon; the launch runs phased';
2933
- }
2934
- // A chat job's power Start is never run phased in its place (the person chose no plan review for a power run).
2935
- if (powerNotice !== null && ctx.powerRequired === true) {
2936
- return reply.code(409).send({ code: 'power_unavailable', error: `${powerNotice.replace(/; this launch runs phased|; the launch runs phased/u, '')}; press Start with Review plan on` });
2937
- }
2938
- if (powerNotice === null) {
2939
- input.power = true;
2940
- // (studio#1150) A power run asks once, at hand-off: a posture the launch named is not kept — and the answer says so.
2941
- if (input.humanConfirm !== undefined && input.humanConfirm !== 'none') {
2942
- humanConfirmNotice = `power mode asks once, at hand-off: humanConfirm ${input.humanConfirm} is not kept (launch with power: false to keep it)`;
2943
- }
2944
- input.humanConfirm = 'none';
2945
- // DES-LEARN §3.3 / wicked-core#1216: the orchestrator talks to the person in their personality
2946
- // for this project (the project's override, else theirs). The engine hands it to the
2947
- // orchestrator only; reviewers, judges and QE never hear it.
2948
- const { voice } = voiceFor(b.projectId);
2949
- if (voice !== undefined)
2950
- input.voice = voice;
2951
- }
2878
+ const { powerNotice, humanConfirmNotice } = posture;
2879
+ // A chat job's power Start is never run phased in its place (the person chose no plan review for a power run).
2880
+ if (posture.powerRefusal !== null) {
2881
+ return reply.code(409).send({ code: 'power_unavailable', error: posture.powerRefusal });
2882
+ }
2883
+ if (posture.humanConfirm !== undefined)
2884
+ input.humanConfirm = posture.humanConfirm;
2885
+ if (posture.power) {
2886
+ input.power = true;
2887
+ // DES-LEARN §3.3 / wicked-core#1216: the orchestrator talks to the person in their personality
2888
+ // for this project (the project's override, else theirs). The engine hands it to the
2889
+ // orchestrator only; reviewers, judges and QE never hear it.
2890
+ const { voice } = voiceFor(b.projectId);
2891
+ if (voice !== undefined)
2892
+ input.voice = voice;
2952
2893
  }
2953
2894
  // QE-IN-APP-WORKFLOWS: the operator's explicit skip (with its reason) or force — forwarded only
2954
2895
  // when sent, never inferred.
@@ -3194,7 +3135,7 @@ runtime = {}) {
3194
3135
  }
3195
3136
  deliver = 'none';
3196
3137
  }
3197
- const isReview = b.workflow === REVIEW_WORKFLOW && runtime.reviewLaunch !== undefined;
3138
+ const isReview = b.workflow !== undefined && reviewPrepared(b.workflow);
3198
3139
  if (isReview) {
3199
3140
  try {
3200
3141
  await runtime.reviewLaunch(input);
@@ -3535,6 +3476,40 @@ runtime = {}) {
3535
3476
  const out = await launchRun(req.body, { actor: actorOf(req), log: req.log });
3536
3477
  return reply.code(out.statusCode).send(out.payload);
3537
3478
  });
3479
+ // (studio#1150) What a launch of this body would keep of its human gates — the SAME `launchPosture` decision
3480
+ // `POST /runs` hands the engine — with nothing launched, recorded or read beyond what that decision reads. A launch
3481
+ // form renders it (and sends the `power` it shows) instead of modelling crew's rules.
3482
+ const LaunchPreviewSchema = z.strictObject({
3483
+ power: z.boolean().optional(),
3484
+ repoRef: z.string().min(1).optional(),
3485
+ workflow: z.string().min(1).optional(),
3486
+ plan: PlanSchema.optional(),
3487
+ projectId: z.string().min(1).optional(),
3488
+ humanConfirm: z.string().min(1).optional(),
3489
+ deliver: z.enum(['pr', 'none']).optional(),
3490
+ deliverGate: z.enum(['human', 'auto']).optional(),
3491
+ }).refine((b) => b.plan === undefined || b.workflow === undefined, {
3492
+ path: ['plan'],
3493
+ error: 'plan and workflow are mutually exclusive',
3494
+ }).refine((b) => b.deliverGate === undefined || b.deliver !== 'none', {
3495
+ path: ['deliverGate'],
3496
+ error: 'deliverGate has no meaning with deliver: "none" — there is no deliver phase to gate',
3497
+ });
3498
+ app.post(`${V}/runs/preview`, { config: { manifest: { requestType: 'LaunchPreviewBody', responseType: 'LaunchPreviewResponse', statusCodes: [200, 400] } } }, async (req, reply) => {
3499
+ const parsed = LaunchPreviewSchema.safeParse(req.body ?? {});
3500
+ if (!parsed.success)
3501
+ return reply.code(400).send(invalidBody(parsed.error, 'Invalid request body'));
3502
+ const p = await launchPosture(parsed.data, postureFacts);
3503
+ const posture = {
3504
+ power: p.power,
3505
+ ...(p.humanConfirm !== undefined ? { humanConfirm: p.humanConfirm } : {}),
3506
+ deliver: p.deliver,
3507
+ autoDeliver: p.autoDeliver,
3508
+ ...(p.powerNotice !== null ? { powerNotice: p.powerNotice } : {}),
3509
+ ...(p.humanConfirmNotice !== null ? { humanConfirmNotice: p.humanConfirmNotice } : {}),
3510
+ };
3511
+ return { posture };
3512
+ });
3538
3513
  /**
3539
3514
  * (DES-CATALOG-002 §4.6) The `job` launcher: a chat job proposal's Go, one launcher per launch kind, each with the
3540
3515
  * identity derived from the proposal (`sessionId` = its run id, so a retry finds and adopts it), the chat filing, the
@@ -3602,30 +3577,16 @@ runtime = {}) {
3602
3577
  if (resolved === null)
3603
3578
  throw new Error(`${p.what.label} is no longer in the catalog`);
3604
3579
  const selfSeated = resolved.workflow !== null && SELF_SEATED.has(resolved.workflow);
3605
- // The seats the person saw: the lead, and the roster narrowed to the proposal's keys.
3606
- const lead = p.seats?.lead ?? undefined;
3607
- const keys = p.seats?.keys ?? [];
3608
- // A reshape inherits the held run's roster configuration; its membership is still the proposal's seats (codex r2).
3609
- let inherited = null;
3610
- if (p.relaunch?.clisJson !== undefined) {
3611
- try {
3612
- const parsedRoster = JSON.parse(p.relaunch.clisJson);
3613
- if (Array.isArray(parsedRoster))
3614
- inherited = parsedRoster;
3615
- }
3616
- catch {
3617
- inherited = null;
3618
- }
3619
- }
3620
- const current = launchRosterNaming(rosterWithStanding(), lead);
3621
- // Inherited configuration for the seats it names; the current roster's entry for a seat added since (codex r3).
3622
- const roster = inherited === null ? current : [...inherited, ...current.filter((s) => !inherited.some((i) => i.key === s.key))];
3623
- const narrowed = keys.length > 0 ? roster.filter((s) => keys.includes(String(s.key))) : roster;
3624
- const missingSeat = keys.find((k) => !roster.some((s) => String(s.key) === k));
3625
- if (missingSeat !== undefined)
3626
- throw new Error(`${missingSeat} is not on this daemon's roster; change who works on it`);
3580
+ // The seats the person saw: the lead, and the roster narrowed to the proposal's keys (`jobLaunchRoster`).
3581
+ // crew#645 / crew#1593 (coord merge check): the card says WHICH seats, never that they are usable now. The same
3582
+ // bounded readiness wait a launch with no roster gets runs FIRST, so the standing serialized here (and the lead's
3583
+ // eligibility `launchRun` checks against it) is the seats' own fresh answer: a lead whose login expired is refused
3584
+ // by name, never launched on a stale snapshot. A seat added meanwhile still doesn't join (narrowed to the card).
3585
+ await rosterWithStanding.ready?.();
3586
+ // crew#1590: every seat on the card is named, so an opt-in seat the person picked is on the roster too.
3587
+ const { clisJson } = jobLaunchRoster(launchRosterNaming(rosterWithStanding(), p.seats?.lead ?? undefined, p.seats?.keys ?? []), p);
3627
3588
  const common = jobLaunchCommon(p, { runId: d.identity.runId, chatId: d.chatId }, {
3628
- ...((inherited !== null || narrowed.length !== roster.length) && narrowed.length > 0 ? { clisJson: JSON.stringify(narrowed) } : {}),
3589
+ ...(clisJson !== undefined ? { clisJson } : {}),
3629
3590
  selfSeated,
3630
3591
  });
3631
3592
  // A power Start was checked before accepting; checked again here, so it never runs phased behind the person's back.
@@ -4438,7 +4399,8 @@ runtime = {}) {
4438
4399
  // proposal, completing the proposal while the chat is open; never open the id again (codex r1).
4439
4400
  const open = askPaths.get(seedChatId) !== undefined || chatScopes.get(seedChatId) !== undefined;
4440
4401
  if (open || chatHistory?.has(seedChatId) === true) {
4441
- let view = chatProposals.viewOfPid(seedChatId, personPid(seedChatId, seedActor.id, b.requestId));
4402
+ const stored = chatProposals.viewOfPid(seedChatId, personPid(seedChatId, seedActor.id, b.requestId));
4403
+ let view = stored === null ? null : await chatProposals.servedView(stored);
4442
4404
  // The same request id with another seed is not a retry (codex r2).
4443
4405
  if (view !== null && view.proposal.request?.digest !== requestDigest(seedBody(b.seed, b.requestId))) {
4444
4406
  return reply.code(409).send({ code: 'request_reused', error: 'this requestId already started a chat with another job', chatId: seedChatId });
@@ -4963,6 +4925,8 @@ runtime = {}) {
4963
4925
  };
4964
4926
  },
4965
4927
  rosterEligible: () => proposalRoster(rosterWithStanding()),
4928
+ // (F1/F2) Agents › "Use <seat> for new work": the pool every new chat job and document is drawn from.
4929
+ newWorkSeats: readNewWorkSeats,
4966
4930
  runs: async () => (await adapter.sessionsDetail()).map((v) => decorateRun(v)),
4967
4931
  chatOfRun: (runId) => runTimingIndex.chatIdFor(runId),
4968
4932
  isAskPath: (runId) => runTimingIndex.isAskPath(runId),
@@ -5820,7 +5784,9 @@ runtime = {}) {
5820
5784
  // turn. The file goes with the chat on `chatClosed` UNLESS a run promoted from it is still
5821
5785
  // live (crew#619 retention — dropped when that run terminals), so a reclaimed id answers
5822
5786
  // `[]` only once no promoted run holds the old file.
5823
- ...(chatTranscripts !== undefined ? { messages: chatTranscripts.read(id) } : {}),
5787
+ // (F1/F2) Served like `GET /chats/:id/messages`: an open job or document reads blocked while `newWorkSeats`
5788
+ // can't be honored.
5789
+ ...(chatTranscripts !== undefined ? { messages: await chatProposals.withSeatsSetting(chatTranscripts.read(id)) } : {}),
5824
5790
  };
5825
5791
  }
5826
5792
  catch (err) {
@@ -5950,7 +5916,8 @@ runtime = {}) {
5950
5916
  const messages = chat === null ? null : chatHistory.messages(id);
5951
5917
  if (chat === null || messages === null)
5952
5918
  return reply.code(404).send({ error: `no chat ${id} in this daemon's history` });
5953
- return { chat, messages, attachments: chatAttachments.list(id) };
5919
+ // (F1/F2) An open job or document reads blocked while `newWorkSeats` can't be honored: a live state, read now.
5920
+ return { chat, messages: await chatProposals.withSeatsSetting(messages), attachments: chatAttachments.list(id) };
5954
5921
  });
5955
5922
  // DES-SYSTEM-CHAT (api-types 0.137.0): upload files to a chat (multipart/form-data). The body is
5956
5923
  // buffered by a parser scoped to this route alone, capped a little over the per-message total;
@@ -7062,6 +7029,47 @@ runtime = {}) {
7062
7029
  function powerSupported() {
7063
7030
  return typeof adapter.supportsPowerMode === 'function' && adapter.supportsPowerMode();
7064
7031
  }
7032
+ /** A hand launch of the run review is prepared by the daemon (DES-RUNS-REVIEW-001 §3) when it carries the review service. */
7033
+ function reviewPrepared(workflow) {
7034
+ return workflow === REVIEW_WORKFLOW && runtime.reviewLaunch !== undefined;
7035
+ }
7036
+ /** (studio#1150) What `launchPosture` reads of this daemon, for `POST /runs` and `POST /runs/preview` alike. */
7037
+ const postureFacts = {
7038
+ powerModeDefault: async () => (await adapter.getSettings()).powerModeDefault ?? true,
7039
+ namesPreset,
7040
+ powerSupported,
7041
+ // The delivery contract (crew#393): a completed code run must end with a reviewable
7042
+ // deliverable, or an explicit, recorded decision not to. So the deliver option is resolved
7043
+ // HERE, at the boundary, for every launch:
7044
+ // - explicit 'pr' / 'none' wins (the operator decided);
7045
+ // - omitted + repo-scoped + a CODE-WORK workflow (the def carries at least one
7046
+ // `executes_code` phase that is NOT an evaluator — feature/bug/migration and a Tool
7047
+ // phase that writes, not chat/onboarding/recon, and not domain-extraction, whose only
7048
+ // code phase is the `coverage` EVALUATOR, which executes code solely to write its own
7049
+ // report into the tree for its validator — nothing to deliver) ⇒ the
7050
+ // daemon's `deliverDefault` setting ('pr' unless the operator flipped it) — the default
7051
+ // that keeps run 83052f0b's work from stranding invisibly again. The code-work guard is
7052
+ // the issue's own scope ("default deliver:'pr' for CODE-WORK launches"): a read-only
7053
+ // workflow leaves a clean worktree, and the deliver script FAILS a clean worktree loudly
7054
+ // ("nothing to deliver", crew#317) — defaulting it on would flip every repo-scoped chat
7055
+ // from completed to failed;
7056
+ // - omitted otherwise ⇒ 'none': a repo-less run has no worktree to lift, and a free-text
7057
+ // run has no def to append the deliver phase to (the adapter REFUSES deliver:'pr'
7058
+ // without a workflow rather than silently dropping it, so defaulting it on would turn
7059
+ // a legal launch into a 400).
7060
+ // The adapter input spells 'none' as an omitted field; the audit entry below records the
7061
+ // RESOLVED value either way, plus whether it was defaulted.
7062
+ deliverDefault: async (workflow) => {
7063
+ // Unknown def ⇒ no default (the launch fails at workflow resolution with its own error —
7064
+ // defaulting 'pr' onto it would swap that for a misleading deliver-flavored one).
7065
+ const def = adapter.getWorkflow(workflow);
7066
+ const codeWork = def !== null && def.phases.some((p) => p.executes_code === true && p.role !== 'evaluator');
7067
+ return codeWork && (await adapter.getSettings()).deliverDefault !== 'none' ? 'pr' : 'none';
7068
+ },
7069
+ // The launch route removes a change review's delivery (it posts nothing), and a run review's preparation removes it
7070
+ // (`ReviewService.prepareLaunch`). The default evals' preparation keeps whatever delivery was resolved.
7071
+ preparationDropsDelivery: (workflow) => workflow === REVIEW_CHANGE_WORKFLOW || reviewPrepared(workflow),
7072
+ };
7065
7073
  // ── Power mode (program DES-POWER-MODE; api-types 0.149.0) ─────────────────────────────────────
7066
7074
  // The engine computes every rigor value; these routes only carry a person's switch, raise or pause
7067
7075
  // answer to it (human actors only: a worker or plugin bearer gets 403) and read its record back.
@@ -9099,6 +9107,16 @@ runtime = {}) {
9099
9107
  return reply.code(403).send({ error: 'Only a person can change the power mode default (powerModeDefault)' });
9100
9108
  }
9101
9109
  }
9110
+ // newWorkSeats (F1/F2): which seats new chats and jobs are drawn from (`core/job-seats.ts`). A list of seat keys,
9111
+ // or null for the default rule; a person's choice only (a worker's bearer gets 403).
9112
+ if (Object.hasOwn(patch, 'newWorkSeats')) {
9113
+ if (patch.newWorkSeats !== null && !isSeatKeyList(patch.newWorkSeats)) {
9114
+ return reply.code(400).send({ error: 'newWorkSeats must be a list of seat keys (at most 64), or null' });
9115
+ }
9116
+ if (!isHumanOperator(actorOf(req))) {
9117
+ return reply.code(403).send({ error: 'Only a person can change which seats new work uses (newWorkSeats)' });
9118
+ }
9119
+ }
9102
9120
  // qeAcceptance (api-types 0.120.0): 'required' | 'off' only. 'off' skips QE acceptance on every
9103
9121
  // launch that requires it (labelled with the setting), so a typo must be a 400, never a dropped key.
9104
9122
  // Turning it off waives an assurance instrument on every launch after it, so only a PERSON may
@@ -9181,7 +9199,11 @@ runtime = {}) {
9181
9199
  const problem = registry.validateSettingsPatch(patch.watch);
9182
9200
  if (problem !== null)
9183
9201
  return reply.code(400).send({ error: problem });
9184
- watchNext = registry.mergeSettings((await adapter.getSettings()).watch, patch.watch, actor.id, Date.now());
9202
+ // The merge runs INSIDE the settings write (crew#1591), against the stored `watch` it
9203
+ // replaces — merging over an earlier read would let two people's switches revert each other.
9204
+ const watchPatch = patch.watch;
9205
+ const at = Date.now();
9206
+ watchNext = (current) => registry.mergeSettings(current.watch, watchPatch, actor.id, at);
9185
9207
  }
9186
9208
  // Only known engine keys and validated `studio.*` keys are persisted. A key that is
9187
9209
  // NEITHER is dropped, not refused: request bodies are forward-additive too (DES-STUDIO-001
@@ -9199,6 +9221,7 @@ runtime = {}) {
9199
9221
  'deliverDefault',
9200
9222
  'qeAcceptance',
9201
9223
  'powerModeDefault',
9224
+ 'newWorkSeats',
9202
9225
  'onboardingAutoCapture',
9203
9226
  'deliverIdentityLogin',
9204
9227
  'deliverIdentityByRepo',
@@ -9223,13 +9246,16 @@ runtime = {}) {
9223
9246
  for (const key of studioKeys) {
9224
9247
  safe[key] = patch[key];
9225
9248
  }
9226
- if (watchNext !== undefined)
9227
- safe.watch = watchNext;
9228
9249
  // `Object.hasOwn`, NOT `k in safe`: `in` walks the prototype chain, so a dropped key named
9229
9250
  // `toString` / `valueOf` / `constructor` would test as "kept" and vanish from `ignored` —
9230
9251
  // the exact silent drop this route exists to end.
9231
- const ignored = Object.keys(patch).filter((k) => !Object.hasOwn(safe, k));
9232
- const settings = await adapter.updateSettings(safe);
9252
+ // `watch` is merged inside the write (crew#1591), so it is persisted without sitting in `safe`.
9253
+ const changed = watchNext === undefined ? Object.keys(safe) : [...Object.keys(safe), 'watch'];
9254
+ const ignored = Object.keys(patch).filter((k) => !Object.hasOwn(safe, k) && !(k === 'watch' && watchNext !== undefined));
9255
+ const derive = watchNext;
9256
+ const settings = derive === undefined
9257
+ ? await adapter.updateSettings(safe)
9258
+ : await adapter.updateSettings(safe, (current) => ({ watch: derive(current) }));
9233
9259
  if (watchNext !== undefined)
9234
9260
  runtime.watchRegistry?.()?.applySettings(settings.watch);
9235
9261
  // Re-apply the worker-config root to this process's env (seat sign-in). The engine reads
@@ -9251,7 +9277,7 @@ runtime = {}) {
9251
9277
  // when there is one) is where a dropped unknown key stops being invisible.
9252
9278
  audit.record('settings.updated', actorOf(req), {
9253
9279
  detail: {
9254
- changed: Object.keys(safe),
9280
+ changed,
9255
9281
  ...(ignored.length > 0 ? { ignored } : {}),
9256
9282
  // Which watchers were switched or re-thresholded (health reads the stamps; this is the trail).
9257
9283
  ...(watchNext !== undefined ? { watch: patch.watch } : {}),
@@ -9450,6 +9476,16 @@ runtime = {}) {
9450
9476
  catch (err) {
9451
9477
  return estateUpstreamError(reply, err);
9452
9478
  }
9479
+ // crew#1546: an edited learning's replacement whose learning is gone is stale: refused and rejected, never approved,
9480
+ // so no crash window can bring retired words back (accept-with-edit checks the same in `approveEdited`).
9481
+ try {
9482
+ const stale = row?.kind_type === 'memory' ? await refuseStaleReplacement(estateTool, id, row.payload) : null;
9483
+ if (stale !== null)
9484
+ return reply.code(409).send({ error: stale, code: 'stale_replacement' });
9485
+ }
9486
+ catch (err) {
9487
+ return reply.code(502).send({ error: `checking whether proposal ${id} is a stale replacement failed (${message(err)}); nothing was approved` });
9488
+ }
9453
9489
  // DC-S4a: a proposal THIS ledger filed for a decision lands through `remember()` — the one
9454
9490
  // landing path, with the human check inside it (§4.5). A payload naming an id the ledger does
9455
9491
  // not know is an ordinary policy proposal (no ORIGIN claim) and takes the path below.
@@ -9854,6 +9890,181 @@ runtime = {}) {
9854
9890
  return items.map(shapeMemoryItem);
9855
9891
  };
9856
9892
  const deletedCount = (raw) => (typeof raw === 'object' && raw !== null ? raw['deleted_count'] : undefined);
9893
+ const pendingMemoryProposals = async () => {
9894
+ const raw = await estateTool('proposal.list', { kind_type: 'memory', state: 'pending' });
9895
+ const items = typeof raw === 'object' && raw !== null ? raw['proposals'] : undefined;
9896
+ if (!Array.isArray(items))
9897
+ throw new EstateMcpError('proposal.list returned an unexpected shape');
9898
+ return items.flatMap((i) => {
9899
+ const r = typeof i === 'object' && i !== null ? i : {};
9900
+ const payload = typeof r['payload'] === 'object' && r['payload'] !== null ? r['payload'] : {};
9901
+ const facets = typeof r['facets'] === 'object' && r['facets'] !== null ? r['facets'] : {};
9902
+ return typeof r['id'] === 'string'
9903
+ ? [{ id: r['id'], content: typeof payload['content'] === 'string' ? payload['content'] : '', reach: typeof payload['reach'] === 'string' ? payload['reach'] : null, facets, replaces: replacesOf(payload) }]
9904
+ : [];
9905
+ });
9906
+ };
9907
+ /** Reject these proposals; true only when the queue is read back with none of them pending. */
9908
+ const withdraw = async (ids) => {
9909
+ for (const id of ids)
9910
+ await estateTool('proposal.reject', { id }).catch(() => undefined);
9911
+ try {
9912
+ const still = new Set((await pendingMemoryProposals()).map((q) => q.id));
9913
+ return ids.every((id) => !still.has(id));
9914
+ }
9915
+ catch {
9916
+ return false;
9917
+ }
9918
+ };
9919
+ const queued = (ids) => ` A proposal of the new words (${ids.join(', ')}) may still be pending: reject it on the approve page.`;
9920
+ const reapproveMemory = async (old, content, beforeIds) => {
9921
+ const reach = old.scope === '' ? 'project' : old.scope.startsWith('operator:') ? 'operator' : null;
9922
+ if (reach === null) {
9923
+ return { status: 409, error: `${old.id} is an approved learning at scope ${JSON.stringify(old.scope)}, which approval cannot place again; nothing changed` };
9924
+ }
9925
+ // The replacement names what it replaces, so approval can refuse it once that memory is gone.
9926
+ const payload = { content, reach, [REPLACES_KEY]: old.id };
9927
+ if (old.tier !== '')
9928
+ payload['tier'] = old.tier;
9929
+ // What was already queued, so a submit whose answer is lost can find the one it filed.
9930
+ let queuedBefore;
9931
+ try {
9932
+ queuedBefore = new Set((await pendingMemoryProposals()).map((q) => q.id));
9933
+ }
9934
+ catch (err) {
9935
+ return { status: 502, error: `reading the approve queue failed (${message(err)}); nothing changed` };
9936
+ }
9937
+ // The memory's OWN proposal must be settled first (codex r2 on crew#1546): estate writes `proposal:<id>`
9938
+ // before it records the approval, so a write that failed in between leaves it pending, and approving it after
9939
+ // this edit would bring the retired words back. Approving it again writes the same memory (idempotent).
9940
+ const sourcePid = old.id.slice(APPROVED_MEMORY_PREFIX.length);
9941
+ if (queuedBefore.has(sourcePid)) {
9942
+ await estateTool('proposal.approve', { id: sourcePid }).catch(() => undefined);
9943
+ try {
9944
+ queuedBefore = new Set((await pendingMemoryProposals()).map((q) => q.id));
9945
+ }
9946
+ catch (err) {
9947
+ return { status: 502, error: `settling ${old.id}'s own proposal could not be checked (${message(err)}); nothing changed` };
9948
+ }
9949
+ if (queuedBefore.has(sourcePid)) {
9950
+ return { status: 409, error: `${old.id}'s own proposal ${sourcePid} is still pending and could not be settled; approve or reject it on the approve page first. Nothing changed` };
9951
+ }
9952
+ }
9953
+ // Superseded replacements are settled too (coord merge check): one of this memory left pending by an edit that
9954
+ // never finished, or of a memory that is already gone, is rejected before the new one is filed.
9955
+ let superseded;
9956
+ try {
9957
+ superseded = (await pendingMemoryProposals()).filter((q) => q.replaces !== null && (q.replaces === old.id || !beforeIds.has(q.replaces))).map((q) => q.id);
9958
+ }
9959
+ catch (err) {
9960
+ return { status: 502, error: `reading the approve queue failed (${message(err)}); nothing changed` };
9961
+ }
9962
+ if (superseded.length > 0 && !(await withdraw(superseded))) {
9963
+ return { status: 502, error: `an earlier replacement of ${old.id} (${superseded.join(', ')}) is still pending and could not be rejected; reject it on the approve page first. Nothing changed` };
9964
+ }
9965
+ let pid = null;
9966
+ let submitErr = null;
9967
+ try {
9968
+ const raw = await estateTool('proposal.submit', { kind_type: 'memory', payload, facets: old.facets });
9969
+ const id = typeof raw === 'object' && raw !== null ? raw['id'] : undefined;
9970
+ if (typeof id === 'string' && id !== '')
9971
+ pid = id;
9972
+ else
9973
+ submitErr = new EstateMcpError('proposal.submit returned no proposal id');
9974
+ }
9975
+ catch (err) {
9976
+ submitErr = err;
9977
+ }
9978
+ if (pid === null) {
9979
+ // The submit may still have filed (a lost answer): find what it filed and withdraw it.
9980
+ // Ours = new since the snapshot, with these words, this reach and these facets (codex r2: words alone would
9981
+ // reject another caller's filing for another repository).
9982
+ const ours = (q) => !queuedBefore.has(q.id) && q.content === content && (q.reach === null || q.reach === reach) && q.replaces === old.id &&
9983
+ Object.entries(old.facets).every(([k, v]) => q.facets[k] === v) && Object.keys(q.facets).every((k) => k in old.facets);
9984
+ let strays;
9985
+ try {
9986
+ strays = (await pendingMemoryProposals()).filter(ours).map((q) => q.id);
9987
+ }
9988
+ catch (err) {
9989
+ return { status: 502, error: `filing the new words for approval failed (${message(submitErr)}) and the queue could not be re-read (${message(err)}).${queued(['unknown id'])}` };
9990
+ }
9991
+ const gone = strays.length === 0 || (await withdraw(strays));
9992
+ // A filing approved meanwhile is no longer pending: the store, not the queue, says whether it landed.
9993
+ let approvedCopies;
9994
+ try {
9995
+ approvedCopies = (await listAll()).filter((m) => m.id.startsWith(APPROVED_MEMORY_PREFIX) && !beforeIds.has(m.id) && m.content.trim() === content).map((m) => m.id);
9996
+ }
9997
+ catch {
9998
+ approvedCopies = null;
9999
+ }
10000
+ const landedNote = approvedCopies === null
10001
+ ? `; the store could not be re-read, so an approved copy of the new words may exist beside ${old.id}`
10002
+ : approvedCopies.length > 0
10003
+ ? `; an approved copy of the new words exists beside ${old.id}: ${approvedCopies.join(', ')}`
10004
+ : '';
10005
+ return {
10006
+ status: 502,
10007
+ error: `filing the new words for approval failed (${message(submitErr)})${landedNote === '' ? '; nothing changed' : landedNote}${gone ? '' : `.${queued(strays)}`}`,
10008
+ };
10009
+ }
10010
+ const newId = `${APPROVED_MEMORY_PREFIX}${pid}`;
10011
+ const approve = () => estateTool('proposal.approve', { id: pid }).then(() => null, (err) => err);
10012
+ const approveErr = await approve();
10013
+ let landed;
10014
+ try {
10015
+ landed = (await listAll()).find((m) => m.id === newId);
10016
+ }
10017
+ catch (err) {
10018
+ return { status: 502, error: `approving the new words could not be checked (${message(err)}); ${newId} may exist beside ${old.id}.${queued([pid])}` };
10019
+ }
10020
+ if (landed === undefined) {
10021
+ const gone = await withdraw([pid]);
10022
+ return { status: 502, error: `approving the new words failed (${approveErr === null ? 'no memory was written' : message(approveErr)}); nothing changed${gone ? '' : `.${queued([pid])}`}` };
10023
+ }
10024
+ // Taking a written replacement back out: its memory erased and its proposal never left pending.
10025
+ const undo = async (why) => {
10026
+ await estateTool('memory.erase', { id: newId }).catch(() => undefined);
10027
+ let erased = false;
10028
+ try {
10029
+ erased = !(await listAll()).some((m) => m.id === newId);
10030
+ }
10031
+ catch {
10032
+ // Reported below as not confirmed gone.
10033
+ }
10034
+ let settled = false;
10035
+ try {
10036
+ settled = !(await pendingMemoryProposals()).some((q) => q.id === pid) || (await withdraw([pid]));
10037
+ }
10038
+ catch {
10039
+ settled = await withdraw([pid]);
10040
+ }
10041
+ return {
10042
+ status: 502,
10043
+ error: erased
10044
+ ? `${why}; they were taken back out, so nothing changed${settled ? '' : `.${queued([pid])}`}`
10045
+ : `${why}; taking ${newId} back out was not confirmed, so both ${old.id} and ${newId} may remain${settled ? '' : `.${queued([pid])}`}`,
10046
+ };
10047
+ };
10048
+ if (landed.scope !== old.scope) {
10049
+ return undo(`the approved words landed at scope ${JSON.stringify(landed.scope)}, not ${JSON.stringify(old.scope)}`);
10050
+ }
10051
+ // The memory landed; its proposal must read approved. A write that landed before estate recorded the
10052
+ // approval leaves it pending: approve it again (the same memory), and undo the edit if that does not settle it.
10053
+ let pending;
10054
+ try {
10055
+ pending = (await pendingMemoryProposals()).some((q) => q.id === pid);
10056
+ if (pending) {
10057
+ await approve();
10058
+ pending = (await pendingMemoryProposals()).some((q) => q.id === pid);
10059
+ }
10060
+ }
10061
+ catch (err) {
10062
+ return undo(`the approval of the new words could not be confirmed (${message(err)})`);
10063
+ }
10064
+ if (pending)
10065
+ return undo('the approval of the new words stayed pending');
10066
+ return { id: newId };
10067
+ };
9857
10068
  try {
9858
10069
  // 1. The memory as it is: its tier, scope and facets ride onto the replacement.
9859
10070
  let before;
@@ -9883,48 +10094,59 @@ runtime = {}) {
9883
10094
  }
9884
10095
  return upstream('checking that the store can erase one memory failed; nothing changed', err);
9885
10096
  }
9886
- // 3. The new words, as a new memory in the old one's place.
9887
- const captureArgs = { content, scope: old.scope, facets: old.facets };
9888
- if (old.tier !== '') {
9889
- captureArgs['tier'] = old.tier;
9890
- const kind = KIND_FOR_TIER[old.tier];
9891
- if (kind !== undefined)
9892
- captureArgs['kind'] = kind;
9893
- }
9894
- const beforeIds = new Set(before.map((m) => m.id));
10097
+ // 3. The new words, as a new memory in the old one's place. An approved learning (estate's
10098
+ // `proposal:` id, the only mark run-learnings recall admits: crew#1546) is replaced through
10099
+ // the approval queue, so the replacement carries the mark too; a capture would mint a bare id
10100
+ // and the edited learning would silently stop reaching briefs. Anything else is captured.
9895
10101
  let newId = null;
9896
- let captureErr = null;
9897
- try {
9898
- const captured = await estateTool('memory.capture', captureArgs);
9899
- const id = typeof captured === 'object' && captured !== null ? captured['memory_id'] : undefined;
9900
- if (typeof id === 'string' && id !== '')
9901
- newId = id;
9902
- else
9903
- captureErr = new EstateMcpError('memory.capture returned no memory_id');
9904
- }
9905
- catch (err) {
9906
- captureErr = err;
10102
+ if (memoryId.startsWith(APPROVED_MEMORY_PREFIX)) {
10103
+ const placed = await reapproveMemory(old, content, new Set(before.map((m) => m.id)));
10104
+ if ('error' in placed)
10105
+ return reply.code(placed.status).send({ error: placed.error });
10106
+ newId = placed.id;
9907
10107
  }
9908
- if (newId === null) {
9909
- // The capture may still have written (a lost answer): look before saying nothing changed.
9910
- let now;
10108
+ else {
10109
+ const captureArgs = { content, scope: old.scope, facets: old.facets };
10110
+ if (old.tier !== '') {
10111
+ captureArgs['tier'] = old.tier;
10112
+ const kind = KIND_FOR_TIER[old.tier];
10113
+ if (kind !== undefined)
10114
+ captureArgs['kind'] = kind;
10115
+ }
10116
+ const beforeIds = new Set(before.map((m) => m.id));
10117
+ let captureErr = null;
9911
10118
  try {
9912
- now = await listAll();
10119
+ const captured = await estateTool('memory.capture', captureArgs);
10120
+ const id = typeof captured === 'object' && captured !== null ? captured['memory_id'] : undefined;
10121
+ if (typeof id === 'string' && id !== '')
10122
+ newId = id;
10123
+ else
10124
+ captureErr = new EstateMcpError('memory.capture returned no memory_id');
9913
10125
  }
9914
10126
  catch (err) {
9915
- return reply.code(502).send({
9916
- error: `writing the new words did not answer as expected (${message(captureErr)}) and the store could not be re-read (${message(err)}); a copy of the new words may exist beside ${memoryId}`,
9917
- });
10127
+ captureErr = err;
9918
10128
  }
9919
- const copies = now.filter((m) => !beforeIds.has(m.id) && m.content.trim() === content && m.scope === old.scope);
9920
- if (copies.length !== 1) {
9921
- return reply.code(502).send({
9922
- error: copies.length === 0
9923
- ? `writing the new words failed (${message(captureErr)}); nothing changed`
9924
- : `writing the new words did not answer as expected (${message(captureErr)}); ${copies.length} copies of them now exist beside ${memoryId}: ${copies.map((m) => m.id).join(', ')}`,
9925
- });
10129
+ if (newId === null) {
10130
+ // The capture may still have written (a lost answer): look before saying nothing changed.
10131
+ let now;
10132
+ try {
10133
+ now = await listAll();
10134
+ }
10135
+ catch (err) {
10136
+ return reply.code(502).send({
10137
+ error: `writing the new words did not answer as expected (${message(captureErr)}) and the store could not be re-read (${message(err)}); a copy of the new words may exist beside ${memoryId}`,
10138
+ });
10139
+ }
10140
+ const copies = now.filter((m) => !beforeIds.has(m.id) && m.content.trim() === content && m.scope === old.scope);
10141
+ if (copies.length !== 1) {
10142
+ return reply.code(502).send({
10143
+ error: copies.length === 0
10144
+ ? `writing the new words failed (${message(captureErr)}); nothing changed`
10145
+ : `writing the new words did not answer as expected (${message(captureErr)}); ${copies.length} copies of them now exist beside ${memoryId}: ${copies.map((m) => m.id).join(', ')}`,
10146
+ });
10147
+ }
10148
+ newId = copies[0].id;
9926
10149
  }
9927
- newId = copies[0].id;
9928
10150
  }
9929
10151
  // 4. The old memory out.
9930
10152
  let eraseErr = null;
@@ -10206,20 +10428,7 @@ runtime = {}) {
10206
10428
  // per request, and one background `seat-image build` at a time.
10207
10429
  const coreExe = () => process.env['WICKED_CORE_EXE'] || null;
10208
10430
  const seatImageRebuilder = runtime.seatImageRebuilder ?? new SeatImageRebuilder(coreExe);
10209
- const seatImageStatus = runtime.seatImageStatus ??
10210
- (async () => {
10211
- const exe = coreExe();
10212
- if (exe === null)
10213
- throw new Error('WICKED_CORE_EXE is not set');
10214
- try {
10215
- const out = await execCapped(exe, ['seat-image', 'status', '--json'], { timeout: PROBE_TIMEOUT_MS });
10216
- return parseSeatImageStatus(out.stdout);
10217
- }
10218
- catch (err) {
10219
- const e = err;
10220
- throw new Error(loginDetail(typeof e.stderr === 'string' && e.stderr !== '' ? e.stderr : (e.message ?? 'failed')));
10221
- }
10222
- });
10431
+ const seatImageStatus = runtime.seatImageStatus ?? seatImageStatusVia(coreExe);
10223
10432
  // The roster's seats (on the container floor every seat runs in an image); `null` when unreadable.
10224
10433
  const rosterSeatsNow = () => {
10225
10434
  try {
@@ -10390,6 +10599,11 @@ runtime = {}) {
10390
10599
  rebuild: () => seatImageRebuilder.current(),
10391
10600
  }),
10392
10601
  clusterP.then((rows) => rows.cluster),
10602
+ // crew#1527: whether a pull request can be opened — the setup steps' answer, through the same bounded reader.
10603
+ (async () => {
10604
+ const started = Date.now();
10605
+ return deliveryRow(await readDeliveryReadiness(() => Promise.resolve(adapter.getSettings())), started, infraRow);
10606
+ })(),
10393
10607
  ]);
10394
10608
  const [views, settings, openGates, diag, ping, rules, gatesByYou, infraProbed, reposRead] = await Promise.all([
10395
10609
  viewsP, settingsP, gatesP, diagP, pingP, rulesP, gatesByYouP, infraP, reposP,
@@ -10528,6 +10742,7 @@ runtime = {}) {
10528
10742
  infraProbed[8],
10529
10743
  infraProbed[7],
10530
10744
  reposRow(reposRead),
10745
+ infraProbed[9],
10531
10746
  infraProbed[6],
10532
10747
  loadRow(),
10533
10748
  ];