@lace-cloud/canvas 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3543,7 +3543,7 @@ function conflictChoiceToJSON(object) {
3543
3543
  }
3544
3544
  }
3545
3545
  function createBaseReasonDetail() {
3546
- return { reason: 0, api_code: "" };
3546
+ return { reason: 0, api_code: "", request_id: "" };
3547
3547
  }
3548
3548
  var ReasonDetail = {
3549
3549
  encode(message, writer = new BinaryWriter4()) {
@@ -3553,6 +3553,9 @@ var ReasonDetail = {
3553
3553
  if (message.api_code !== "") {
3554
3554
  writer.uint32(18).string(message.api_code);
3555
3555
  }
3556
+ if (message.request_id !== "") {
3557
+ writer.uint32(26).string(message.request_id);
3558
+ }
3556
3559
  return writer;
3557
3560
  },
3558
3561
  decode(input, length) {
@@ -3576,6 +3579,13 @@ var ReasonDetail = {
3576
3579
  message.api_code = reader.string();
3577
3580
  continue;
3578
3581
  }
3582
+ case 3: {
3583
+ if (tag !== 26) {
3584
+ break;
3585
+ }
3586
+ message.request_id = reader.string();
3587
+ continue;
3588
+ }
3579
3589
  }
3580
3590
  if ((tag & 7) === 4 || tag === 0) {
3581
3591
  break;
@@ -3587,7 +3597,8 @@ var ReasonDetail = {
3587
3597
  fromJSON(object) {
3588
3598
  return {
3589
3599
  reason: isSet3(object.reason) ? reasonFromJSON(object.reason) : 0,
3590
- api_code: isSet3(object.apiCode) ? globalThis.String(object.apiCode) : isSet3(object.api_code) ? globalThis.String(object.api_code) : ""
3600
+ api_code: isSet3(object.apiCode) ? globalThis.String(object.apiCode) : isSet3(object.api_code) ? globalThis.String(object.api_code) : "",
3601
+ request_id: isSet3(object.requestId) ? globalThis.String(object.requestId) : isSet3(object.request_id) ? globalThis.String(object.request_id) : ""
3591
3602
  };
3592
3603
  },
3593
3604
  toJSON(message) {
@@ -3598,6 +3609,9 @@ var ReasonDetail = {
3598
3609
  if (message.api_code !== "") {
3599
3610
  obj.apiCode = message.api_code;
3600
3611
  }
3612
+ if (message.request_id !== "") {
3613
+ obj.requestId = message.request_id;
3614
+ }
3601
3615
  return obj;
3602
3616
  },
3603
3617
  create(base) {
@@ -3607,6 +3621,7 @@ var ReasonDetail = {
3607
3621
  const message = createBaseReasonDetail();
3608
3622
  message.reason = object.reason ?? 0;
3609
3623
  message.api_code = object.api_code ?? "";
3624
+ message.request_id = object.request_id ?? "";
3610
3625
  return message;
3611
3626
  }
3612
3627
  };
@@ -7965,7 +7980,7 @@ var InvokeRequest = {
7965
7980
  }
7966
7981
  };
7967
7982
  function createBaseInvokeEvent() {
7968
- return { json: void 0, exit: void 0 };
7983
+ return { json: void 0, exit: void 0, started: void 0 };
7969
7984
  }
7970
7985
  var InvokeEvent = {
7971
7986
  encode(message, writer = new BinaryWriter4()) {
@@ -7975,6 +7990,9 @@ var InvokeEvent = {
7975
7990
  if (message.exit !== void 0) {
7976
7991
  InvokeExit.encode(message.exit, writer.uint32(18).fork()).join();
7977
7992
  }
7993
+ if (message.started !== void 0) {
7994
+ InvokeStarted.encode(message.started, writer.uint32(26).fork()).join();
7995
+ }
7978
7996
  return writer;
7979
7997
  },
7980
7998
  decode(input, length) {
@@ -7998,6 +8016,13 @@ var InvokeEvent = {
7998
8016
  message.exit = InvokeExit.decode(reader, reader.uint32());
7999
8017
  continue;
8000
8018
  }
8019
+ case 3: {
8020
+ if (tag !== 26) {
8021
+ break;
8022
+ }
8023
+ message.started = InvokeStarted.decode(reader, reader.uint32());
8024
+ continue;
8025
+ }
8001
8026
  }
8002
8027
  if ((tag & 7) === 4 || tag === 0) {
8003
8028
  break;
@@ -8009,7 +8034,8 @@ var InvokeEvent = {
8009
8034
  fromJSON(object) {
8010
8035
  return {
8011
8036
  json: isSet3(object.json) ? globalThis.String(object.json) : void 0,
8012
- exit: isSet3(object.exit) ? InvokeExit.fromJSON(object.exit) : void 0
8037
+ exit: isSet3(object.exit) ? InvokeExit.fromJSON(object.exit) : void 0,
8038
+ started: isSet3(object.started) ? InvokeStarted.fromJSON(object.started) : void 0
8013
8039
  };
8014
8040
  },
8015
8041
  toJSON(message) {
@@ -8020,6 +8046,9 @@ var InvokeEvent = {
8020
8046
  if (message.exit !== void 0) {
8021
8047
  obj.exit = InvokeExit.toJSON(message.exit);
8022
8048
  }
8049
+ if (message.started !== void 0) {
8050
+ obj.started = InvokeStarted.toJSON(message.started);
8051
+ }
8023
8052
  return obj;
8024
8053
  },
8025
8054
  create(base) {
@@ -8029,6 +8058,44 @@ var InvokeEvent = {
8029
8058
  const message = createBaseInvokeEvent();
8030
8059
  message.json = object.json ?? void 0;
8031
8060
  message.exit = object.exit !== void 0 && object.exit !== null ? InvokeExit.fromPartial(object.exit) : void 0;
8061
+ message.started = object.started !== void 0 && object.started !== null ? InvokeStarted.fromPartial(object.started) : void 0;
8062
+ return message;
8063
+ }
8064
+ };
8065
+ function createBaseInvokeStarted() {
8066
+ return {};
8067
+ }
8068
+ var InvokeStarted = {
8069
+ encode(_, writer = new BinaryWriter4()) {
8070
+ return writer;
8071
+ },
8072
+ decode(input, length) {
8073
+ const reader = input instanceof BinaryReader4 ? input : new BinaryReader4(input);
8074
+ const end = length === void 0 ? reader.len : reader.pos + length;
8075
+ const message = createBaseInvokeStarted();
8076
+ while (reader.pos < end) {
8077
+ const tag = reader.uint32();
8078
+ switch (tag >>> 3) {
8079
+ }
8080
+ if ((tag & 7) === 4 || tag === 0) {
8081
+ break;
8082
+ }
8083
+ reader.skip(tag & 7);
8084
+ }
8085
+ return message;
8086
+ },
8087
+ fromJSON(_) {
8088
+ return {};
8089
+ },
8090
+ toJSON(_) {
8091
+ const obj = {};
8092
+ return obj;
8093
+ },
8094
+ create(base) {
8095
+ return InvokeStarted.fromPartial(base ?? {});
8096
+ },
8097
+ fromPartial(_) {
8098
+ const message = createBaseInvokeStarted();
8032
8099
  return message;
8033
8100
  }
8034
8101
  };
@@ -10307,8 +10374,9 @@ var LaceEngineDefinition = {
10307
10374
  options: {}
10308
10375
  },
10309
10376
  /**
10310
- * Runs one CLI command in-process against a fresh command tree. The command's `-o json` output is the stream:
10311
- * each top-level JSON value on stdout is one `json` event; `exit` is always last.
10377
+ * Runs one CLI command in-process against a fresh command tree. `started` is first, once the engine has accepted
10378
+ * the request and before the command runs; the command's `-o json` output follows: each top-level JSON value on
10379
+ * stdout is one `json` event; `exit` is always last.
10312
10380
  */
10313
10381
  invoke: {
10314
10382
  name: "Invoke",
@@ -10383,6 +10451,7 @@ function isSet3(value) {
10383
10451
  }
10384
10452
 
10385
10453
  // src/ports.ts
10454
+ import { apiFields } from "@lace-cloud/proto";
10386
10455
  function currentFrame(source) {
10387
10456
  return new Promise((resolve) => {
10388
10457
  let settled = false;
@@ -10416,7 +10485,9 @@ var ConnectError = class extends Error {
10416
10485
  super(`[${code}] ${message}`);
10417
10486
  this.code = code;
10418
10487
  this.reason = detail.reason;
10419
- this.apiCode = detail.api_code === "" ? void 0 : detail.api_code;
10488
+ const { apiCode, requestId } = apiFields(detail);
10489
+ this.apiCode = apiCode;
10490
+ this.requestId = requestId;
10420
10491
  this.name = "ConnectError";
10421
10492
  }
10422
10493
  };
@@ -10693,7 +10764,8 @@ function parseBridgeResponse(raw) {
10693
10764
  return null;
10694
10765
  }
10695
10766
  const apiCode = "apiCode" in raw && typeof raw.apiCode === "string" ? raw.apiCode : void 0;
10696
- return { kind, id, code, message, reason, apiCode };
10767
+ const requestId = "requestId" in raw && typeof raw.requestId === "string" ? raw.requestId : void 0;
10768
+ return { kind, id, code, message, reason, apiCode, requestId };
10697
10769
  }
10698
10770
  return null;
10699
10771
  }
@@ -10701,7 +10773,11 @@ function frameError(frame) {
10701
10773
  return new ConnectError(
10702
10774
  frame.code,
10703
10775
  frame.message,
10704
- ReasonDetail.fromJSON({ reason: frame.reason, api_code: frame.apiCode })
10776
+ ReasonDetail.fromJSON({
10777
+ reason: frame.reason,
10778
+ api_code: frame.apiCode,
10779
+ request_id: frame.requestId
10780
+ })
10705
10781
  );
10706
10782
  }
10707
10783
  function bridgeCaller(bridge) {
@@ -12127,7 +12203,8 @@ var commandFailureSchema = z.strictObject({
12127
12203
  tool: z.string().optional(),
12128
12204
  importResiduals: z.array(importResidualSchema).optional(),
12129
12205
  addresses: z.array(z.string()).optional(),
12130
- apiCode: z.string().optional()
12206
+ apiCode: z.string().optional(),
12207
+ requestId: z.string().optional()
12131
12208
  });
12132
12209
  var moduleValidateDeviationSchema = z.object({
12133
12210
  notCompositional: z.boolean(),
@@ -12566,6 +12643,7 @@ var stackScanSchema = z.object({
12566
12643
  driftCount: z.number(),
12567
12644
  scannedAt: z.string(),
12568
12645
  undeterminedReason: z.string().nullable(),
12646
+ undeterminedMessage: z.string().nullable(),
12569
12647
  standingDriftFindings: z.number(),
12570
12648
  footprintDestroyed: z.boolean(),
12571
12649
  drift: driftSchema
@@ -12958,7 +13036,7 @@ function commandsPort(caller, commandPaths, ownCwd) {
12958
13036
  working_directory: cwd
12959
13037
  };
12960
13038
  async function* run() {
12961
- for await (const event of caller.stream("Invoke", request, signal)) {
13039
+ for await (const event of untilExit()) {
12962
13040
  if (event.json !== void 0) {
12963
13041
  const data = JSON.parse(event.json);
12964
13042
  if (carriesFailure(data)) continue;
@@ -12976,8 +13054,28 @@ function commandsPort(caller, commandPaths, ownCwd) {
12976
13054
  return;
12977
13055
  }
12978
13056
  }
12979
- if (signal.aborted) throw new CommandDetachedError();
12980
- throw new CommandUnobservedError();
13057
+ }
13058
+ async function* untilExit() {
13059
+ let started = false;
13060
+ const stopped = (error) => {
13061
+ if (signal.aborted) return new CommandDetachedError();
13062
+ if (started) return new CommandUnobservedError();
13063
+ return error;
13064
+ };
13065
+ try {
13066
+ for await (const event of caller.stream("Invoke", request, signal)) {
13067
+ started || (started = event.started !== void 0);
13068
+ yield event;
13069
+ }
13070
+ } catch (error) {
13071
+ throw stopped(error);
13072
+ }
13073
+ throw stopped(
13074
+ new ConnectError(
13075
+ "internal",
13076
+ "the engine ended the Invoke stream before it started the command"
13077
+ )
13078
+ );
12981
13079
  }
12982
13080
  return {
12983
13081
  events: run(),
@@ -13051,407 +13149,71 @@ function convertCreatedRef(r) {
13051
13149
  return { scope: r.scope, id: r.id, moduleKey: r.module_key, sourceId: r.source_id };
13052
13150
  }
13053
13151
 
13054
- // src/core/define-command.ts
13055
- function errorNotice(err) {
13056
- if (err instanceof CommandExitError) {
13057
- return err.failure ? [err.stderrTail, err.failure] : [err.stderrTail];
13058
- }
13059
- if (err instanceof Error) return [err.message];
13060
- return [String(err)];
13152
+ // src/core/diagnostics.ts
13153
+ var NOT_LACE_SHAPE = "not_lace_shape";
13154
+ function holdsLaceShapeRefusal(diagnostics) {
13155
+ return diagnostics.some((d) => d.code === NOT_LACE_SHAPE);
13061
13156
  }
13062
- function defineCommand(binding) {
13063
- return {
13064
- kind: "command",
13065
- path: binding.path,
13066
- confirms: binding.confirm !== void 0,
13067
- resultKind: binding.result.kind,
13068
- invalidates: binding.invalidates,
13069
- partialArgs(ctx, target) {
13070
- return binding.args(ctx, target);
13071
- },
13072
- confirmSpec(ctx, target, formArgs) {
13073
- if (!binding.confirm) return void 0;
13074
- const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13075
- if (!merged.ok) return void 0;
13076
- return binding.confirm(ctx, merged.args, target);
13077
- },
13078
- async start(rt, ctx, target, formArgs, signal) {
13079
- const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13080
- if (!merged.ok) return null;
13081
- const commands = rt.ports.commands;
13082
- if (!commands) return null;
13083
- const invocation = commands.invoke(binding.path, merged.args, signal, rt.cwd);
13084
- rt.begin();
13085
- if (binding.invalidates === "start+settle") rt.tick();
13086
- void (async () => {
13087
- try {
13088
- for await (const event of invocation.events) {
13089
- binding.result.consume(rt, event);
13090
- }
13091
- if (binding.invalidates) rt.tick();
13092
- } catch (err) {
13093
- if (!rt.fail(err) && !(err instanceof CommandDetachedError)) {
13094
- rt.ports.presenter.notify("error", ...errorNotice(err));
13095
- }
13096
- if (binding.invalidates) rt.tick();
13097
- } finally {
13098
- rt.settled?.();
13099
- }
13100
- })();
13101
- return { cancel: () => invocation.cancel() };
13102
- }
13103
- };
13157
+ function findingKey(d) {
13158
+ return JSON.stringify([
13159
+ d.file,
13160
+ d.line,
13161
+ d.message,
13162
+ d.module_key,
13163
+ d.instance_id,
13164
+ d.input_name,
13165
+ d.address
13166
+ ]);
13104
13167
  }
13105
-
13106
- // src/core/actions.ts
13107
- function slotSink(kind) {
13108
- return { kind, consume: (rt, e) => rt.write(kind, rt.token, e) };
13168
+ function uniqueDiagnostics(diagnostics) {
13169
+ const seen = /* @__PURE__ */ new Set();
13170
+ return diagnostics.filter((d) => {
13171
+ const key = findingKey(d);
13172
+ if (seen.has(key)) return false;
13173
+ seen.add(key);
13174
+ return true;
13175
+ });
13109
13176
  }
13110
- var apply = defineCommand({
13111
- kind: "command",
13112
- path: "stack apply",
13113
- args: (ctx) => ({ stack: ctx.stack?.id }),
13114
- // The run sink ticks at both start and settle, so a read keyed on the
13115
- // tick (a host's run list, the describe overlay) sees the in-flight run
13116
- // as soon as it starts, not only once it ends.
13117
- invalidates: "start+settle",
13118
- result: slotSink("run")
13119
- });
13120
- var destroy = defineCommand({
13121
- kind: "command",
13122
- path: "stack destroy",
13123
- args: (ctx) => ({ stack: ctx.stack?.id, yes: true }),
13124
- // The typed confirmation is the stack's slug — the human-facing name a
13125
- // user actually reads off the host's stack list — never its id, which
13126
- // `args.stack` carries for the command itself but nobody types from
13127
- // memory.
13128
- confirm: (ctx) => ({
13129
- text: `Destroy ${ctx.stack?.slug}? This runs terraform destroy on the runner.`,
13130
- typed: ctx.stack?.slug
13131
- }),
13132
- invalidates: "start+settle",
13133
- result: slotSink("run")
13134
- });
13135
- function scanNotice(e) {
13136
- const { slug } = e.stack;
13137
- const settled = e.settled;
13138
- if (!settled) {
13139
- return e.triggered ? `Drift scan triggered for stack ${slug} (${e.stack.id}).` : `Drift scan already in progress for stack ${slug}.`;
13140
- }
13141
- if (settled.undeterminedReason !== null) return void 0;
13142
- if (settled.footprintDestroyed) {
13143
- return `Drift scan complete for stack ${slug}: IN_SYNC (0 drifted) \u2014 its resources were destroyed, so there was nothing to compare.`;
13144
- }
13145
- if (settled.standingDriftFindings > 0) {
13146
- return `Drift scan complete for stack ${slug}: the scan observed no drift, but ${settled.standingDriftFindings} drift finding(s) from earlier scans still stand \u2014 the stack remains DRIFTED.`;
13147
- }
13148
- return `Drift scan complete for stack ${slug}: ${settled.driftStatus} (${settled.driftCount} drifted).`;
13177
+ function diagnosticsOf(sourceDiagnostics, reportFindings) {
13178
+ return uniqueDiagnostics([...sourceDiagnostics, ...reportFindings]);
13149
13179
  }
13150
- var scan = defineCommand({
13151
- kind: "command",
13152
- path: "stack scan",
13153
- args: (ctx) => ({ stack: ctx.stack?.id, wait: true }),
13154
- invalidates: true,
13155
- result: {
13156
- kind: "notify",
13157
- consume: (rt, e) => {
13158
- const notice = scanNotice(e);
13159
- if (notice !== void 0) rt.ports.presenter.notify("info", notice);
13160
- }
13180
+
13181
+ // src/core/report-fold.ts
13182
+ var REPORT_PATHS = ["module validate", "module convert", "module scan"];
13183
+ var FOLDS_AS = new Map([
13184
+ ...REPORT_PATHS.map((path) => [path, path]),
13185
+ ["stack import", "module convert"]
13186
+ ]);
13187
+ var EMPTY_REPORT_FOLD = /* @__PURE__ */ new Map();
13188
+ function readEntry(path, exitCode, data) {
13189
+ if (carriesFailure(data)) {
13190
+ return { kind: "failure", path, exitCode, failure: parseCommandFailure(data) };
13161
13191
  }
13162
- });
13163
- var create = defineCommand({
13164
- kind: "command",
13165
- path: "stack create",
13166
- args: (ctx) => ({ source: ctx.root }),
13167
- invalidates: true,
13168
- result: {
13169
- kind: "notify",
13170
- consume: (rt, e) => rt.ports.presenter.notify("info", `Created stack ${e.slug}`)
13192
+ switch (path) {
13193
+ case "module validate":
13194
+ return { kind: "result", path, exitCode, document: parseBound(path, data) };
13195
+ case "module convert":
13196
+ return { kind: "result", path, exitCode, document: parseBound(path, data) };
13197
+ case "module scan":
13198
+ return { kind: "result", path, exitCode, document: parseBound(path, data) };
13171
13199
  }
13172
- });
13173
- function residualAddresses(residuals) {
13174
- return residuals.map((r) => r.address).join(", ");
13175
13200
  }
13176
- function treeChanges(e) {
13177
- return [
13178
- ...e.written.length === 0 ? [] : [`rewriting ${e.written.join(", ")} in place`],
13179
- ...e.removed.length === 0 ? [] : [`removing ${e.removed.join(", ")}`]
13180
- ];
13201
+ function foldReport(prev, result) {
13202
+ const path = FOLDS_AS.get(result.path);
13203
+ if (path === void 0) return prev;
13204
+ const next = new Map(prev);
13205
+ if (result.document === "") next.delete(path);
13206
+ else next.set(path, readEntry(path, result.exitCode, JSON.parse(result.document)));
13207
+ return next;
13181
13208
  }
13182
- function importNotice(e) {
13183
- const { slug } = e.stack;
13184
- const changes = treeChanges(e);
13185
- const files = changes.length > 0 ? `, ${changes.join(" and ")}` : "";
13186
- const imported = `Imported ${e.importBlocks} resource(s) into ${slug}${files}.`;
13187
- if (e.validate.exitClass !== "ok") {
13188
- return ["warn", `${imported} The tree did not validate: fix it before you commit it.`];
13189
- }
13190
- const adopt = e.changed ? ` Review the change in git, commit it, then apply ${slug} to adopt them.` : "";
13191
- if (e.importResiduals.length === 0) return ["info", `${imported}${adopt}`];
13192
- return [
13193
- "warn",
13194
- `${imported}${adopt} Not adopted: ${residualAddresses(e.importResiduals)}; supply their import ids before applying, or the apply creates them anew.`
13195
- ];
13196
- }
13197
- var importResult = {
13198
- kind: "notify",
13199
- consume: (rt, e) => rt.ports.presenter.notify(...importNotice(e))
13200
- };
13201
- var importStack = defineCommand({
13202
- kind: "command",
13203
- path: "stack import",
13204
- args: (ctx) => ({ stack: ctx.stack?.id }),
13205
- invalidates: true,
13206
- result: importResult
13207
- });
13208
- var importPartial = defineCommand({
13209
- kind: "command",
13210
- path: "stack import",
13211
- args: (ctx) => ({ stack: ctx.stack?.id, allowPartial: true }),
13212
- confirm: (ctx, _args, target) => ({
13213
- text: `Import into ${ctx.stack?.slug} without adopting ${residualAddresses(target.failure?.importResiduals ?? [])}? Lace writes no import block for them, so the stack's apply creates them anew beside the live ones.`
13214
- }),
13215
- invalidates: true,
13216
- result: importResult
13217
- });
13218
- var validate = defineCommand({
13219
- kind: "command",
13220
- path: "module validate",
13221
- args: () => ({}),
13222
- result: {
13223
- kind: "notify",
13224
- consume: (rt, e) => {
13225
- if (e.exitClass === "ok") rt.ports.presenter.notify("info", `Valid for Lace \u2014 ${e.verdict}`);
13226
- }
13227
- }
13228
- });
13229
- var convert = defineCommand({
13230
- kind: "command",
13231
- path: "module convert",
13232
- args: () => ({}),
13233
- result: {
13234
- kind: "notify",
13235
- consume: (rt, e) => rt.ports.presenter.notify(
13236
- "info",
13237
- e.changed ? `Converted \u2014 ${e.written.length} file(s) written` : "Already lace-style \u2014 nothing to write"
13238
- )
13239
- }
13240
- });
13241
- var preview = defineCommand({
13242
- kind: "command",
13243
- path: "stack preview",
13244
- args: (ctx) => ({ stack: ctx.stack?.id }),
13245
- result: slotSink("preview")
13246
- });
13247
- var runCancel = defineCommand({
13248
- kind: "command",
13249
- path: "run cancel",
13250
- args: (_ctx, target) => ({ run: target.runId }),
13251
- invalidates: true,
13252
- result: {
13253
- kind: "notify",
13254
- consume: (rt, e) => rt.ports.presenter.notify("info", `Run ${e.id} ${e.status}`)
13255
- }
13256
- });
13257
- var followLogs = defineCommand({
13258
- kind: "command",
13259
- path: "run logs",
13260
- args: (_ctx, target) => ({ run: target.runId, follow: true }),
13261
- result: slotSink("follow")
13262
- });
13263
- var MODULE_COMMAND_ACTIONS = [
13264
- {
13265
- id: "validate",
13266
- label: "Validate",
13267
- icon: "validate",
13268
- section: "check",
13269
- placement: "toolbar",
13270
- requiredPorts: ["commands"],
13271
- requiredContext: ["root"],
13272
- binding: validate
13273
- },
13274
- {
13275
- id: "convert",
13276
- label: "Convert",
13277
- icon: "convert",
13278
- section: "check",
13279
- placement: "toolbar",
13280
- requiredPorts: ["commands"],
13281
- requiredContext: ["root"],
13282
- binding: convert
13283
- },
13284
- // Convert on the source-refused banner while the tree is out of lace
13285
- // shape: the same `module convert` the toolbar runs, and the choice the
13286
- // banner says of it. The engine re-derives the tree it writes, which
13287
- // accepts it and lifts the lock.
13288
- {
13289
- id: "convert-refused",
13290
- label: "Convert",
13291
- choice: "Convert restructures it in place; a stack's apply creates only what its state does not hold yet.",
13292
- icon: "convert",
13293
- placement: { row: "source-refused" },
13294
- requiredPorts: ["commands"],
13295
- requiredContext: ["root", "needsConversion"],
13296
- binding: convert
13297
- }
13298
- ];
13299
- var STACK_COMMAND_ACTIONS = [
13300
- {
13301
- id: "apply",
13302
- label: "Apply",
13303
- placement: "toolbar",
13304
- requiredPorts: ["commands"],
13305
- // `stack apply` gates on the tf and certification of the directory it
13306
- // runs in (submit.Prepare(env.Root)) before it ever reaches the
13307
- // runner, so a mount with no root can't run it even with a stack
13308
- // chosen — the same root gate `validate`/`convert` need. It ships
13309
- // whatever tf is on disk, not the canvas's own working IR.
13310
- requiredContext: ["root", "stack"],
13311
- binding: apply
13312
- },
13313
- {
13314
- id: "destroy",
13315
- label: "Destroy",
13316
- placement: "toolbar",
13317
- requiredPorts: ["commands"],
13318
- // `stack destroy` shares the CLI's `executeRun` with `stack apply` and
13319
- // runs under `env.Root`, so it needs the identical context tuple.
13320
- requiredContext: ["root", "stack"],
13321
- binding: destroy
13322
- },
13323
- {
13324
- id: "scan",
13325
- label: "Scan for drift",
13326
- placement: "toolbar",
13327
- requiredPorts: ["commands"],
13328
- requiredContext: ["stack"],
13329
- binding: scan
13330
- },
13331
- {
13332
- id: "create",
13333
- label: "Create stack",
13334
- placement: "toolbar",
13335
- requiredPorts: ["commands"],
13336
- requiredContext: ["root"],
13337
- binding: create
13338
- },
13339
- {
13340
- id: "import",
13341
- label: "Import existing resources",
13342
- placement: "toolbar",
13343
- requiredPorts: ["commands"],
13344
- // `stack import` writes the directory it runs in, the same way
13345
- // Convert does.
13346
- requiredContext: ["root", "stack"],
13347
- binding: importStack
13348
- },
13349
- {
13350
- id: "import-partial",
13351
- label: "Import the rest",
13352
- placement: { row: "failure" },
13353
- requiredPorts: ["commands"],
13354
- requiredContext: ["root", "stack"],
13355
- answers: ["import_residual"],
13356
- binding: importPartial
13357
- },
13358
- {
13359
- id: "preview",
13360
- label: "Preview",
13361
- placement: "toolbar",
13362
- requiredPorts: ["commands"],
13363
- // `stack preview` plans the tf of the directory it runs in — a stack
13364
- // alone isn't enough, the mount needs the root too.
13365
- requiredContext: ["root", "stack"],
13366
- binding: preview
13367
- },
13368
- {
13369
- id: "run-cancel",
13370
- label: "Cancel",
13371
- placement: { row: "runs" },
13372
- requiredPorts: ["commands"],
13373
- requiredTarget: ["runId"],
13374
- binding: runCancel
13375
- },
13376
- {
13377
- id: "follow-logs",
13378
- label: "Follow logs",
13379
- placement: { row: "runs" },
13380
- requiredPorts: ["commands"],
13381
- requiredTarget: ["runId"],
13382
- binding: followLogs
13383
- }
13384
- ];
13385
- var CORE_COMMAND_ACTIONS = [
13386
- ...STACK_COMMAND_ACTIONS,
13387
- ...MODULE_COMMAND_ACTIONS
13388
- ];
13389
-
13390
- // src/core/diagnostics.ts
13391
- var NOT_LACE_SHAPE = "not_lace_shape";
13392
- function holdsLaceShapeRefusal(diagnostics) {
13393
- return diagnostics.some((d) => d.code === NOT_LACE_SHAPE);
13394
- }
13395
- function findingKey(d) {
13396
- return JSON.stringify([
13397
- d.file,
13398
- d.line,
13399
- d.message,
13400
- d.module_key,
13401
- d.instance_id,
13402
- d.input_name,
13403
- d.address
13404
- ]);
13405
- }
13406
- function uniqueDiagnostics(diagnostics) {
13407
- const seen = /* @__PURE__ */ new Set();
13408
- return diagnostics.filter((d) => {
13409
- const key = findingKey(d);
13410
- if (seen.has(key)) return false;
13411
- seen.add(key);
13412
- return true;
13413
- });
13414
- }
13415
- function diagnosticsOf(sourceDiagnostics, reportFindings) {
13416
- return uniqueDiagnostics([...sourceDiagnostics, ...reportFindings]);
13417
- }
13418
-
13419
- // src/core/report-fold.ts
13420
- var REPORT_PATHS = ["module validate", "module convert", "module scan"];
13421
- var FOLDS_AS = new Map([
13422
- ...REPORT_PATHS.map((path) => [path, path]),
13423
- ["stack import", "module convert"]
13424
- ]);
13425
- var EMPTY_REPORT_FOLD = /* @__PURE__ */ new Map();
13426
- function readEntry(path, exitCode, data) {
13427
- if (carriesFailure(data)) {
13428
- return { kind: "failure", path, exitCode, failure: parseCommandFailure(data) };
13429
- }
13430
- switch (path) {
13431
- case "module validate":
13432
- return { kind: "result", path, exitCode, document: parseBound(path, data) };
13433
- case "module convert":
13434
- return { kind: "result", path, exitCode, document: parseBound(path, data) };
13435
- case "module scan":
13436
- return { kind: "result", path, exitCode, document: parseBound(path, data) };
13437
- }
13438
- }
13439
- function foldReport(prev, result) {
13440
- const path = FOLDS_AS.get(result.path);
13441
- if (path === void 0) return prev;
13442
- const next = new Map(prev);
13443
- if (result.document === "") next.delete(path);
13444
- else next.set(path, readEntry(path, result.exitCode, JSON.parse(result.document)));
13445
- return next;
13446
- }
13447
- function treeHashOf(entry) {
13448
- if (entry.kind === "failure") return void 0;
13449
- switch (entry.path) {
13450
- case "module validate":
13451
- case "module scan":
13452
- return entry.document.treeHash;
13453
- case "module convert":
13454
- return entry.document.validate.treeHash;
13209
+ function treeHashOf(entry) {
13210
+ if (entry.kind === "failure") return void 0;
13211
+ switch (entry.path) {
13212
+ case "module validate":
13213
+ case "module scan":
13214
+ return entry.document.treeHash;
13215
+ case "module convert":
13216
+ return entry.document.validate.treeHash;
13455
13217
  }
13456
13218
  }
13457
13219
  function currentReport(fold, treeHash) {
@@ -13561,148 +13323,527 @@ function reduceRun(prev, token, event) {
13561
13323
  phases: closePhases(phases)
13562
13324
  };
13563
13325
  }
13564
- return { token, outcome: { kind: "running" }, lastLog, submitted, phases };
13565
- }
13566
- function exitSays(error) {
13567
- return error.failure ? { message: error.stderrTail, failure: error.failure } : { message: error.stderrTail };
13568
- }
13569
- function settleRun(prev, token, error) {
13570
- const carried = prev && prev.token === token ? prev : null;
13571
- const lastLog = carried?.lastLog ?? null;
13572
- const submitted = carried?.submitted ?? false;
13573
- const phases = closePhases(carried?.phases ?? []);
13574
- if (error instanceof CommandDetachedError || error instanceof CommandUnobservedError)
13575
- return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13576
- if (error instanceof CommandExitError) {
13577
- if (error.code === 130)
13578
- return { token, outcome: { kind: "cancelled" }, lastLog, submitted, phases };
13579
- if (error.code === 143)
13580
- return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13581
- if (error.code === 7)
13582
- return {
13583
- token,
13584
- outcome: { kind: "blocked", ...exitSays(error) },
13585
- lastLog,
13586
- submitted,
13587
- phases
13588
- };
13589
- return {
13590
- token,
13591
- outcome: { kind: "failed", ...exitSays(error) },
13592
- lastLog,
13593
- submitted,
13594
- phases
13595
- };
13326
+ return { token, outcome: { kind: "running" }, lastLog, submitted, phases };
13327
+ }
13328
+ function failureSays(error, command) {
13329
+ if (error instanceof CommandExitError) {
13330
+ return error.failure ? { message: error.failure.message, failure: error.failure } : { message: error.stderrTail };
13331
+ }
13332
+ if (error instanceof CommandUnobservedError && command.kind === "read") {
13333
+ return { message: `the stream ended before \`lace ${command.path}\` finished; run it again` };
13334
+ }
13335
+ return { message: error instanceof Error ? error.message : String(error) };
13336
+ }
13337
+ var RUN = { kind: "write" };
13338
+ function settleRun(prev, token, error) {
13339
+ const carried = prev && prev.token === token ? prev : null;
13340
+ const lastLog = carried?.lastLog ?? null;
13341
+ const submitted = carried?.submitted ?? false;
13342
+ const phases = closePhases(carried?.phases ?? []);
13343
+ if (error instanceof CommandDetachedError || error instanceof CommandUnobservedError)
13344
+ return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13345
+ if (error instanceof CommandExitError) {
13346
+ if (error.code === 130)
13347
+ return { token, outcome: { kind: "cancelled" }, lastLog, submitted, phases };
13348
+ if (error.code === 143)
13349
+ return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13350
+ if (error.code === 7)
13351
+ return {
13352
+ token,
13353
+ outcome: { kind: "blocked", ...failureSays(error, RUN) },
13354
+ lastLog,
13355
+ submitted,
13356
+ phases
13357
+ };
13358
+ }
13359
+ return {
13360
+ token,
13361
+ outcome: { kind: "failed", ...failureSays(error, RUN) },
13362
+ lastLog,
13363
+ submitted,
13364
+ phases
13365
+ };
13366
+ }
13367
+ function reducePreview(_prev, token, event) {
13368
+ return { token, data: event };
13369
+ }
13370
+ function reduceReport(prev, session, result) {
13371
+ const fold = foldReport(prev?.sessions.get(session) ?? EMPTY_REPORT_FOLD, result);
13372
+ return { sessions: new Map(prev?.sessions).set(session, fold) };
13373
+ }
13374
+ function reduceFollow(prev, token, event) {
13375
+ const carried = prev && prev.token === token ? prev : null;
13376
+ const runId = carried?.runId ?? "";
13377
+ const lines = carried?.lines ?? [];
13378
+ if (event.type === "log") return { token, runId, lines: [...lines, event.text], done: false };
13379
+ return { token, runId, lines, done: true };
13380
+ }
13381
+ function createResultStore() {
13382
+ let slots = {
13383
+ run: null,
13384
+ preview: null,
13385
+ report: null,
13386
+ follow: null,
13387
+ running: /* @__PURE__ */ new Map()
13388
+ };
13389
+ let tick = 0;
13390
+ const listeners = /* @__PURE__ */ new Set();
13391
+ const notify = () => {
13392
+ for (const listener of listeners) listener();
13393
+ };
13394
+ const retiredTokens = /* @__PURE__ */ new WeakSet();
13395
+ return {
13396
+ getSnapshot() {
13397
+ return slots;
13398
+ },
13399
+ getTick() {
13400
+ return tick;
13401
+ },
13402
+ subscribe(listener) {
13403
+ listeners.add(listener);
13404
+ return () => listeners.delete(listener);
13405
+ },
13406
+ write(kind, token, value, readOver) {
13407
+ if (retiredTokens.has(token)) return;
13408
+ slots = { ...slots, [kind]: applySlot(kind, slots[kind], token, value, readOver) };
13409
+ notify();
13410
+ },
13411
+ fail(kind, token, error) {
13412
+ if (kind !== "run") return false;
13413
+ if (retiredTokens.has(token) || !slots.run) return true;
13414
+ slots = { ...slots, run: stamp(settleRun(slots.run, token, error), slots.run.readOver) };
13415
+ notify();
13416
+ return true;
13417
+ },
13418
+ begin(kind, token, readOver, started) {
13419
+ if (kind === "run") {
13420
+ slots = {
13421
+ ...slots,
13422
+ run: {
13423
+ token,
13424
+ outcome: { kind: "running" },
13425
+ lastLog: null,
13426
+ submitted: false,
13427
+ phases: [],
13428
+ readOver
13429
+ }
13430
+ };
13431
+ } else if (kind === "follow") {
13432
+ slots = {
13433
+ ...slots,
13434
+ follow: { token, runId: started.target.runId ?? "", lines: [], done: false, readOver }
13435
+ };
13436
+ } else if (kind === "notify") {
13437
+ const { on, path, label } = started;
13438
+ slots = { ...slots, running: new Map(slots.running).set(on, { token, path, label }) };
13439
+ } else {
13440
+ return;
13441
+ }
13442
+ notify();
13443
+ },
13444
+ detach(kind, token) {
13445
+ if (kind === "follow" && slots.follow?.token === token) {
13446
+ slots = { ...slots, follow: null };
13447
+ notify();
13448
+ } else if (kind === "report" && slots.report?.sessions.has(token)) {
13449
+ const sessions = new Map(slots.report.sessions);
13450
+ sessions.delete(token);
13451
+ slots = {
13452
+ ...slots,
13453
+ report: sessions.size > 0 ? { sessions, readOver: slots.report.readOver } : null
13454
+ };
13455
+ notify();
13456
+ } else if (kind === "run" && slots.run?.token === token) {
13457
+ const settled = settleRun(slots.run, token, new CommandDetachedError());
13458
+ slots = { ...slots, run: stamp(settled, slots.run.readOver) };
13459
+ notify();
13460
+ } else if (kind === "notify") {
13461
+ const running = new Map([...slots.running].filter(([, mark]) => mark.token !== token));
13462
+ if (running.size !== slots.running.size) {
13463
+ slots = { ...slots, running };
13464
+ notify();
13465
+ }
13466
+ }
13467
+ retiredTokens.add(token);
13468
+ },
13469
+ busy(kind, on) {
13470
+ if (kind === "run") {
13471
+ return slots.run?.outcome.kind === "running" ? { kind: "run" } : void 0;
13472
+ }
13473
+ if (kind !== "notify") return void 0;
13474
+ const running = slots.running.get(on);
13475
+ return running ? { kind: "notify", running } : void 0;
13476
+ },
13477
+ bumpTick() {
13478
+ tick += 1;
13479
+ notify();
13480
+ }
13481
+ };
13482
+ }
13483
+
13484
+ // src/core/define-command.ts
13485
+ function defineCommand(binding) {
13486
+ return {
13487
+ kind: "command",
13488
+ path: binding.path,
13489
+ confirms: binding.confirm !== void 0,
13490
+ resultKind: binding.result.kind,
13491
+ invalidates: binding.invalidates,
13492
+ partialArgs(ctx, target) {
13493
+ return binding.args(ctx, target);
13494
+ },
13495
+ confirmSpec(ctx, target, formArgs) {
13496
+ if (!binding.confirm) return void 0;
13497
+ const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13498
+ if (!merged.ok) return void 0;
13499
+ return binding.confirm(ctx, merged.args, target);
13500
+ },
13501
+ async start(rt, ctx, target, formArgs, signal) {
13502
+ const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13503
+ if (!merged.ok) return null;
13504
+ const commands = rt.ports.commands;
13505
+ if (!commands) return null;
13506
+ const invocation = commands.invoke(binding.path, merged.args, signal, rt.cwd);
13507
+ rt.begin();
13508
+ if (binding.invalidates === "start+settle") rt.tick();
13509
+ void (async () => {
13510
+ let rendered = false;
13511
+ try {
13512
+ for await (const event of invocation.events) {
13513
+ rendered = true;
13514
+ binding.result.consume(rt, event);
13515
+ }
13516
+ if (binding.invalidates) rt.tick();
13517
+ } catch (err) {
13518
+ const settledByDocument = rendered && binding.result.kind === "notify" && (err instanceof CommandExitError || err instanceof CommandUnobservedError);
13519
+ if (!rt.fail(err) && !(err instanceof CommandDetachedError) && !settledByDocument) {
13520
+ const { message, failure } = failureSays(
13521
+ err,
13522
+ binding.result.kind === "preview" || binding.result.kind === "follow" ? { kind: "read", path: binding.path } : { kind: "write" }
13523
+ );
13524
+ rt.ports.presenter.notify("error", message, ...failure ? [failure] : []);
13525
+ }
13526
+ if (binding.invalidates) rt.tick();
13527
+ } finally {
13528
+ rt.settled?.();
13529
+ }
13530
+ })();
13531
+ return { cancel: () => invocation.cancel() };
13532
+ }
13533
+ };
13534
+ }
13535
+
13536
+ // src/core/actions.ts
13537
+ function whyNotValid(v) {
13538
+ if (v.failure) return v.failure.message;
13539
+ const errors = v.diagnostics.filter((d) => d.severity === "error");
13540
+ if (errors.length === 0) return void 0;
13541
+ return `${errors[0].message} (${errors.length} ${errors.length === 1 ? "error" : "errors"})`;
13542
+ }
13543
+ function didNotValidate(v) {
13544
+ const why = whyNotValid(v);
13545
+ return why === void 0 ? "The tree did not validate: fix it before you commit it." : `The tree did not validate: ${why}. Fix it before you commit it.`;
13546
+ }
13547
+ function beside(v) {
13548
+ return v.failure ? [v.failure] : [];
13549
+ }
13550
+ function slotSink(kind) {
13551
+ return { kind, consume: (rt, e) => rt.write(kind, rt.token, e) };
13552
+ }
13553
+ var apply = defineCommand({
13554
+ kind: "command",
13555
+ path: "stack apply",
13556
+ args: (ctx) => ({ stack: ctx.stack?.id }),
13557
+ // The run sink ticks at both start and settle, so a read keyed on the
13558
+ // tick (a host's run list, the describe overlay) sees the in-flight run
13559
+ // as soon as it starts, not only once it ends.
13560
+ invalidates: "start+settle",
13561
+ result: slotSink("run")
13562
+ });
13563
+ var destroy = defineCommand({
13564
+ kind: "command",
13565
+ path: "stack destroy",
13566
+ args: (ctx) => ({ stack: ctx.stack?.id, yes: true }),
13567
+ // The typed confirmation is the stack's slug — the human-facing name a
13568
+ // user actually reads off the host's stack list — never its id, which
13569
+ // `args.stack` carries for the command itself but nobody types from
13570
+ // memory.
13571
+ confirm: (ctx) => ({
13572
+ text: `Destroy ${ctx.stack?.slug}? This runs terraform destroy on the runner.`,
13573
+ typed: ctx.stack?.slug
13574
+ }),
13575
+ invalidates: "start+settle",
13576
+ result: slotSink("run")
13577
+ });
13578
+ function scanNotice(e) {
13579
+ const { slug } = e.stack;
13580
+ const settled = e.settled;
13581
+ if (!settled) {
13582
+ return [
13583
+ "info",
13584
+ e.triggered ? `Drift scan triggered for stack ${slug} (${e.stack.id}).` : `Drift scan already in progress for stack ${slug}.`
13585
+ ];
13586
+ }
13587
+ if (settled.undeterminedMessage !== null) return ["warn", settled.undeterminedMessage];
13588
+ if (settled.footprintDestroyed) {
13589
+ return [
13590
+ "info",
13591
+ `Drift scan complete for stack ${slug}: IN_SYNC (0 drifted) \u2014 its resources were destroyed, so there was nothing to compare.`
13592
+ ];
13593
+ }
13594
+ if (settled.standingDriftFindings > 0) {
13595
+ return [
13596
+ "info",
13597
+ `Drift scan complete for stack ${slug}: the scan observed no drift, but ${settled.standingDriftFindings} drift finding(s) from earlier scans still stand \u2014 the stack remains DRIFTED.`
13598
+ ];
13599
+ }
13600
+ return [
13601
+ "info",
13602
+ `Drift scan complete for stack ${slug}: ${settled.driftStatus} (${settled.driftCount} drifted).`
13603
+ ];
13604
+ }
13605
+ var scan = defineCommand({
13606
+ kind: "command",
13607
+ path: "stack scan",
13608
+ args: (ctx) => ({ stack: ctx.stack?.id, wait: true }),
13609
+ invalidates: true,
13610
+ result: {
13611
+ kind: "notify",
13612
+ consume: (rt, e) => rt.ports.presenter.notify(...scanNotice(e))
13613
+ }
13614
+ });
13615
+ var create = defineCommand({
13616
+ kind: "command",
13617
+ path: "stack create",
13618
+ args: (ctx) => ({ source: ctx.root }),
13619
+ invalidates: true,
13620
+ result: {
13621
+ kind: "notify",
13622
+ consume: (rt, e) => rt.ports.presenter.notify("info", `Created stack ${e.slug}`)
13623
+ }
13624
+ });
13625
+ function residualAddresses(residuals) {
13626
+ return residuals.map((r) => r.address).join(", ");
13627
+ }
13628
+ function treeChanges(e) {
13629
+ return [
13630
+ ...e.written.length === 0 ? [] : [`rewriting ${e.written.join(", ")} in place`],
13631
+ ...e.removed.length === 0 ? [] : [`removing ${e.removed.join(", ")}`]
13632
+ ];
13633
+ }
13634
+ function importNotice(e) {
13635
+ const { slug } = e.stack;
13636
+ const changes = treeChanges(e);
13637
+ const files = changes.length > 0 ? `, ${changes.join(" and ")}` : "";
13638
+ const imported = `Imported ${e.importBlocks} resource(s) into ${slug}${files}.`;
13639
+ if (e.validate.exitClass !== "ok") {
13640
+ return ["warn", `${imported} ${didNotValidate(e.validate)}`, ...beside(e.validate)];
13641
+ }
13642
+ const adopt = e.changed ? ` Review the change in git, commit it, then apply ${slug} to adopt them.` : "";
13643
+ if (e.importResiduals.length === 0) return ["info", `${imported}${adopt}`];
13644
+ return [
13645
+ "warn",
13646
+ `${imported}${adopt} Not adopted: ${residualAddresses(e.importResiduals)}; supply their import ids before applying, or the apply creates them anew.`
13647
+ ];
13648
+ }
13649
+ var importResult = {
13650
+ kind: "notify",
13651
+ consume: (rt, e) => rt.ports.presenter.notify(...importNotice(e))
13652
+ };
13653
+ var importStack = defineCommand({
13654
+ kind: "command",
13655
+ path: "stack import",
13656
+ args: (ctx) => ({ stack: ctx.stack?.id }),
13657
+ invalidates: true,
13658
+ result: importResult
13659
+ });
13660
+ var importPartial = defineCommand({
13661
+ kind: "command",
13662
+ path: "stack import",
13663
+ args: (ctx) => ({ stack: ctx.stack?.id, allowPartial: true }),
13664
+ confirm: (ctx, _args, target) => ({
13665
+ text: `Import into ${ctx.stack?.slug} without adopting ${residualAddresses(target.failure?.importResiduals ?? [])}? Lace writes no import block for them, so the stack's apply creates them anew beside the live ones.`
13666
+ }),
13667
+ invalidates: true,
13668
+ result: importResult
13669
+ });
13670
+ function validateNotice(v) {
13671
+ if (v.exitClass === "ok") return ["info", `Valid for Lace \u2014 ${v.verdict}`];
13672
+ if (v.failure) return ["error", v.failure.message, v.failure];
13673
+ const why = whyNotValid(v);
13674
+ return ["warn", why === void 0 ? "Not valid for Lace" : `Not valid: ${why}`];
13675
+ }
13676
+ function convertNotice(e) {
13677
+ const converted = e.changed ? `Converted \u2014 ${e.written.length} file(s) written` : "Already lace-style \u2014 nothing to write";
13678
+ if (e.validate.exitClass === "ok") return ["info", converted];
13679
+ return ["warn", `${converted}. ${didNotValidate(e.validate)}`, ...beside(e.validate)];
13680
+ }
13681
+ var validate = defineCommand({
13682
+ kind: "command",
13683
+ path: "module validate",
13684
+ args: () => ({}),
13685
+ result: {
13686
+ kind: "notify",
13687
+ consume: (rt, e) => rt.ports.presenter.notify(...validateNotice(e))
13688
+ }
13689
+ });
13690
+ var convert = defineCommand({
13691
+ kind: "command",
13692
+ path: "module convert",
13693
+ args: () => ({}),
13694
+ result: {
13695
+ kind: "notify",
13696
+ consume: (rt, e) => rt.ports.presenter.notify(...convertNotice(e))
13697
+ }
13698
+ });
13699
+ var preview = defineCommand({
13700
+ kind: "command",
13701
+ path: "stack preview",
13702
+ args: (ctx) => ({ stack: ctx.stack?.id }),
13703
+ result: slotSink("preview")
13704
+ });
13705
+ var runCancel = defineCommand({
13706
+ kind: "command",
13707
+ path: "run cancel",
13708
+ args: (_ctx, target) => ({ run: target.runId }),
13709
+ invalidates: true,
13710
+ result: {
13711
+ kind: "notify",
13712
+ consume: (rt, e) => rt.ports.presenter.notify("info", `Run ${e.id} ${e.status}`)
13713
+ }
13714
+ });
13715
+ var followLogs = defineCommand({
13716
+ kind: "command",
13717
+ path: "run logs",
13718
+ args: (_ctx, target) => ({ run: target.runId, follow: true }),
13719
+ result: slotSink("follow")
13720
+ });
13721
+ var MODULE_COMMAND_ACTIONS = [
13722
+ {
13723
+ id: "validate",
13724
+ label: "Validate",
13725
+ icon: "validate",
13726
+ section: "check",
13727
+ placement: "toolbar",
13728
+ requiredPorts: ["commands"],
13729
+ requiredContext: ["root"],
13730
+ binding: validate
13731
+ },
13732
+ {
13733
+ id: "convert",
13734
+ label: "Convert",
13735
+ icon: "convert",
13736
+ section: "check",
13737
+ placement: "toolbar",
13738
+ requiredPorts: ["commands"],
13739
+ requiredContext: ["root"],
13740
+ binding: convert
13741
+ },
13742
+ // Convert on the source-refused banner while the tree is out of lace
13743
+ // shape: the same `module convert` the toolbar runs, and the choice the
13744
+ // banner says of it. The engine re-derives the tree it writes, which
13745
+ // accepts it and lifts the lock.
13746
+ {
13747
+ id: "convert-refused",
13748
+ label: "Convert",
13749
+ choice: "Convert restructures it in place; a stack's apply creates only what its state does not hold yet.",
13750
+ icon: "convert",
13751
+ placement: { row: "source-refused" },
13752
+ requiredPorts: ["commands"],
13753
+ requiredContext: ["root", "needsConversion"],
13754
+ binding: convert
13755
+ }
13756
+ ];
13757
+ var STACK_COMMAND_ACTIONS = [
13758
+ {
13759
+ id: "apply",
13760
+ label: "Apply",
13761
+ placement: "toolbar",
13762
+ requiredPorts: ["commands"],
13763
+ // `stack apply` gates on the tf and certification of the directory it
13764
+ // runs in (submit.Prepare(env.Root)) before it ever reaches the
13765
+ // runner, so a mount with no root can't run it even with a stack
13766
+ // chosen — the same root gate `validate`/`convert` need. It ships
13767
+ // whatever tf is on disk, not the canvas's own working IR.
13768
+ requiredContext: ["root", "stack"],
13769
+ binding: apply
13770
+ },
13771
+ {
13772
+ id: "destroy",
13773
+ label: "Destroy",
13774
+ placement: "toolbar",
13775
+ requiredPorts: ["commands"],
13776
+ // `stack destroy` shares the CLI's `executeRun` with `stack apply` and
13777
+ // runs under `env.Root`, so it needs the identical context tuple.
13778
+ requiredContext: ["root", "stack"],
13779
+ binding: destroy
13780
+ },
13781
+ {
13782
+ id: "scan",
13783
+ label: "Scan for drift",
13784
+ placement: "toolbar",
13785
+ requiredPorts: ["commands"],
13786
+ requiredContext: ["stack"],
13787
+ binding: scan
13788
+ },
13789
+ {
13790
+ id: "create",
13791
+ label: "Create stack",
13792
+ placement: "toolbar",
13793
+ requiredPorts: ["commands"],
13794
+ requiredContext: ["root"],
13795
+ binding: create
13796
+ },
13797
+ {
13798
+ id: "import",
13799
+ label: "Import existing resources",
13800
+ placement: "toolbar",
13801
+ requiredPorts: ["commands"],
13802
+ // `stack import` writes the directory it runs in, the same way
13803
+ // Convert does.
13804
+ requiredContext: ["root", "stack"],
13805
+ binding: importStack
13806
+ },
13807
+ {
13808
+ id: "import-partial",
13809
+ label: "Import the rest",
13810
+ placement: { row: "failure" },
13811
+ requiredPorts: ["commands"],
13812
+ requiredContext: ["root", "stack"],
13813
+ answers: ["import_residual"],
13814
+ binding: importPartial
13815
+ },
13816
+ {
13817
+ id: "preview",
13818
+ label: "Preview",
13819
+ placement: "toolbar",
13820
+ requiredPorts: ["commands"],
13821
+ // `stack preview` plans the tf of the directory it runs in — a stack
13822
+ // alone isn't enough, the mount needs the root too.
13823
+ requiredContext: ["root", "stack"],
13824
+ binding: preview
13825
+ },
13826
+ {
13827
+ id: "run-cancel",
13828
+ label: "Cancel",
13829
+ placement: { row: "runs" },
13830
+ requiredPorts: ["commands"],
13831
+ requiredTarget: ["runId"],
13832
+ binding: runCancel
13833
+ },
13834
+ {
13835
+ id: "follow-logs",
13836
+ label: "Follow logs",
13837
+ placement: { row: "runs" },
13838
+ requiredPorts: ["commands"],
13839
+ requiredTarget: ["runId"],
13840
+ binding: followLogs
13596
13841
  }
13597
- return {
13598
- token,
13599
- outcome: { kind: "failed", message: error instanceof Error ? error.message : String(error) },
13600
- lastLog,
13601
- submitted,
13602
- phases
13603
- };
13604
- }
13605
- function reducePreview(_prev, token, event) {
13606
- return { token, data: event };
13607
- }
13608
- function reduceReport(prev, session, result) {
13609
- const fold = foldReport(prev?.sessions.get(session) ?? EMPTY_REPORT_FOLD, result);
13610
- return { sessions: new Map(prev?.sessions).set(session, fold) };
13611
- }
13612
- function reduceFollow(prev, token, event) {
13613
- const carried = prev && prev.token === token ? prev : null;
13614
- const runId = carried?.runId ?? "";
13615
- const lines = carried?.lines ?? [];
13616
- if (event.type === "log") return { token, runId, lines: [...lines, event.text], done: false };
13617
- return { token, runId, lines, done: true };
13618
- }
13619
- function createResultStore() {
13620
- let slots = {
13621
- run: null,
13622
- preview: null,
13623
- report: null,
13624
- follow: null
13625
- };
13626
- let tick = 0;
13627
- const listeners = /* @__PURE__ */ new Set();
13628
- const notify = () => {
13629
- for (const listener of listeners) listener();
13630
- };
13631
- const retiredTokens = /* @__PURE__ */ new WeakSet();
13632
- return {
13633
- getSnapshot() {
13634
- return slots;
13635
- },
13636
- getTick() {
13637
- return tick;
13638
- },
13639
- subscribe(listener) {
13640
- listeners.add(listener);
13641
- return () => listeners.delete(listener);
13642
- },
13643
- write(kind, token, value, readOver) {
13644
- if (retiredTokens.has(token)) return;
13645
- slots = { ...slots, [kind]: applySlot(kind, slots[kind], token, value, readOver) };
13646
- notify();
13647
- },
13648
- fail(kind, token, error) {
13649
- if (kind !== "run") return false;
13650
- if (retiredTokens.has(token) || !slots.run) return true;
13651
- slots = { ...slots, run: stamp(settleRun(slots.run, token, error), slots.run.readOver) };
13652
- notify();
13653
- return true;
13654
- },
13655
- begin(kind, token, readOver, target) {
13656
- if (kind === "run") {
13657
- slots = {
13658
- ...slots,
13659
- run: {
13660
- token,
13661
- outcome: { kind: "running" },
13662
- lastLog: null,
13663
- submitted: false,
13664
- phases: [],
13665
- readOver
13666
- }
13667
- };
13668
- } else if (kind === "follow") {
13669
- slots = {
13670
- ...slots,
13671
- follow: { token, runId: target.runId ?? "", lines: [], done: false, readOver }
13672
- };
13673
- } else {
13674
- return;
13675
- }
13676
- notify();
13677
- },
13678
- detach(kind, token) {
13679
- if (kind === "follow" && slots.follow?.token === token) {
13680
- slots = { ...slots, follow: null };
13681
- notify();
13682
- } else if (kind === "report" && slots.report?.sessions.has(token)) {
13683
- const sessions = new Map(slots.report.sessions);
13684
- sessions.delete(token);
13685
- slots = {
13686
- ...slots,
13687
- report: sessions.size > 0 ? { sessions, readOver: slots.report.readOver } : null
13688
- };
13689
- notify();
13690
- } else if (kind === "run" && slots.run?.token === token) {
13691
- const settled = settleRun(slots.run, token, new CommandDetachedError());
13692
- slots = { ...slots, run: stamp(settled, slots.run.readOver) };
13693
- notify();
13694
- }
13695
- retiredTokens.add(token);
13696
- },
13697
- isBusy(kind) {
13698
- return kind === "run" && slots.run?.outcome.kind === "running";
13699
- },
13700
- bumpTick() {
13701
- tick += 1;
13702
- notify();
13703
- }
13704
- };
13705
- }
13842
+ ];
13843
+ var CORE_COMMAND_ACTIONS = [
13844
+ ...STACK_COMMAND_ACTIONS,
13845
+ ...MODULE_COMMAND_ACTIONS
13846
+ ];
13706
13847
 
13707
13848
  // src/registry.ts
13708
13849
  var CONTEXT_NEEDS = {
@@ -13733,7 +13874,16 @@ var TARGET_NEEDS = {
13733
13874
  runId: "a run",
13734
13875
  failure: "a failed command"
13735
13876
  };
13736
- var BUSY_REASON = "A run is in progress";
13877
+ function busyReason(busy) {
13878
+ return busy.kind === "run" ? "A run is in progress" : `${busy.running.label} is running`;
13879
+ }
13880
+ function runsOn(action, ctx, target) {
13881
+ if (action.requiredTarget?.includes("runId")) return `run:${target.runId}`;
13882
+ const required = action.requiredContext ?? [];
13883
+ if (required.includes("stack")) return `stack:${ctx.stack?.id}`;
13884
+ if (required.includes("root")) return `root:${ctx.root}`;
13885
+ return "";
13886
+ }
13737
13887
  function keySatisfied(ctx, key) {
13738
13888
  if (key === "editable") return ctx.editable === true;
13739
13889
  if (key === "saved") return ctx.view?.unsaved === false;
@@ -13758,13 +13908,24 @@ function keySatisfied(ctx, key) {
13758
13908
  function contextSatisfied(ctx, required) {
13759
13909
  return required.every((key) => keySatisfied(ctx, key));
13760
13910
  }
13761
- function disabledReason(action, ctx, isBusy) {
13762
- if (isBusy) return BUSY_REASON;
13911
+ function disabledReason(action, ctx, busy) {
13912
+ if (busy) return busyReason(busy);
13763
13913
  for (const { key, reason } of action.enabledWhen ?? []) {
13764
13914
  if (!keySatisfied(ctx, key)) return reason;
13765
13915
  }
13766
13916
  return void 0;
13767
13917
  }
13918
+ function busyLabelOf(action, ctx, busy) {
13919
+ if (action.busy && keySatisfied(ctx, action.busy.when)) return action.busy.label;
13920
+ if (busy === void 0 || action.binding.kind !== "command") return void 0;
13921
+ return busy.kind === "run" || busy.running.path === action.binding.path ? action.label : void 0;
13922
+ }
13923
+ function actionState(action, ctx, busy) {
13924
+ return {
13925
+ disabledReason: disabledReason(action, ctx, busy),
13926
+ busyLabel: busyLabelOf(action, ctx, busy)
13927
+ };
13928
+ }
13768
13929
  function missingPort(ports, required) {
13769
13930
  return required.find((name) => ports[name] === void 0);
13770
13931
  }
@@ -13863,7 +14024,19 @@ function createActionRunner(ports, store, options = {}) {
13863
14024
  const handles = /* @__PURE__ */ new Map();
13864
14025
  const tokens = /* @__PURE__ */ new Map();
13865
14026
  const clipboard = createClipboardStore();
13866
- const notifyControllers = /* @__PURE__ */ new Set();
14027
+ const notifyControllers = /* @__PURE__ */ new Map();
14028
+ let edits = 0;
14029
+ const editingListeners = /* @__PURE__ */ new Set();
14030
+ async function asEdit(edit) {
14031
+ edits += 1;
14032
+ if (edits === 1) for (const listener of editingListeners) listener(true);
14033
+ try {
14034
+ return await edit();
14035
+ } finally {
14036
+ edits -= 1;
14037
+ if (edits === 0) for (const listener of editingListeners) listener(false);
14038
+ }
14039
+ }
13867
14040
  async function applyWith(editor, actions) {
13868
14041
  let result;
13869
14042
  try {
@@ -13903,13 +14076,14 @@ function createActionRunner(ports, store, options = {}) {
13903
14076
  async function applyActions(actions) {
13904
14077
  const editor = ports.editor;
13905
14078
  if (!editor) return;
13906
- return applyWith(editor, actions);
14079
+ return asEdit(() => applyWith(editor, actions));
13907
14080
  }
13908
14081
  function askConfirm(spec) {
13909
14082
  const confirm = ports.presenter.confirm;
13910
14083
  return confirm ? confirm(spec) : Promise.resolve(false);
13911
14084
  }
13912
- function runtimeFor(token, readOver, cwd, run, onSettle) {
14085
+ function runtimeFor(token, readOver, cwd, command, onSettle) {
14086
+ const run = command?.run;
13913
14087
  return {
13914
14088
  ports,
13915
14089
  token,
@@ -13920,7 +14094,7 @@ function createActionRunner(ports, store, options = {}) {
13920
14094
  if (run && line !== void 0) options.onRunLog?.(line, run);
13921
14095
  },
13922
14096
  begin: () => {
13923
- if (run) store.begin(run.resultKind, token, readOver, run.target);
14097
+ if (command) store.begin(command.run.resultKind, token, readOver, command.started);
13924
14098
  },
13925
14099
  fail: (error) => run ? store.fail(run.resultKind, token, error) : false,
13926
14100
  detach: (kind, tok) => store.detach(kind, tok),
@@ -13931,6 +14105,15 @@ function createActionRunner(ports, store, options = {}) {
13931
14105
  function readOverOf(ctx) {
13932
14106
  return { stack: ctx.stack?.id };
13933
14107
  }
14108
+ function busyOn(resultKind, action, ctx, target) {
14109
+ const on = runsOn(action, ctx, target);
14110
+ return { on, busy: store.busy(resultKind, on) };
14111
+ }
14112
+ function busyOf(action, ctx, target) {
14113
+ const binding = action.binding;
14114
+ if (binding.kind !== "command") return void 0;
14115
+ return busyOn(binding.resultKind, action, ctx, target).busy;
14116
+ }
13934
14117
  function cwdOf(action, ctx) {
13935
14118
  return (action.requiredContext ?? []).includes("root") ? ctx.root : void 0;
13936
14119
  }
@@ -13952,19 +14135,24 @@ function createActionRunner(ports, store, options = {}) {
13952
14135
  if (binding.kind !== "command") return;
13953
14136
  const spec = binding.confirmSpec(ctx, target, formArgs);
13954
14137
  if (spec && !await askConfirm(spec)) return;
13955
- if (store.isBusy(binding.resultKind)) {
13956
- ports.presenter.notify("warn", BUSY_REASON);
14138
+ const { on, busy } = busyOn(binding.resultKind, action, ctx, target);
14139
+ if (busy) {
14140
+ ports.presenter.notify("warn", busyReason(busy));
13957
14141
  return;
13958
14142
  }
13959
14143
  const readOver = readOverOf(ctx);
13960
14144
  const cwd = cwdOf(action, ctx);
13961
14145
  const token = {};
13962
14146
  const run = { token, path: binding.path, resultKind: binding.resultKind, ctx, target };
14147
+ const started = { target, on, path: binding.path, label: action.label };
13963
14148
  const controller = new AbortController();
13964
14149
  if (binding.resultKind === "notify") {
13965
- notifyControllers.add(controller);
14150
+ notifyControllers.set(controller, token);
13966
14151
  await binding.start(
13967
- runtimeFor(token, readOver, cwd, run, () => notifyControllers.delete(controller)),
14152
+ runtimeFor(token, readOver, cwd, { run, started }, () => {
14153
+ notifyControllers.delete(controller);
14154
+ store.detach("notify", token);
14155
+ }),
13968
14156
  ctx,
13969
14157
  target,
13970
14158
  formArgs,
@@ -13976,7 +14164,7 @@ function createActionRunner(ports, store, options = {}) {
13976
14164
  controllers.set(binding.resultKind, controller);
13977
14165
  tokens.set(binding.resultKind, token);
13978
14166
  const handle = await binding.start(
13979
- runtimeFor(token, readOver, cwd, run),
14167
+ runtimeFor(token, readOver, cwd, { run, started }),
13980
14168
  ctx,
13981
14169
  target,
13982
14170
  formArgs,
@@ -14025,7 +14213,7 @@ function createActionRunner(ports, store, options = {}) {
14025
14213
  ...envExtras
14026
14214
  };
14027
14215
  if (binding.result === "apply") {
14028
- return binding.run(env);
14216
+ return asEdit(() => binding.run(env));
14029
14217
  }
14030
14218
  if (binding.result === "generate") {
14031
14219
  for await (const event of binding.run(env)) {
@@ -14053,8 +14241,7 @@ function createActionRunner(ports, store, options = {}) {
14053
14241
  ports.presenter.notify("warn", unmet);
14054
14242
  return;
14055
14243
  }
14056
- const isBusy = action.binding.kind === "command" && store.isBusy(action.binding.resultKind);
14057
- const reason = disabledReason(action, ctx, isBusy);
14244
+ const reason = disabledReason(action, ctx, busyOf(action, ctx, target));
14058
14245
  if (reason !== void 0) {
14059
14246
  ports.presenter.notify("warn", reason);
14060
14247
  return;
@@ -14081,6 +14268,18 @@ function createActionRunner(ports, store, options = {}) {
14081
14268
  apply(actions) {
14082
14269
  return applyActions(actions);
14083
14270
  },
14271
+ editing() {
14272
+ return edits > 0;
14273
+ },
14274
+ onEditingChange(listener) {
14275
+ editingListeners.add(listener);
14276
+ return () => {
14277
+ editingListeners.delete(listener);
14278
+ };
14279
+ },
14280
+ busy(action, ctx, target) {
14281
+ return busyOf(action, ctx, target);
14282
+ },
14084
14283
  async cancel(kind) {
14085
14284
  const handle = handles.get(kind);
14086
14285
  if (!handle) return;
@@ -14092,7 +14291,10 @@ function createActionRunner(ports, store, options = {}) {
14092
14291
  },
14093
14292
  dispose() {
14094
14293
  for (const kind of [...controllers.keys()]) detachSlot(kind);
14095
- for (const controller of notifyControllers) controller.abort();
14294
+ for (const [controller, token] of notifyControllers) {
14295
+ controller.abort();
14296
+ store.detach("notify", token);
14297
+ }
14096
14298
  notifyControllers.clear();
14097
14299
  }
14098
14300
  };
@@ -14190,6 +14392,7 @@ export {
14190
14392
  diagnosticsOf,
14191
14393
  keySatisfied,
14192
14394
  disabledReason,
14395
+ actionState,
14193
14396
  answering,
14194
14397
  resolveContributions,
14195
14398
  rowActions,
@@ -14210,10 +14413,6 @@ export {
14210
14413
  parseBound,
14211
14414
  carriesFailure,
14212
14415
  parseCommandFailure,
14213
- defineCommand,
14214
- MODULE_COMMAND_ACTIONS,
14215
- CORE_COMMAND_ACTIONS,
14216
- isPlainObject,
14217
14416
  EMPTY_REPORT_FOLD,
14218
14417
  foldReport,
14219
14418
  currentReport,
@@ -14221,11 +14420,16 @@ export {
14221
14420
  reportDiagnostics,
14222
14421
  liveSlots,
14223
14422
  reduceRun,
14423
+ failureSays,
14224
14424
  settleRun,
14225
14425
  reducePreview,
14226
14426
  reduceReport,
14227
14427
  reduceFollow,
14228
14428
  createResultStore,
14429
+ defineCommand,
14430
+ MODULE_COMMAND_ACTIONS,
14431
+ CORE_COMMAND_ACTIONS,
14432
+ isPlainObject,
14229
14433
  createActionRunner,
14230
14434
  connectCaller,
14231
14435
  bridgeCaller,
@@ -14234,4 +14438,4 @@ export {
14234
14438
  AutosaveEndedError,
14235
14439
  autosave
14236
14440
  };
14237
- //# sourceMappingURL=chunk-YLJWYH7B.mjs.map
14441
+ //# sourceMappingURL=chunk-ID563WHD.mjs.map