@abelxiaoxing/cadence 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,9 @@
1
1
  import { IMAGE_LIMITS, IMAGE_TYPES } from "../../image-content.mjs";
2
- import { decodeModelRetry, type ModelRetry } from "../../worker-public.mjs";
2
+ import {
3
+ decodeModelRetry,
4
+ knowledgeFields,
5
+ type ModelRetry,
6
+ } from "../../worker-public.mjs";
3
7
  /** Finite, authenticated workbench API. Ordinary chat is not task admission. */
4
8
  import {
5
9
  bool,
@@ -48,6 +52,18 @@ import {
48
52
  type WorkflowRun,
49
53
  } from "./workflow.ts";
50
54
 
55
+ /** Response header on an authenticated workbench project observation. Separate
56
+ * from the closed JSON body (owner status/epoch). An associated project may
57
+ * request a session when running; association alone is not an attachment. */
58
+ export const PROJECT_ASSOCIATION_HEADER = "x-cadence-project-association";
59
+ export function decodeProjectAssociation(value: unknown) {
60
+ // Older gateways do not report this fact. Missing evidence is neither a
61
+ // successful attachment nor proof that an owner is independent.
62
+ return value === null || value === undefined
63
+ ? "unknown"
64
+ : oneOf(value, ["associated", "unassociated"]);
65
+ }
66
+
51
67
  export interface CadenceConversation {
52
68
  design?: DesignDraft;
53
69
  id: string;
@@ -105,17 +121,19 @@ export type KnowledgeLookup =
105
121
  export function decodeKnowledgeLookup(v: unknown): KnowledgeLookup {
106
122
  if (Object.hasOwn(v ?? {}, "checkout")) {
107
123
  const { checkout } = closed(v, ["checkout"]);
108
- return { checkout: list(checkout, 8, (path) => text(path, 1024, true)) };
124
+ return { checkout: knowledgeFields.checkout(checkout) };
109
125
  }
110
126
  if (Object.hasOwn(v ?? {}, "investigation"))
111
127
  return {
112
- investigation: decodeId(closed(v, ["investigation"]).investigation),
128
+ investigation: knowledgeFields.investigation(
129
+ closed(v, ["investigation"]).investigation,
130
+ ),
113
131
  };
114
132
  if (Object.hasOwn(v ?? {}, "match")) {
115
133
  const raw = closed(v, ["path", "match"]);
116
134
  return {
117
- path: text(raw.path, 1024, true),
118
- match: text(raw.match, 256, true),
135
+ path: knowledgeFields.path(raw.path),
136
+ match: knowledgeFields.match(raw.match),
119
137
  };
120
138
  }
121
139
  const raw = closed(v, [
@@ -123,10 +141,10 @@ export function decodeKnowledgeLookup(v: unknown): KnowledgeLookup {
123
141
  ...(Object.hasOwn(v ?? {}, "section") ? ["section"] : []),
124
142
  ]);
125
143
  return {
126
- path: text(raw.path, 1024, true),
144
+ path: knowledgeFields.path(raw.path),
127
145
  ...(raw.section === undefined
128
146
  ? {}
129
- : { section: text(raw.section, 512, true) }),
147
+ : { section: knowledgeFields.section(raw.section) }),
130
148
  };
131
149
  }
132
150
  export type WorkbenchRead =
@@ -366,14 +384,21 @@ export type WorkbenchCommand =
366
384
  archived: boolean;
367
385
  }
368
386
  | { kind: "open-project"; commandId: string; path: string; epoch: string };
369
- export type ChatStatus =
370
- | "queued"
371
- | "running"
372
- | "completed"
373
- | "failed"
374
- | "canceled"
375
- | "timeout"
376
- | "unknown";
387
+ /** A workflow transcript retains its own lifecycle; only an ordinary Send
388
+ * starts in preparation rather than queued. */
389
+ const workflowTurnStatuses = [
390
+ "queued",
391
+ "running",
392
+ "completed",
393
+ "failed",
394
+ "canceled",
395
+ "timeout",
396
+ "unknown",
397
+ ] as const;
398
+ export const CHAT_STATUSES = ["starting", ...workflowTurnStatuses] as const;
399
+ export type ChatStatus = (typeof CHAT_STATUSES)[number];
400
+ export const isLiveChatStatus = (status: ChatStatus) =>
401
+ status === "starting" || status === "queued" || status === "running";
377
402
  export interface ChatImage {
378
403
  live?: true;
379
404
  /** Pi entry ID, or the admitted command ID until Pi flushes its user entry. */
@@ -418,7 +443,7 @@ export interface ChatTurn {
418
443
  retry?: ModelRetry;
419
444
  id: string;
420
445
  epoch: string;
421
- status: ChatStatus;
446
+ status: (typeof workflowTurnStatuses)[number];
422
447
  items: ChatItem[];
423
448
  notice: string;
424
449
  /** Immutable full-transcript pages; items above are only the latest preview. */
@@ -752,15 +777,6 @@ export interface WorkbenchPort {
752
777
  },
753
778
  ): WorkbenchResult | Promise<WorkbenchResult>;
754
779
  }
755
- const statuses = [
756
- "queued",
757
- "running",
758
- "completed",
759
- "failed",
760
- "canceled",
761
- "timeout",
762
- "unknown",
763
- ] as const;
764
780
  export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
765
781
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
766
782
  switch (kind) {
@@ -1257,7 +1273,7 @@ export function decodeChatTurn(v: unknown): ChatTurn {
1257
1273
  ...(o.retry === undefined ? {} : { retry: decodeModelRetry(o.retry) }),
1258
1274
  id: decodeId(o.id),
1259
1275
  epoch: decodeId(o.epoch),
1260
- status: oneOf(o.status, statuses),
1276
+ status: oneOf(o.status, workflowTurnStatuses),
1261
1277
  notice: text(o.notice, 1024),
1262
1278
  ...(transcript
1263
1279
  ? { transcript: { pages: integer(transcript.pages, 0) } }
@@ -1441,7 +1457,7 @@ function decodeChatTurnHeader(v: unknown): ChatTurnHeader {
1441
1457
  ? {}
1442
1458
  : { parent: nullable(o.parent, decodeEntryId) }),
1443
1459
  at: integer(o.at, 0),
1444
- status: oneOf(o.status, statuses),
1460
+ status: oneOf(o.status, CHAT_STATUSES),
1445
1461
  notice: text(o.notice, 1024),
1446
1462
  omitted: {
1447
1463
  thinking: bool(omitted.thinking),
@@ -1473,7 +1489,7 @@ export function decodeChatSummary(v: unknown): ChatSummary {
1473
1489
  id: decodeSessionId(o.id),
1474
1490
  title: text(o.title, 512, true),
1475
1491
  leaf: nullable(o.leaf, decodeEntryId),
1476
- status: oneOf(o.status, statuses),
1492
+ status: oneOf(o.status, CHAT_STATUSES),
1477
1493
  updatedAt: integer(o.updatedAt, 0),
1478
1494
  origin: oneOf(o.origin, ["terminal", "webui"]),
1479
1495
  ...(has("cadence") ? { cadence: bool(o.cadence) } : {}),
@@ -1493,7 +1509,7 @@ function decodeChatAttempt(v: unknown): ChatAttempt {
1493
1509
  return {
1494
1510
  commandId: decodeId(o.commandId),
1495
1511
  text: text(o.text, 16 * 1024),
1496
- status: oneOf(o.status, statuses),
1512
+ status: oneOf(o.status, CHAT_STATUSES),
1497
1513
  notice: text(o.notice, 1024),
1498
1514
  };
1499
1515
  }
@@ -324,7 +324,7 @@ export type WorkflowResponse =
324
324
  /** A plan or an investigation request that its author can correct: the message
325
325
  * names the field, what it holds and what is accepted there. */
326
326
  export class WorkflowInputError extends Error {}
327
- function issue(path: string, problem: string): never {
327
+ export function issue(path: string, problem: string): never {
328
328
  throw new WorkflowInputError(`${path}: ${problem}`);
329
329
  }
330
330
  const quoted = (value: string) => JSON.stringify(clipUnits(value, 80));
@@ -346,7 +346,7 @@ function at<T>(path: string, read: () => T): T {
346
346
  );
347
347
  }
348
348
  }
349
- function words(
349
+ export function words(
350
350
  path: string,
351
351
  v: unknown,
352
352
  maximum: number,
@@ -360,7 +360,7 @@ function words(
360
360
  return issue(path, `is ${bytes} bytes; at most ${maximum}`);
361
361
  return at(path, () => text(v, maximum, nonempty));
362
362
  }
363
- function entries<T>(
363
+ export function entries<T>(
364
364
  path: string,
365
365
  v: unknown,
366
366
  maximum: number,
@@ -375,7 +375,7 @@ function entries<T>(
375
375
  );
376
376
  }
377
377
  /** A closed object: every required field present, nothing unknown. */
378
- function fields(
378
+ export function fields(
379
379
  path: string,
380
380
  v: unknown,
381
381
  required: readonly string[],
@@ -1098,9 +1098,37 @@ export function readableDelivery(binding?: DeliveryBinding): string {
1098
1098
  const t = binding.target;
1099
1099
  return `Target: ${t.branch} @ ${t.head}\nTarget checkout: ${t.checkoutRoot}\nExecution: new cadence/<goal>-<run-id> branch and one stable isolated worktree after approval. Assignments that can run side by side each work in a temporary worktree of their own beside it; the service commits that work and picks it onto the candidate. Independent conversations may use separate candidates concurrently.\nAcceptance: checks and automatic Agent review of the exact candidate. A verified, non-overlapping sibling delivery may be merged into the isolated candidate, followed by fresh checks and review.\nDelivery: serialized fast-forward only into the bound target at its approved, verified-sibling or own last confirmed baseline. Keep the task branch; remove only owned worktrees without any residue, including ignored files. No source/profile/dependency copying, push or deployment.`;
1100
1100
  }
1101
- export function readableDeliveryRun(d?: DeliveryObservation): string {
1101
+ /** Display projection only. A missing seal is not proof of missing edits.
1102
+ * In an interrupted run pending facts may simply not have been recorded. */
1103
+ export function deliveryLabels(
1104
+ d: DeliveryObservation,
1105
+ status: WorkflowRun["status"],
1106
+ ) {
1107
+ const finished = status !== "running" && status !== "queued";
1108
+ const settled = finished && status !== "unknown";
1109
+ const beforeWorkspace =
1110
+ settled && d.workspace === null && d.preparation === "pending";
1111
+ const pending = (value: string) =>
1112
+ value !== "pending" || !finished
1113
+ ? value
1114
+ : settled
1115
+ ? "Not executed"
1116
+ : "Not recorded";
1117
+ return {
1118
+ preparation:
1119
+ d.preparation === "pending" && finished && !beforeWorkspace
1120
+ ? "Not recorded"
1121
+ : pending(d.preparation),
1122
+ missingCandidate: beforeWorkspace ? "Not executed" : "Not recorded",
1123
+ integration: pending(d.integration.status),
1124
+ cleanup: pending(d.cleanup.status),
1125
+ } as const;
1126
+ }
1127
+ export function readableDeliveryRun(run: WorkflowRun): string {
1128
+ const d = run.delivery;
1102
1129
  if (!d) return "";
1103
- return `Task branch: ${d.taskBranch}\nWorktree: ${d.worktreeRoot}\nTarget: ${d.binding.target.branch} @ ${d.binding.target.head}\nPreparation: ${d.preparation}\nCandidate: ${d.candidate ?? "not recorded"}\nAcceptance: ${d.acceptance ? `checks + automatic Agent review of ${d.acceptance.candidate}` : "not recorded"}\nIntegration: ${d.integration.status}${d.integration.after ? ` @ ${d.integration.after}` : ""}${d.integration.reason ? ` — ${d.integration.reason}` : ""}\nPost-merge checks: ${d.postChecks}\nWorktree cleanup: ${d.cleanup.status}${d.cleanup.reason ? ` — ${d.cleanup.reason}` : ""}\nPolicy: keep the task branch; no push or deployment.`;
1130
+ const labels = deliveryLabels(d, run.status);
1131
+ return `Task branch: ${d.taskBranch}\nWorktree: ${d.worktreeRoot}\nTarget: ${d.binding.target.branch} @ ${d.binding.target.head}\nPreparation: ${labels.preparation}\nCandidate: ${d.candidate ?? labels.missingCandidate}\nAcceptance: ${d.acceptance ? `checks + automatic Agent review of ${d.acceptance.candidate}` : labels.missingCandidate}\nIntegration: ${labels.integration}${d.integration.after ? ` @ ${d.integration.after}` : ""}${d.integration.reason ? ` — ${d.integration.reason}` : ""}\nPost-merge checks: ${d.postChecks}\nWorktree cleanup: ${labels.cleanup}${d.cleanup.reason ? ` — ${d.cleanup.reason}` : ""}\nPolicy: keep the task branch; no push or deployment.`;
1104
1132
  }
1105
1133
  export function decodeWorkflowProposal(v: unknown): WorkflowProposal {
1106
1134
  const modern =
@@ -46,7 +46,7 @@ const CHUNK = 1024 * 1024;
46
46
  /** A refusal with an explanation; the public code stays one of ERROR_CODES. */
47
47
  export class WorkflowRefusal extends ContractError {
48
48
  constructor(
49
- code: "conflict" | "stale" | "forbidden" | "invalid",
49
+ code: "conflict" | "stale" | "forbidden" | "invalid" | "unavailable",
50
50
  readonly detail: string,
51
51
  ) {
52
52
  super(code);
@@ -668,20 +668,40 @@ export function workflowObservation(
668
668
  identity: hash(JSON.stringify({ head, branch, contents })),
669
669
  };
670
670
  }
671
+ /** Observe the target checkout, never the isolated candidate. Keep both Git
672
+ * answers even when one is unavailable. No later reread supplies failure facts. */
673
+ export async function assertTargetPosition(
674
+ cwd: string,
675
+ expected: { head: string; branch: string },
676
+ stage: string,
677
+ ): Promise<void> {
678
+ const [ref, oid] = await Promise.all([
679
+ gitRun(cwd, ["symbolic-ref", "--quiet", "HEAD"]).catch(() => null),
680
+ gitRun(cwd, ["rev-parse", "--verify", "HEAD"]).catch(() => null),
681
+ ]);
682
+ const branch =
683
+ ref?.code === 0
684
+ ? ref.stdout.trim()
685
+ : ref?.code === 1
686
+ ? "(detached HEAD)"
687
+ : null;
688
+ const head = oid?.code === 0 ? oid.stdout.trim() : null;
689
+ if (head === expected.head && branch === expected.branch) return;
690
+ const unreadable = !head || !branch;
691
+ throw new WorkflowRefusal(
692
+ unreadable ? "unavailable" : "stale",
693
+ `${stage}: target ${unreadable ? "identity could not be verified" : "position changed"}; expected ${expected.branch} at ${expected.head}, observed ${branch || "(unreadable ref)"} at ${head || "(unreadable HEAD)"}. Refused to proceed; this check made no merge.`,
694
+ );
695
+ }
671
696
  /** Only what a safe fast-forward needs: the same branch and HEAD, and no dirty
672
697
  * declared/generated target. Unrelated user changes are left to `merge --ff-only`. */
673
698
  export async function assertTarget(
674
699
  cwd: string,
675
700
  expected: { head: string; branch: string },
676
701
  scope: readonly string[],
702
+ stage: string,
677
703
  ): Promise<void> {
678
- const head = await gitHead(cwd);
679
- const branch = (await gitText(cwd, ["symbolic-ref", "HEAD"])).trim();
680
- if (head !== expected.head || branch !== expected.branch)
681
- throw new WorkflowRefusal(
682
- "stale",
683
- `The target branch changed during the run (expected ${expected.branch} at ${expected.head.slice(0, 12)}); nothing was integrated.`,
684
- );
704
+ await assertTargetPosition(cwd, expected, stage);
685
705
  assertVisibleIndex(
686
706
  overlapping(scope, indexHidden(await gitText(cwd, INDEX_FLAGS))),
687
707
  );
@@ -347,6 +347,13 @@ function decodeId(v) {
347
347
  invalid();
348
348
  return s;
349
349
  }
350
+ var knowledgeFields = Object.freeze({
351
+ checkout: (v) => list(v, 8, (entry) => text(entry, 1024, true)),
352
+ path: (v) => text(v, 1024, true),
353
+ section: (v) => text(v, 512, true),
354
+ match: (v) => text(v, 256, true),
355
+ investigation: decodeId
356
+ });
350
357
  function decodeHash(v) {
351
358
  const s = text(v, 64);
352
359
  if (!/^[0-9a-f]{64}$/.test(s))
@@ -2817,6 +2824,9 @@ function unitEnvironment(text2) {
2817
2824
  }
2818
2825
  return out;
2819
2826
  }
2827
+ function generatedUnit(s) {
2828
+ return readGenerated(unitPath(s), MARKER);
2829
+ }
2820
2830
  function directory(path2) {
2821
2831
  try {
2822
2832
  return isAbsolute3(path2) && statSync2(path2).isDirectory();
@@ -3923,6 +3933,69 @@ import {
3923
3933
  } from "node:crypto";
3924
3934
  import { dirname as dirname7, isAbsolute as isAbsolute5, join as join7 } from "node:path";
3925
3935
 
3936
+ // src/image-content.mjs
3937
+ var IMAGE_LIMITS = Object.freeze({
3938
+ chunkChars: 256 * 1024,
3939
+ idleMs: 10 * 60 * 1000
3940
+ });
3941
+ var IMAGE_TYPES = Object.freeze([
3942
+ "image/png",
3943
+ "image/jpeg",
3944
+ "image/webp"
3945
+ ]);
3946
+
3947
+ // src/service/contracts/workflow.ts
3948
+ var WORKFLOW_LIMITS = {
3949
+ tasks: 16,
3950
+ route: 48,
3951
+ questions: 32,
3952
+ checks: 16,
3953
+ bytes: 256 * 1024,
3954
+ context: 32768,
3955
+ reason: 1024,
3956
+ historyScanEntries: 200,
3957
+ historyPage: 20,
3958
+ historyScans: 16,
3959
+ historyIdleMs: 120000
3960
+ };
3961
+ // src/service/contracts/workbench.ts
3962
+ var FILE_PART_BYTES = 192 * 1024;
3963
+ var FILE_DOWNLOAD_BYTES = 64 * 1024 * 1024;
3964
+ var CONVERSATION_SEND_BYTES = 16 * 1024;
3965
+ var UNDELIVERED_TEXT_BYTES = 2 * CONVERSATION_SEND_BYTES;
3966
+ var workflowTurnStatuses = [
3967
+ "queued",
3968
+ "running",
3969
+ "completed",
3970
+ "failed",
3971
+ "canceled",
3972
+ "timeout",
3973
+ "unknown"
3974
+ ];
3975
+ var CHAT_STATUSES = ["starting", ...workflowTurnStatuses];
3976
+ var STEP_TEXT_BYTES = 16 * 1024;
3977
+
3978
+ // src/service-wire.ts
3979
+ var pageReaders = [
3980
+ "tasks",
3981
+ "runs",
3982
+ "messages",
3983
+ "tools",
3984
+ "contents",
3985
+ "events",
3986
+ "checks",
3987
+ "changes",
3988
+ "reviews"
3989
+ ];
3990
+ var HISTORY_CSRF_HEADER = "x-cadence-history-csrf";
3991
+ var retainedReaders = [
3992
+ ...pageReaders,
3993
+ "entity",
3994
+ "graph",
3995
+ "detail",
3996
+ "search"
3997
+ ];
3998
+
3926
3999
  // src/service/config.ts
3927
4000
  import { isIP } from "node:net";
3928
4001
  function decodeHttpPolicy(value) {
@@ -4238,18 +4311,41 @@ function readExternal(path2) {
4238
4311
  class HttpAuthentication {
4239
4312
  material;
4240
4313
  epoch;
4314
+ workspaceId;
4241
4315
  localCapability;
4242
- csrf = randomUUID4();
4316
+ executionCsrf = randomUUID4();
4317
+ get csrf() {
4318
+ return this.executionCsrf;
4319
+ }
4320
+ history;
4243
4321
  cookieName;
4244
4322
  constructor(material, epoch, workspaceId, localCapability) {
4245
4323
  this.material = material;
4246
4324
  this.epoch = epoch;
4325
+ this.workspaceId = workspaceId;
4247
4326
  this.localCapability = localCapability;
4248
4327
  decodeId(epoch);
4249
4328
  decodeId(workspaceId);
4250
4329
  if (!/^[A-Za-z0-9_-]{43}$/.test(localCapability))
4251
4330
  throw new ContractError("invalid");
4252
4331
  this.cookieName = `cadence_${workspaceId.replaceAll("-", "")}`;
4332
+ material.onRevoke(() => {
4333
+ this.history = undefined;
4334
+ this.executionCsrf = randomUUID4();
4335
+ });
4336
+ }
4337
+ historyChallenge(workspace) {
4338
+ if (workspace.workspaceId !== this.workspaceId || workspace.epoch !== this.epoch)
4339
+ throw new ContractError("stale");
4340
+ if (this.history?.storeId !== workspace.storeId)
4341
+ this.history = {
4342
+ storeId: decodeId(workspace.storeId),
4343
+ csrf: randomUUID4()
4344
+ };
4345
+ return this.history.csrf;
4346
+ }
4347
+ get historyStore() {
4348
+ return this.history?.storeId;
4253
4349
  }
4254
4350
  bootstrap(value, boundary) {
4255
4351
  this.material.assertCurrent();
@@ -4282,14 +4378,14 @@ class HttpAuthentication {
4282
4378
  }
4283
4379
  return false;
4284
4380
  }
4285
- authenticate(boundary, attachmentId, mutation = false, websocket = false) {
4381
+ authenticate(boundary, attachmentId, post = false, websocket = false) {
4286
4382
  this.material.assertCurrent();
4287
4383
  if (!this.material.available)
4288
4384
  throw new ContractError("quarantine");
4289
4385
  const h = boundary.headers;
4290
4386
  const local = h.get("x-cadence-local");
4291
4387
  if (local !== undefined) {
4292
- if (!boundary.local || h.has("cookie") || [...h.keys()].some((name) => name.startsWith("sec-fetch-") && (name !== "sec-fetch-mode" || h.get(name) !== "cors")) || !sameSecret(local, this.localCapability))
4388
+ if (post === "retained-history" || !boundary.local || h.has("cookie") || [...h.keys()].some((name) => name.startsWith("sec-fetch-") && (name !== "sec-fetch-mode" || h.get(name) !== "cors")) || !sameSecret(local, this.localCapability))
4293
4389
  throw new ContractError("forbidden");
4294
4390
  } else {
4295
4391
  if (h.has("authorization") || h.has("x-cadence-token"))
@@ -4298,10 +4394,14 @@ class HttpAuthentication {
4298
4394
  throw new ContractError("unauthenticated");
4299
4395
  if (h.has("sec-fetch-site") && !["same-origin", "none"].includes(h.get("sec-fetch-site") ?? ""))
4300
4396
  throw new ContractError("forbidden");
4301
- if ((mutation || websocket) && h.get("origin") !== boundary.origin)
4397
+ if ((post || websocket) && h.get("origin") !== boundary.origin)
4302
4398
  throw new ContractError("forbidden");
4303
- if (mutation && h.get("x-cadence-csrf") !== this.csrf)
4399
+ if (post === "retained-history") {
4400
+ if (!this.history || h.get(HISTORY_CSRF_HEADER) !== this.history.csrf || h.has("x-cadence-attachment") || h.has("x-cadence-csrf"))
4401
+ throw new ContractError("forbidden");
4402
+ } else if (post && h.get("x-cadence-csrf") !== this.csrf) {
4304
4403
  throw new ContractError("forbidden");
4404
+ }
4305
4405
  }
4306
4406
  return {
4307
4407
  attachmentId: decodeId(attachmentId),
@@ -4668,28 +4768,28 @@ function object2(value, at) {
4668
4768
  return fail(at, "must be a plain object without reserved keys");
4669
4769
  }
4670
4770
  }
4671
- function shape(fields2, required = [], retired = {}) {
4771
+ function shape(fields3, required = [], retired = {}) {
4672
4772
  const check = (value, at) => {
4673
4773
  const o = object2(value, at);
4674
4774
  for (const key of Object.keys(o))
4675
- if (!Object.hasOwn(fields2, key))
4775
+ if (!Object.hasOwn(fields3, key))
4676
4776
  fail(child(at, key), Object.hasOwn(retired, key) ? retired[key] : UNSUPPORTED);
4677
4777
  for (const key of required)
4678
4778
  if (o[key] === undefined)
4679
4779
  fail(child(at, key), "is required");
4680
- for (const [key, field] of Object.entries(fields2))
4780
+ for (const [key, field] of Object.entries(fields3))
4681
4781
  if (o[key] !== undefined)
4682
4782
  field(o[key], child(at, key));
4683
4783
  };
4684
- check.fields = fields2;
4784
+ check.fields = fields3;
4685
4785
  return check;
4686
4786
  }
4687
- function record(entries) {
4787
+ function record(entries2) {
4688
4788
  const check = (value, at) => {
4689
4789
  for (const [key, entry] of Object.entries(object2(value, at)))
4690
- entries(entry, child(at, key));
4790
+ entries2(entry, child(at, key));
4691
4791
  };
4692
- check.entries = entries;
4792
+ check.entries = entries2;
4693
4793
  return check;
4694
4794
  }
4695
4795
  function list2(items, maximum = ENTRY_LIMIT) {
@@ -5123,7 +5223,7 @@ function decodeRecoveryEvent(value) {
5123
5223
  archive
5124
5224
  };
5125
5225
  }
5126
- function entries(path2, maximum = 4096) {
5226
+ function entries2(path2, maximum = 4096) {
5127
5227
  const out = [];
5128
5228
  let dir;
5129
5229
  try {
@@ -5151,7 +5251,7 @@ function size(path2, limit = { left: 1e5 }) {
5151
5251
  if (!st.isDirectory())
5152
5252
  return st.size;
5153
5253
  let total = 0;
5154
- for (const name of entries(path2, 1e5))
5254
+ for (const name of entries2(path2, 1e5))
5155
5255
  total += size(join10(path2, name), limit);
5156
5256
  return total;
5157
5257
  }
@@ -5211,7 +5311,7 @@ class RecoveryLog {
5211
5311
  return value;
5212
5312
  }
5213
5313
  latestFile() {
5214
- for (const name of entries(this.logDirectory).reverse()) {
5314
+ for (const name of entries2(this.logDirectory).reverse()) {
5215
5315
  if (!/^[0-9]{13}-[0-9a-f-]{36}\.json$/.test(name))
5216
5316
  continue;
5217
5317
  const path2 = join10(this.logDirectory, name);
@@ -5228,7 +5328,7 @@ class RecoveryLog {
5228
5328
  }
5229
5329
  events(limit = 20) {
5230
5330
  const out = [];
5231
- for (const name of entries(this.logDirectory).reverse()) {
5331
+ for (const name of entries2(this.logDirectory).reverse()) {
5232
5332
  if (out.length >= limit)
5233
5333
  break;
5234
5334
  if (!/^[0-9]{13}-[0-9a-f-]{36}\.json$/.test(name))
@@ -5242,10 +5342,10 @@ class RecoveryLog {
5242
5342
  return out;
5243
5343
  }
5244
5344
  prune(now = Date.now()) {
5245
- const names2 = entries(this.logDirectory);
5345
+ const names2 = entries2(this.logDirectory);
5246
5346
  for (const name of names2.slice(0, Math.max(0, names2.length - RECOVERY_EVENTS)))
5247
5347
  rmSync2(join10(this.logDirectory, name), { force: true });
5248
- const archived = entries(this.archiveDirectory).filter((name) => /^[0-9]{13}-[0-9a-f-]{36}$/.test(name));
5348
+ const archived = entries2(this.archiveDirectory).filter((name) => /^[0-9]{13}-[0-9a-f-]{36}$/.test(name));
5249
5349
  const kept = [];
5250
5350
  for (const name of archived) {
5251
5351
  const path2 = join10(this.archiveDirectory, name);
@@ -5278,7 +5378,7 @@ class RecoveryLog {
5278
5378
  }));
5279
5379
  }
5280
5380
  usage() {
5281
- const names2 = entries(this.archiveDirectory);
5381
+ const names2 = entries2(this.archiveDirectory);
5282
5382
  return {
5283
5383
  entries: names2.length,
5284
5384
  bytes: names2.reduce((sum, name) => sum + size(join10(this.archiveDirectory, name)), 0)
@@ -5286,7 +5386,7 @@ class RecoveryLog {
5286
5386
  }
5287
5387
  }
5288
5388
  function strayTemporaries(directory2) {
5289
- return entries(directory2).filter((name) => /^pending-[0-9a-f-]{36}\.json$/.test(name)).map((name) => join10(directory2, name));
5389
+ return entries2(directory2).filter((name) => /^pending-[0-9a-f-]{36}\.json$/.test(name)).map((name) => join10(directory2, name));
5290
5390
  }
5291
5391
 
5292
5392
  // src/service/runtime.ts
@@ -5503,7 +5603,7 @@ function describePiProblem(problem) {
5503
5603
  }
5504
5604
  function decodePiProblem(value) {
5505
5605
  const o = closed(value, ["file", "check", "field", "reason"]);
5506
- const words = (v) => {
5606
+ const words2 = (v) => {
5507
5607
  const s = text(v, 512, true);
5508
5608
  if (/[\p{Cc}\p{Cf}]/u.test(s))
5509
5609
  throw new ContractError("invalid");
@@ -5512,8 +5612,8 @@ function decodePiProblem(value) {
5512
5612
  return {
5513
5613
  file: oneOf(o.file, Object.keys(PI_SOURCE_STAGES)),
5514
5614
  check: oneOf(o.check, ["file", "json", "schema", "sdk"]),
5515
- field: o.field === null ? null : words(o.field),
5516
- reason: words(o.reason)
5615
+ field: o.field === null ? null : words2(o.field),
5616
+ reason: words2(o.reason)
5517
5617
  };
5518
5618
  }
5519
5619
  function decodeStartupReport(value) {
@@ -6161,14 +6261,14 @@ class RegistryHealer {
6161
6261
  archive.keep(this.path(name));
6162
6262
  }
6163
6263
  }
6164
- const entries2 = [];
6264
+ const entries3 = [];
6165
6265
  for (const row of liveReservations(this.c))
6166
- entries2.push(row);
6266
+ entries3.push(row);
6167
6267
  this.c.files.create(this.path("format.json"), encoded({
6168
6268
  schema: "cadence-service-registry-format/1",
6169
6269
  stateHome: this.c.stateHome
6170
6270
  }));
6171
- this.c.files.create(this.path("roots.json"), encoded({ schema: "cadence-service-registry/1", entries: entries2 }), 1024 * 1024);
6271
+ this.c.files.create(this.path("roots.json"), encoded({ schema: "cadence-service-registry/1", entries: entries3 }), 1024 * 1024);
6172
6272
  } finally {
6173
6273
  this.c.files.remove(lockPath, lock);
6174
6274
  }
@@ -7942,10 +8042,10 @@ async function serviceStatus(c, diagnose = false) {
7942
8042
  };
7943
8043
  }
7944
8044
  }
7945
- async function stopService(c) {
8045
+ async function stopService(c, confirmedWork) {
7946
8046
  let epoch;
7947
8047
  try {
7948
- const reply = closed(await nativeCall(c, "stop"), ["status", "epoch"]);
8048
+ const reply = closed(await nativeCall(c, "stop", false, confirmedWork ? { confirmedWork } : undefined), ["status", "epoch"]);
7949
8049
  if (reply.status !== "accepted")
7950
8050
  throw new ContractError("unavailable");
7951
8051
  epoch = decodeId(reply.epoch);
@@ -8266,12 +8366,17 @@ async function serverAction(s, action, requested, linger) {
8266
8366
  return { status: "unsupported" };
8267
8367
  }
8268
8368
  }
8269
- function upgrade(s, to) {
8369
+ function upgrade(s, to, stopConfirmed) {
8270
8370
  if (s.platform !== "linux")
8271
8371
  return Promise.resolve({ status: "unsupported" });
8272
8372
  return upgradeService(s, to, {
8273
8373
  commands: packageCommands(s),
8274
- stop: () => serverAction(s, "stop", undefined, false),
8374
+ stop: async () => {
8375
+ if (stopConfirmed && !await stopConfirmed())
8376
+ return { status: "unconfirmed" };
8377
+ stopConfirmed = undefined;
8378
+ return serverAction(s, "stop", undefined, false);
8379
+ },
8275
8380
  restart: () => restartInstalled(s)
8276
8381
  });
8277
8382
  }
@@ -8466,7 +8571,7 @@ async function serverMain(argv, hostUrl) {
8466
8571
  let linger = process.env.CADENCE_LINGER !== "0";
8467
8572
  let scope;
8468
8573
  let name, port;
8469
- let to, job2;
8574
+ let to, job2, confirmedWork;
8470
8575
  const seen = new Set;
8471
8576
  while (argv.length) {
8472
8577
  const flag = argv.shift();
@@ -8491,9 +8596,13 @@ async function serverMain(argv, hostUrl) {
8491
8596
  to = decodeVersion(argv.shift());
8492
8597
  else if (flag === "--job" && (action === "restart" || action === "upgrade") && argv[0])
8493
8598
  job2 = decodeId(argv.shift());
8599
+ else if (flag === "--confirmed-work" && argv[0])
8600
+ confirmedWork = decodeHash(argv.shift());
8494
8601
  else
8495
8602
  throw new ContractError("invalid");
8496
8603
  }
8604
+ if (job2 === undefined !== (confirmedWork === undefined))
8605
+ throw new ContractError("invalid");
8497
8606
  const s = hostSystem(dirname14(dirname14(fileURLToPath2(hostUrl))), ownerControl, {
8498
8607
  scope,
8499
8608
  name
@@ -8538,8 +8647,22 @@ async function serverMain(argv, hostUrl) {
8538
8647
  }
8539
8648
  }
8540
8649
  let result;
8650
+ const stopConfirmed = confirmedWork && job2 ? async () => {
8651
+ try {
8652
+ const unit = generatedUnit(s);
8653
+ if (typeof unit !== "string" || unitWorkspace(unit) !== null)
8654
+ return false;
8655
+ const store = new GatewayStore(serviceConfigPath(s));
8656
+ const recorded = new MaintenanceRecord(store).read();
8657
+ if (recorded?.id !== job2 || recorded.state !== "running" || recorded.action !== action || recorded.to !== (to ?? null) || recorded.from !== installedVersion(s.root))
8658
+ return false;
8659
+ return (await stopService(store, confirmedWork)).status === "stopped";
8660
+ } catch {
8661
+ return false;
8662
+ }
8663
+ } : undefined;
8541
8664
  try {
8542
- result = action === "upgrade" ? await upgrade(s, to) : await serverAction(s, action, requested, linger);
8665
+ result = action === "upgrade" ? await upgrade(s, to, stopConfirmed) : stopConfirmed && !await stopConfirmed() ? { status: "unconfirmed" } : await serverAction(s, action, requested, linger);
8543
8666
  } catch (error) {
8544
8667
  if (error instanceof ContractError && error.code === "invalid")
8545
8668
  process.stderr.write(`Cadence server install needs an existing absolute --workspace directory.