@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.
@@ -43,6 +43,7 @@ __export(engine_exports, {
43
43
  defineCommand: () => defineCommand,
44
44
  diagnosticsOf: () => diagnosticsOf,
45
45
  diagnosticsOfDocument: () => diagnosticsOfDocument,
46
+ failureSays: () => failureSays,
46
47
  foldReport: () => foldReport,
47
48
  isBoundPath: () => isBoundPath,
48
49
  liveSlots: () => liveSlots,
@@ -3607,7 +3608,7 @@ function conflictChoiceToJSON(object) {
3607
3608
  }
3608
3609
  }
3609
3610
  function createBaseReasonDetail() {
3610
- return { reason: 0, api_code: "" };
3611
+ return { reason: 0, api_code: "", request_id: "" };
3611
3612
  }
3612
3613
  var ReasonDetail = {
3613
3614
  encode(message, writer = new import_wire4.BinaryWriter()) {
@@ -3617,6 +3618,9 @@ var ReasonDetail = {
3617
3618
  if (message.api_code !== "") {
3618
3619
  writer.uint32(18).string(message.api_code);
3619
3620
  }
3621
+ if (message.request_id !== "") {
3622
+ writer.uint32(26).string(message.request_id);
3623
+ }
3620
3624
  return writer;
3621
3625
  },
3622
3626
  decode(input, length) {
@@ -3640,6 +3644,13 @@ var ReasonDetail = {
3640
3644
  message.api_code = reader.string();
3641
3645
  continue;
3642
3646
  }
3647
+ case 3: {
3648
+ if (tag !== 26) {
3649
+ break;
3650
+ }
3651
+ message.request_id = reader.string();
3652
+ continue;
3653
+ }
3643
3654
  }
3644
3655
  if ((tag & 7) === 4 || tag === 0) {
3645
3656
  break;
@@ -3651,7 +3662,8 @@ var ReasonDetail = {
3651
3662
  fromJSON(object) {
3652
3663
  return {
3653
3664
  reason: isSet3(object.reason) ? reasonFromJSON(object.reason) : 0,
3654
- api_code: isSet3(object.apiCode) ? globalThis.String(object.apiCode) : isSet3(object.api_code) ? globalThis.String(object.api_code) : ""
3665
+ api_code: isSet3(object.apiCode) ? globalThis.String(object.apiCode) : isSet3(object.api_code) ? globalThis.String(object.api_code) : "",
3666
+ request_id: isSet3(object.requestId) ? globalThis.String(object.requestId) : isSet3(object.request_id) ? globalThis.String(object.request_id) : ""
3655
3667
  };
3656
3668
  },
3657
3669
  toJSON(message) {
@@ -3662,6 +3674,9 @@ var ReasonDetail = {
3662
3674
  if (message.api_code !== "") {
3663
3675
  obj.apiCode = message.api_code;
3664
3676
  }
3677
+ if (message.request_id !== "") {
3678
+ obj.requestId = message.request_id;
3679
+ }
3665
3680
  return obj;
3666
3681
  },
3667
3682
  create(base) {
@@ -3671,6 +3686,7 @@ var ReasonDetail = {
3671
3686
  const message = createBaseReasonDetail();
3672
3687
  message.reason = object.reason ?? 0;
3673
3688
  message.api_code = object.api_code ?? "";
3689
+ message.request_id = object.request_id ?? "";
3674
3690
  return message;
3675
3691
  }
3676
3692
  };
@@ -8029,7 +8045,7 @@ var InvokeRequest = {
8029
8045
  }
8030
8046
  };
8031
8047
  function createBaseInvokeEvent() {
8032
- return { json: void 0, exit: void 0 };
8048
+ return { json: void 0, exit: void 0, started: void 0 };
8033
8049
  }
8034
8050
  var InvokeEvent = {
8035
8051
  encode(message, writer = new import_wire4.BinaryWriter()) {
@@ -8039,6 +8055,9 @@ var InvokeEvent = {
8039
8055
  if (message.exit !== void 0) {
8040
8056
  InvokeExit.encode(message.exit, writer.uint32(18).fork()).join();
8041
8057
  }
8058
+ if (message.started !== void 0) {
8059
+ InvokeStarted.encode(message.started, writer.uint32(26).fork()).join();
8060
+ }
8042
8061
  return writer;
8043
8062
  },
8044
8063
  decode(input, length) {
@@ -8062,6 +8081,13 @@ var InvokeEvent = {
8062
8081
  message.exit = InvokeExit.decode(reader, reader.uint32());
8063
8082
  continue;
8064
8083
  }
8084
+ case 3: {
8085
+ if (tag !== 26) {
8086
+ break;
8087
+ }
8088
+ message.started = InvokeStarted.decode(reader, reader.uint32());
8089
+ continue;
8090
+ }
8065
8091
  }
8066
8092
  if ((tag & 7) === 4 || tag === 0) {
8067
8093
  break;
@@ -8073,7 +8099,8 @@ var InvokeEvent = {
8073
8099
  fromJSON(object) {
8074
8100
  return {
8075
8101
  json: isSet3(object.json) ? globalThis.String(object.json) : void 0,
8076
- exit: isSet3(object.exit) ? InvokeExit.fromJSON(object.exit) : void 0
8102
+ exit: isSet3(object.exit) ? InvokeExit.fromJSON(object.exit) : void 0,
8103
+ started: isSet3(object.started) ? InvokeStarted.fromJSON(object.started) : void 0
8077
8104
  };
8078
8105
  },
8079
8106
  toJSON(message) {
@@ -8084,6 +8111,9 @@ var InvokeEvent = {
8084
8111
  if (message.exit !== void 0) {
8085
8112
  obj.exit = InvokeExit.toJSON(message.exit);
8086
8113
  }
8114
+ if (message.started !== void 0) {
8115
+ obj.started = InvokeStarted.toJSON(message.started);
8116
+ }
8087
8117
  return obj;
8088
8118
  },
8089
8119
  create(base) {
@@ -8093,6 +8123,44 @@ var InvokeEvent = {
8093
8123
  const message = createBaseInvokeEvent();
8094
8124
  message.json = object.json ?? void 0;
8095
8125
  message.exit = object.exit !== void 0 && object.exit !== null ? InvokeExit.fromPartial(object.exit) : void 0;
8126
+ message.started = object.started !== void 0 && object.started !== null ? InvokeStarted.fromPartial(object.started) : void 0;
8127
+ return message;
8128
+ }
8129
+ };
8130
+ function createBaseInvokeStarted() {
8131
+ return {};
8132
+ }
8133
+ var InvokeStarted = {
8134
+ encode(_, writer = new import_wire4.BinaryWriter()) {
8135
+ return writer;
8136
+ },
8137
+ decode(input, length) {
8138
+ const reader = input instanceof import_wire4.BinaryReader ? input : new import_wire4.BinaryReader(input);
8139
+ const end = length === void 0 ? reader.len : reader.pos + length;
8140
+ const message = createBaseInvokeStarted();
8141
+ while (reader.pos < end) {
8142
+ const tag = reader.uint32();
8143
+ switch (tag >>> 3) {
8144
+ }
8145
+ if ((tag & 7) === 4 || tag === 0) {
8146
+ break;
8147
+ }
8148
+ reader.skip(tag & 7);
8149
+ }
8150
+ return message;
8151
+ },
8152
+ fromJSON(_) {
8153
+ return {};
8154
+ },
8155
+ toJSON(_) {
8156
+ const obj = {};
8157
+ return obj;
8158
+ },
8159
+ create(base) {
8160
+ return InvokeStarted.fromPartial(base ?? {});
8161
+ },
8162
+ fromPartial(_) {
8163
+ const message = createBaseInvokeStarted();
8096
8164
  return message;
8097
8165
  }
8098
8166
  };
@@ -10371,8 +10439,9 @@ var LaceEngineDefinition = {
10371
10439
  options: {}
10372
10440
  },
10373
10441
  /**
10374
- * Runs one CLI command in-process against a fresh command tree. The command's `-o json` output is the stream:
10375
- * each top-level JSON value on stdout is one `json` event; `exit` is always last.
10442
+ * Runs one CLI command in-process against a fresh command tree. `started` is first, once the engine has accepted
10443
+ * the request and before the command runs; the command's `-o json` output follows: each top-level JSON value on
10444
+ * stdout is one `json` event; `exit` is always last.
10376
10445
  */
10377
10446
  invoke: {
10378
10447
  name: "Invoke",
@@ -10447,6 +10516,7 @@ function isSet3(value) {
10447
10516
  }
10448
10517
 
10449
10518
  // src/ports.ts
10519
+ var import_proto = require("@lace-cloud/proto");
10450
10520
  var ApplyUnobservedError = class extends Error {
10451
10521
  constructor(end) {
10452
10522
  super(`unobserved: the source stopped (${end.kind}) before the frame that carries the write`);
@@ -10466,7 +10536,9 @@ var ConnectError = class extends Error {
10466
10536
  super(`[${code}] ${message}`);
10467
10537
  this.code = code;
10468
10538
  this.reason = detail.reason;
10469
- this.apiCode = detail.api_code === "" ? void 0 : detail.api_code;
10539
+ const { apiCode, requestId } = (0, import_proto.apiFields)(detail);
10540
+ this.apiCode = apiCode;
10541
+ this.requestId = requestId;
10470
10542
  this.name = "ConnectError";
10471
10543
  }
10472
10544
  };
@@ -10743,7 +10815,8 @@ function parseBridgeResponse(raw) {
10743
10815
  return null;
10744
10816
  }
10745
10817
  const apiCode = "apiCode" in raw && typeof raw.apiCode === "string" ? raw.apiCode : void 0;
10746
- return { kind, id, code, message, reason, apiCode };
10818
+ const requestId = "requestId" in raw && typeof raw.requestId === "string" ? raw.requestId : void 0;
10819
+ return { kind, id, code, message, reason, apiCode, requestId };
10747
10820
  }
10748
10821
  return null;
10749
10822
  }
@@ -10751,7 +10824,11 @@ function frameError(frame) {
10751
10824
  return new ConnectError(
10752
10825
  frame.code,
10753
10826
  frame.message,
10754
- ReasonDetail.fromJSON({ reason: frame.reason, api_code: frame.apiCode })
10827
+ ReasonDetail.fromJSON({
10828
+ reason: frame.reason,
10829
+ api_code: frame.apiCode,
10830
+ request_id: frame.requestId
10831
+ })
10755
10832
  );
10756
10833
  }
10757
10834
  function bridgeCaller(bridge) {
@@ -10836,7 +10913,7 @@ function bridgeCaller(bridge) {
10836
10913
  }
10837
10914
 
10838
10915
  // src/adapters/engine/mapping.ts
10839
- var import_proto = require("@lace-cloud/proto");
10916
+ var import_proto2 = require("@lace-cloud/proto");
10840
10917
 
10841
10918
  // src/contracts/commands.gen.ts
10842
10919
  var COMMANDS = {
@@ -12172,7 +12249,8 @@ var commandFailureSchema = import_zod.z.strictObject({
12172
12249
  tool: import_zod.z.string().optional(),
12173
12250
  importResiduals: import_zod.z.array(importResidualSchema).optional(),
12174
12251
  addresses: import_zod.z.array(import_zod.z.string()).optional(),
12175
- apiCode: import_zod.z.string().optional()
12252
+ apiCode: import_zod.z.string().optional(),
12253
+ requestId: import_zod.z.string().optional()
12176
12254
  });
12177
12255
  var moduleValidateDeviationSchema = import_zod.z.object({
12178
12256
  notCompositional: import_zod.z.boolean(),
@@ -12611,6 +12689,7 @@ var stackScanSchema = import_zod.z.object({
12611
12689
  driftCount: import_zod.z.number(),
12612
12690
  scannedAt: import_zod.z.string(),
12613
12691
  undeterminedReason: import_zod.z.string().nullable(),
12692
+ undeterminedMessage: import_zod.z.string().nullable(),
12614
12693
  standingDriftFindings: import_zod.z.number(),
12615
12694
  footprintDestroyed: import_zod.z.boolean(),
12616
12695
  drift: driftSchema
@@ -12781,9 +12860,9 @@ function isolated(report) {
12781
12860
  async function initialize(caller) {
12782
12861
  const initialize2 = await caller.unary("Initialize", {
12783
12862
  client_version: "@lace-cloud/canvas",
12784
- protocol_version: import_proto.ENGINE_PROTOCOL_VERSION
12863
+ protocol_version: import_proto2.ENGINE_PROTOCOL_VERSION
12785
12864
  });
12786
- (0, import_proto.checkEngineProtocol)(initialize2.server_version, initialize2.protocol_version);
12865
+ (0, import_proto2.checkEngineProtocol)(initialize2.server_version, initialize2.protocol_version);
12787
12866
  return new Set(initialize2.command_paths);
12788
12867
  }
12789
12868
  async function openEngineCommands(caller, { cwd }) {
@@ -12808,7 +12887,7 @@ async function openEngineSession(caller, target, options = {}) {
12808
12887
  let stopped = null;
12809
12888
  const revisionWaiters = /* @__PURE__ */ new Set();
12810
12889
  function adopt(state) {
12811
- const published = state.bundle ?? import_proto.EMPTY_BUNDLE;
12890
+ const published = state.bundle ?? import_proto2.EMPTY_BUNDLE;
12812
12891
  const bundle = currentSource && deepEqual(currentSource.bundle, published) ? currentSource.bundle : published;
12813
12892
  sessionGenerating = state.generating;
12814
12893
  currentSource = {
@@ -12820,7 +12899,7 @@ async function openEngineSession(caller, target, options = {}) {
12820
12899
  conflict: state.conflict ? { baseTreeHash: state.conflict.base_tree_hash, treeHash: state.conflict.tree_hash } : null,
12821
12900
  sourceRefused: state.source_refused,
12822
12901
  generating: generating(),
12823
- diagnostics: state.diagnostics.map(import_proto.convertDiagnostic),
12902
+ diagnostics: state.diagnostics.map(import_proto2.convertDiagnostic),
12824
12903
  treeHash: state.tree_hash
12825
12904
  };
12826
12905
  for (const listener of sourceListeners) deliver(listener, currentSource);
@@ -13003,7 +13082,7 @@ function commandsPort(caller, commandPaths, ownCwd) {
13003
13082
  working_directory: cwd
13004
13083
  };
13005
13084
  async function* run() {
13006
- for await (const event of caller.stream("Invoke", request, signal)) {
13085
+ for await (const event of untilExit()) {
13007
13086
  if (event.json !== void 0) {
13008
13087
  const data = JSON.parse(event.json);
13009
13088
  if (carriesFailure(data)) continue;
@@ -13021,8 +13100,28 @@ function commandsPort(caller, commandPaths, ownCwd) {
13021
13100
  return;
13022
13101
  }
13023
13102
  }
13024
- if (signal.aborted) throw new CommandDetachedError();
13025
- throw new CommandUnobservedError();
13103
+ }
13104
+ async function* untilExit() {
13105
+ let started = false;
13106
+ const stopped = (error) => {
13107
+ if (signal.aborted) return new CommandDetachedError();
13108
+ if (started) return new CommandUnobservedError();
13109
+ return error;
13110
+ };
13111
+ try {
13112
+ for await (const event of caller.stream("Invoke", request, signal)) {
13113
+ started || (started = event.started !== void 0);
13114
+ yield event;
13115
+ }
13116
+ } catch (error) {
13117
+ throw stopped(error);
13118
+ }
13119
+ throw stopped(
13120
+ new ConnectError(
13121
+ "internal",
13122
+ "the engine ended the Invoke stream before it started the command"
13123
+ )
13124
+ );
13026
13125
  }
13027
13126
  return {
13028
13127
  events: run(),
@@ -13096,407 +13195,71 @@ function convertCreatedRef(r) {
13096
13195
  return { scope: r.scope, id: r.id, moduleKey: r.module_key, sourceId: r.source_id };
13097
13196
  }
13098
13197
 
13099
- // src/core/define-command.ts
13100
- function errorNotice(err) {
13101
- if (err instanceof CommandExitError) {
13102
- return err.failure ? [err.stderrTail, err.failure] : [err.stderrTail];
13103
- }
13104
- if (err instanceof Error) return [err.message];
13105
- return [String(err)];
13198
+ // src/core/diagnostics.ts
13199
+ var NOT_LACE_SHAPE = "not_lace_shape";
13200
+ function holdsLaceShapeRefusal(diagnostics) {
13201
+ return diagnostics.some((d) => d.code === NOT_LACE_SHAPE);
13106
13202
  }
13107
- function defineCommand(binding) {
13108
- return {
13109
- kind: "command",
13110
- path: binding.path,
13111
- confirms: binding.confirm !== void 0,
13112
- resultKind: binding.result.kind,
13113
- invalidates: binding.invalidates,
13114
- partialArgs(ctx, target) {
13115
- return binding.args(ctx, target);
13116
- },
13117
- confirmSpec(ctx, target, formArgs) {
13118
- if (!binding.confirm) return void 0;
13119
- const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13120
- if (!merged.ok) return void 0;
13121
- return binding.confirm(ctx, merged.args, target);
13122
- },
13123
- async start(rt, ctx, target, formArgs, signal) {
13124
- const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13125
- if (!merged.ok) return null;
13126
- const commands = rt.ports.commands;
13127
- if (!commands) return null;
13128
- const invocation = commands.invoke(binding.path, merged.args, signal, rt.cwd);
13129
- rt.begin();
13130
- if (binding.invalidates === "start+settle") rt.tick();
13131
- void (async () => {
13132
- try {
13133
- for await (const event of invocation.events) {
13134
- binding.result.consume(rt, event);
13135
- }
13136
- if (binding.invalidates) rt.tick();
13137
- } catch (err) {
13138
- if (!rt.fail(err) && !(err instanceof CommandDetachedError)) {
13139
- rt.ports.presenter.notify("error", ...errorNotice(err));
13140
- }
13141
- if (binding.invalidates) rt.tick();
13142
- } finally {
13143
- rt.settled?.();
13144
- }
13145
- })();
13146
- return { cancel: () => invocation.cancel() };
13147
- }
13148
- };
13203
+ function findingKey(d) {
13204
+ return JSON.stringify([
13205
+ d.file,
13206
+ d.line,
13207
+ d.message,
13208
+ d.module_key,
13209
+ d.instance_id,
13210
+ d.input_name,
13211
+ d.address
13212
+ ]);
13149
13213
  }
13150
-
13151
- // src/core/actions.ts
13152
- function slotSink(kind) {
13153
- return { kind, consume: (rt, e) => rt.write(kind, rt.token, e) };
13214
+ function uniqueDiagnostics(diagnostics) {
13215
+ const seen = /* @__PURE__ */ new Set();
13216
+ return diagnostics.filter((d) => {
13217
+ const key = findingKey(d);
13218
+ if (seen.has(key)) return false;
13219
+ seen.add(key);
13220
+ return true;
13221
+ });
13154
13222
  }
13155
- var apply = defineCommand({
13156
- kind: "command",
13157
- path: "stack apply",
13158
- args: (ctx) => ({ stack: ctx.stack?.id }),
13159
- // The run sink ticks at both start and settle, so a read keyed on the
13160
- // tick (a host's run list, the describe overlay) sees the in-flight run
13161
- // as soon as it starts, not only once it ends.
13162
- invalidates: "start+settle",
13163
- result: slotSink("run")
13164
- });
13165
- var destroy = defineCommand({
13166
- kind: "command",
13167
- path: "stack destroy",
13168
- args: (ctx) => ({ stack: ctx.stack?.id, yes: true }),
13169
- // The typed confirmation is the stack's slug — the human-facing name a
13170
- // user actually reads off the host's stack list — never its id, which
13171
- // `args.stack` carries for the command itself but nobody types from
13172
- // memory.
13173
- confirm: (ctx) => ({
13174
- text: `Destroy ${ctx.stack?.slug}? This runs terraform destroy on the runner.`,
13175
- typed: ctx.stack?.slug
13176
- }),
13177
- invalidates: "start+settle",
13178
- result: slotSink("run")
13179
- });
13180
- function scanNotice(e) {
13181
- const { slug } = e.stack;
13182
- const settled = e.settled;
13183
- if (!settled) {
13184
- return e.triggered ? `Drift scan triggered for stack ${slug} (${e.stack.id}).` : `Drift scan already in progress for stack ${slug}.`;
13185
- }
13186
- if (settled.undeterminedReason !== null) return void 0;
13187
- if (settled.footprintDestroyed) {
13188
- return `Drift scan complete for stack ${slug}: IN_SYNC (0 drifted) \u2014 its resources were destroyed, so there was nothing to compare.`;
13189
- }
13190
- if (settled.standingDriftFindings > 0) {
13191
- 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.`;
13192
- }
13193
- return `Drift scan complete for stack ${slug}: ${settled.driftStatus} (${settled.driftCount} drifted).`;
13223
+ function diagnosticsOf(sourceDiagnostics, reportFindings) {
13224
+ return uniqueDiagnostics([...sourceDiagnostics, ...reportFindings]);
13194
13225
  }
13195
- var scan = defineCommand({
13196
- kind: "command",
13197
- path: "stack scan",
13198
- args: (ctx) => ({ stack: ctx.stack?.id, wait: true }),
13199
- invalidates: true,
13200
- result: {
13201
- kind: "notify",
13202
- consume: (rt, e) => {
13203
- const notice = scanNotice(e);
13204
- if (notice !== void 0) rt.ports.presenter.notify("info", notice);
13205
- }
13226
+
13227
+ // src/core/report-fold.ts
13228
+ var REPORT_PATHS = ["module validate", "module convert", "module scan"];
13229
+ var FOLDS_AS = new Map([
13230
+ ...REPORT_PATHS.map((path) => [path, path]),
13231
+ ["stack import", "module convert"]
13232
+ ]);
13233
+ var EMPTY_REPORT_FOLD = /* @__PURE__ */ new Map();
13234
+ function readEntry(path, exitCode, data) {
13235
+ if (carriesFailure(data)) {
13236
+ return { kind: "failure", path, exitCode, failure: parseCommandFailure(data) };
13206
13237
  }
13207
- });
13208
- var create = defineCommand({
13209
- kind: "command",
13210
- path: "stack create",
13211
- args: (ctx) => ({ source: ctx.root }),
13212
- invalidates: true,
13213
- result: {
13214
- kind: "notify",
13215
- consume: (rt, e) => rt.ports.presenter.notify("info", `Created stack ${e.slug}`)
13238
+ switch (path) {
13239
+ case "module validate":
13240
+ return { kind: "result", path, exitCode, document: parseBound(path, data) };
13241
+ case "module convert":
13242
+ return { kind: "result", path, exitCode, document: parseBound(path, data) };
13243
+ case "module scan":
13244
+ return { kind: "result", path, exitCode, document: parseBound(path, data) };
13216
13245
  }
13217
- });
13218
- function residualAddresses(residuals) {
13219
- return residuals.map((r) => r.address).join(", ");
13220
13246
  }
13221
- function treeChanges(e) {
13222
- return [
13223
- ...e.written.length === 0 ? [] : [`rewriting ${e.written.join(", ")} in place`],
13224
- ...e.removed.length === 0 ? [] : [`removing ${e.removed.join(", ")}`]
13225
- ];
13247
+ function foldReport(prev, result) {
13248
+ const path = FOLDS_AS.get(result.path);
13249
+ if (path === void 0) return prev;
13250
+ const next = new Map(prev);
13251
+ if (result.document === "") next.delete(path);
13252
+ else next.set(path, readEntry(path, result.exitCode, JSON.parse(result.document)));
13253
+ return next;
13226
13254
  }
13227
- function importNotice(e) {
13228
- const { slug } = e.stack;
13229
- const changes = treeChanges(e);
13230
- const files = changes.length > 0 ? `, ${changes.join(" and ")}` : "";
13231
- const imported = `Imported ${e.importBlocks} resource(s) into ${slug}${files}.`;
13232
- if (e.validate.exitClass !== "ok") {
13233
- return ["warn", `${imported} The tree did not validate: fix it before you commit it.`];
13234
- }
13235
- const adopt = e.changed ? ` Review the change in git, commit it, then apply ${slug} to adopt them.` : "";
13236
- if (e.importResiduals.length === 0) return ["info", `${imported}${adopt}`];
13237
- return [
13238
- "warn",
13239
- `${imported}${adopt} Not adopted: ${residualAddresses(e.importResiduals)}; supply their import ids before applying, or the apply creates them anew.`
13240
- ];
13241
- }
13242
- var importResult = {
13243
- kind: "notify",
13244
- consume: (rt, e) => rt.ports.presenter.notify(...importNotice(e))
13245
- };
13246
- var importStack = defineCommand({
13247
- kind: "command",
13248
- path: "stack import",
13249
- args: (ctx) => ({ stack: ctx.stack?.id }),
13250
- invalidates: true,
13251
- result: importResult
13252
- });
13253
- var importPartial = defineCommand({
13254
- kind: "command",
13255
- path: "stack import",
13256
- args: (ctx) => ({ stack: ctx.stack?.id, allowPartial: true }),
13257
- confirm: (ctx, _args, target) => ({
13258
- 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.`
13259
- }),
13260
- invalidates: true,
13261
- result: importResult
13262
- });
13263
- var validate = defineCommand({
13264
- kind: "command",
13265
- path: "module validate",
13266
- args: () => ({}),
13267
- result: {
13268
- kind: "notify",
13269
- consume: (rt, e) => {
13270
- if (e.exitClass === "ok") rt.ports.presenter.notify("info", `Valid for Lace \u2014 ${e.verdict}`);
13271
- }
13272
- }
13273
- });
13274
- var convert = defineCommand({
13275
- kind: "command",
13276
- path: "module convert",
13277
- args: () => ({}),
13278
- result: {
13279
- kind: "notify",
13280
- consume: (rt, e) => rt.ports.presenter.notify(
13281
- "info",
13282
- e.changed ? `Converted \u2014 ${e.written.length} file(s) written` : "Already lace-style \u2014 nothing to write"
13283
- )
13284
- }
13285
- });
13286
- var preview = defineCommand({
13287
- kind: "command",
13288
- path: "stack preview",
13289
- args: (ctx) => ({ stack: ctx.stack?.id }),
13290
- result: slotSink("preview")
13291
- });
13292
- var runCancel = defineCommand({
13293
- kind: "command",
13294
- path: "run cancel",
13295
- args: (_ctx, target) => ({ run: target.runId }),
13296
- invalidates: true,
13297
- result: {
13298
- kind: "notify",
13299
- consume: (rt, e) => rt.ports.presenter.notify("info", `Run ${e.id} ${e.status}`)
13300
- }
13301
- });
13302
- var followLogs = defineCommand({
13303
- kind: "command",
13304
- path: "run logs",
13305
- args: (_ctx, target) => ({ run: target.runId, follow: true }),
13306
- result: slotSink("follow")
13307
- });
13308
- var MODULE_COMMAND_ACTIONS = [
13309
- {
13310
- id: "validate",
13311
- label: "Validate",
13312
- icon: "validate",
13313
- section: "check",
13314
- placement: "toolbar",
13315
- requiredPorts: ["commands"],
13316
- requiredContext: ["root"],
13317
- binding: validate
13318
- },
13319
- {
13320
- id: "convert",
13321
- label: "Convert",
13322
- icon: "convert",
13323
- section: "check",
13324
- placement: "toolbar",
13325
- requiredPorts: ["commands"],
13326
- requiredContext: ["root"],
13327
- binding: convert
13328
- },
13329
- // Convert on the source-refused banner while the tree is out of lace
13330
- // shape: the same `module convert` the toolbar runs, and the choice the
13331
- // banner says of it. The engine re-derives the tree it writes, which
13332
- // accepts it and lifts the lock.
13333
- {
13334
- id: "convert-refused",
13335
- label: "Convert",
13336
- choice: "Convert restructures it in place; a stack's apply creates only what its state does not hold yet.",
13337
- icon: "convert",
13338
- placement: { row: "source-refused" },
13339
- requiredPorts: ["commands"],
13340
- requiredContext: ["root", "needsConversion"],
13341
- binding: convert
13342
- }
13343
- ];
13344
- var STACK_COMMAND_ACTIONS = [
13345
- {
13346
- id: "apply",
13347
- label: "Apply",
13348
- placement: "toolbar",
13349
- requiredPorts: ["commands"],
13350
- // `stack apply` gates on the tf and certification of the directory it
13351
- // runs in (submit.Prepare(env.Root)) before it ever reaches the
13352
- // runner, so a mount with no root can't run it even with a stack
13353
- // chosen — the same root gate `validate`/`convert` need. It ships
13354
- // whatever tf is on disk, not the canvas's own working IR.
13355
- requiredContext: ["root", "stack"],
13356
- binding: apply
13357
- },
13358
- {
13359
- id: "destroy",
13360
- label: "Destroy",
13361
- placement: "toolbar",
13362
- requiredPorts: ["commands"],
13363
- // `stack destroy` shares the CLI's `executeRun` with `stack apply` and
13364
- // runs under `env.Root`, so it needs the identical context tuple.
13365
- requiredContext: ["root", "stack"],
13366
- binding: destroy
13367
- },
13368
- {
13369
- id: "scan",
13370
- label: "Scan for drift",
13371
- placement: "toolbar",
13372
- requiredPorts: ["commands"],
13373
- requiredContext: ["stack"],
13374
- binding: scan
13375
- },
13376
- {
13377
- id: "create",
13378
- label: "Create stack",
13379
- placement: "toolbar",
13380
- requiredPorts: ["commands"],
13381
- requiredContext: ["root"],
13382
- binding: create
13383
- },
13384
- {
13385
- id: "import",
13386
- label: "Import existing resources",
13387
- placement: "toolbar",
13388
- requiredPorts: ["commands"],
13389
- // `stack import` writes the directory it runs in, the same way
13390
- // Convert does.
13391
- requiredContext: ["root", "stack"],
13392
- binding: importStack
13393
- },
13394
- {
13395
- id: "import-partial",
13396
- label: "Import the rest",
13397
- placement: { row: "failure" },
13398
- requiredPorts: ["commands"],
13399
- requiredContext: ["root", "stack"],
13400
- answers: ["import_residual"],
13401
- binding: importPartial
13402
- },
13403
- {
13404
- id: "preview",
13405
- label: "Preview",
13406
- placement: "toolbar",
13407
- requiredPorts: ["commands"],
13408
- // `stack preview` plans the tf of the directory it runs in — a stack
13409
- // alone isn't enough, the mount needs the root too.
13410
- requiredContext: ["root", "stack"],
13411
- binding: preview
13412
- },
13413
- {
13414
- id: "run-cancel",
13415
- label: "Cancel",
13416
- placement: { row: "runs" },
13417
- requiredPorts: ["commands"],
13418
- requiredTarget: ["runId"],
13419
- binding: runCancel
13420
- },
13421
- {
13422
- id: "follow-logs",
13423
- label: "Follow logs",
13424
- placement: { row: "runs" },
13425
- requiredPorts: ["commands"],
13426
- requiredTarget: ["runId"],
13427
- binding: followLogs
13428
- }
13429
- ];
13430
- var CORE_COMMAND_ACTIONS = [
13431
- ...STACK_COMMAND_ACTIONS,
13432
- ...MODULE_COMMAND_ACTIONS
13433
- ];
13434
-
13435
- // src/core/diagnostics.ts
13436
- var NOT_LACE_SHAPE = "not_lace_shape";
13437
- function holdsLaceShapeRefusal(diagnostics) {
13438
- return diagnostics.some((d) => d.code === NOT_LACE_SHAPE);
13439
- }
13440
- function findingKey(d) {
13441
- return JSON.stringify([
13442
- d.file,
13443
- d.line,
13444
- d.message,
13445
- d.module_key,
13446
- d.instance_id,
13447
- d.input_name,
13448
- d.address
13449
- ]);
13450
- }
13451
- function uniqueDiagnostics(diagnostics) {
13452
- const seen = /* @__PURE__ */ new Set();
13453
- return diagnostics.filter((d) => {
13454
- const key = findingKey(d);
13455
- if (seen.has(key)) return false;
13456
- seen.add(key);
13457
- return true;
13458
- });
13459
- }
13460
- function diagnosticsOf(sourceDiagnostics, reportFindings) {
13461
- return uniqueDiagnostics([...sourceDiagnostics, ...reportFindings]);
13462
- }
13463
-
13464
- // src/core/report-fold.ts
13465
- var REPORT_PATHS = ["module validate", "module convert", "module scan"];
13466
- var FOLDS_AS = new Map([
13467
- ...REPORT_PATHS.map((path) => [path, path]),
13468
- ["stack import", "module convert"]
13469
- ]);
13470
- var EMPTY_REPORT_FOLD = /* @__PURE__ */ new Map();
13471
- function readEntry(path, exitCode, data) {
13472
- if (carriesFailure(data)) {
13473
- return { kind: "failure", path, exitCode, failure: parseCommandFailure(data) };
13474
- }
13475
- switch (path) {
13476
- case "module validate":
13477
- return { kind: "result", path, exitCode, document: parseBound(path, data) };
13478
- case "module convert":
13479
- return { kind: "result", path, exitCode, document: parseBound(path, data) };
13480
- case "module scan":
13481
- return { kind: "result", path, exitCode, document: parseBound(path, data) };
13482
- }
13483
- }
13484
- function foldReport(prev, result) {
13485
- const path = FOLDS_AS.get(result.path);
13486
- if (path === void 0) return prev;
13487
- const next = new Map(prev);
13488
- if (result.document === "") next.delete(path);
13489
- else next.set(path, readEntry(path, result.exitCode, JSON.parse(result.document)));
13490
- return next;
13491
- }
13492
- function treeHashOf(entry) {
13493
- if (entry.kind === "failure") return void 0;
13494
- switch (entry.path) {
13495
- case "module validate":
13496
- case "module scan":
13497
- return entry.document.treeHash;
13498
- case "module convert":
13499
- return entry.document.validate.treeHash;
13255
+ function treeHashOf(entry) {
13256
+ if (entry.kind === "failure") return void 0;
13257
+ switch (entry.path) {
13258
+ case "module validate":
13259
+ case "module scan":
13260
+ return entry.document.treeHash;
13261
+ case "module convert":
13262
+ return entry.document.validate.treeHash;
13500
13263
  }
13501
13264
  }
13502
13265
  function currentReport(fold, treeHash) {
@@ -13606,148 +13369,527 @@ function reduceRun(prev, token, event) {
13606
13369
  phases: closePhases(phases)
13607
13370
  };
13608
13371
  }
13609
- return { token, outcome: { kind: "running" }, lastLog, submitted, phases };
13610
- }
13611
- function exitSays(error) {
13612
- return error.failure ? { message: error.stderrTail, failure: error.failure } : { message: error.stderrTail };
13613
- }
13614
- function settleRun(prev, token, error) {
13615
- const carried = prev && prev.token === token ? prev : null;
13616
- const lastLog = carried?.lastLog ?? null;
13617
- const submitted = carried?.submitted ?? false;
13618
- const phases = closePhases(carried?.phases ?? []);
13619
- if (error instanceof CommandDetachedError || error instanceof CommandUnobservedError)
13620
- return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13621
- if (error instanceof CommandExitError) {
13622
- if (error.code === 130)
13623
- return { token, outcome: { kind: "cancelled" }, lastLog, submitted, phases };
13624
- if (error.code === 143)
13625
- return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13626
- if (error.code === 7)
13627
- return {
13628
- token,
13629
- outcome: { kind: "blocked", ...exitSays(error) },
13630
- lastLog,
13631
- submitted,
13632
- phases
13633
- };
13634
- return {
13635
- token,
13636
- outcome: { kind: "failed", ...exitSays(error) },
13637
- lastLog,
13638
- submitted,
13639
- phases
13640
- };
13372
+ return { token, outcome: { kind: "running" }, lastLog, submitted, phases };
13373
+ }
13374
+ function failureSays(error, command) {
13375
+ if (error instanceof CommandExitError) {
13376
+ return error.failure ? { message: error.failure.message, failure: error.failure } : { message: error.stderrTail };
13377
+ }
13378
+ if (error instanceof CommandUnobservedError && command.kind === "read") {
13379
+ return { message: `the stream ended before \`lace ${command.path}\` finished; run it again` };
13380
+ }
13381
+ return { message: error instanceof Error ? error.message : String(error) };
13382
+ }
13383
+ var RUN = { kind: "write" };
13384
+ function settleRun(prev, token, error) {
13385
+ const carried = prev && prev.token === token ? prev : null;
13386
+ const lastLog = carried?.lastLog ?? null;
13387
+ const submitted = carried?.submitted ?? false;
13388
+ const phases = closePhases(carried?.phases ?? []);
13389
+ if (error instanceof CommandDetachedError || error instanceof CommandUnobservedError)
13390
+ return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13391
+ if (error instanceof CommandExitError) {
13392
+ if (error.code === 130)
13393
+ return { token, outcome: { kind: "cancelled" }, lastLog, submitted, phases };
13394
+ if (error.code === 143)
13395
+ return { token, outcome: { kind: "detached", submitted }, lastLog, submitted, phases };
13396
+ if (error.code === 7)
13397
+ return {
13398
+ token,
13399
+ outcome: { kind: "blocked", ...failureSays(error, RUN) },
13400
+ lastLog,
13401
+ submitted,
13402
+ phases
13403
+ };
13404
+ }
13405
+ return {
13406
+ token,
13407
+ outcome: { kind: "failed", ...failureSays(error, RUN) },
13408
+ lastLog,
13409
+ submitted,
13410
+ phases
13411
+ };
13412
+ }
13413
+ function reducePreview(_prev, token, event) {
13414
+ return { token, data: event };
13415
+ }
13416
+ function reduceReport(prev, session, result) {
13417
+ const fold = foldReport(prev?.sessions.get(session) ?? EMPTY_REPORT_FOLD, result);
13418
+ return { sessions: new Map(prev?.sessions).set(session, fold) };
13419
+ }
13420
+ function reduceFollow(prev, token, event) {
13421
+ const carried = prev && prev.token === token ? prev : null;
13422
+ const runId = carried?.runId ?? "";
13423
+ const lines = carried?.lines ?? [];
13424
+ if (event.type === "log") return { token, runId, lines: [...lines, event.text], done: false };
13425
+ return { token, runId, lines, done: true };
13426
+ }
13427
+ function createResultStore() {
13428
+ let slots = {
13429
+ run: null,
13430
+ preview: null,
13431
+ report: null,
13432
+ follow: null,
13433
+ running: /* @__PURE__ */ new Map()
13434
+ };
13435
+ let tick = 0;
13436
+ const listeners = /* @__PURE__ */ new Set();
13437
+ const notify = () => {
13438
+ for (const listener of listeners) listener();
13439
+ };
13440
+ const retiredTokens = /* @__PURE__ */ new WeakSet();
13441
+ return {
13442
+ getSnapshot() {
13443
+ return slots;
13444
+ },
13445
+ getTick() {
13446
+ return tick;
13447
+ },
13448
+ subscribe(listener) {
13449
+ listeners.add(listener);
13450
+ return () => listeners.delete(listener);
13451
+ },
13452
+ write(kind, token, value, readOver) {
13453
+ if (retiredTokens.has(token)) return;
13454
+ slots = { ...slots, [kind]: applySlot(kind, slots[kind], token, value, readOver) };
13455
+ notify();
13456
+ },
13457
+ fail(kind, token, error) {
13458
+ if (kind !== "run") return false;
13459
+ if (retiredTokens.has(token) || !slots.run) return true;
13460
+ slots = { ...slots, run: stamp(settleRun(slots.run, token, error), slots.run.readOver) };
13461
+ notify();
13462
+ return true;
13463
+ },
13464
+ begin(kind, token, readOver, started) {
13465
+ if (kind === "run") {
13466
+ slots = {
13467
+ ...slots,
13468
+ run: {
13469
+ token,
13470
+ outcome: { kind: "running" },
13471
+ lastLog: null,
13472
+ submitted: false,
13473
+ phases: [],
13474
+ readOver
13475
+ }
13476
+ };
13477
+ } else if (kind === "follow") {
13478
+ slots = {
13479
+ ...slots,
13480
+ follow: { token, runId: started.target.runId ?? "", lines: [], done: false, readOver }
13481
+ };
13482
+ } else if (kind === "notify") {
13483
+ const { on, path, label } = started;
13484
+ slots = { ...slots, running: new Map(slots.running).set(on, { token, path, label }) };
13485
+ } else {
13486
+ return;
13487
+ }
13488
+ notify();
13489
+ },
13490
+ detach(kind, token) {
13491
+ if (kind === "follow" && slots.follow?.token === token) {
13492
+ slots = { ...slots, follow: null };
13493
+ notify();
13494
+ } else if (kind === "report" && slots.report?.sessions.has(token)) {
13495
+ const sessions = new Map(slots.report.sessions);
13496
+ sessions.delete(token);
13497
+ slots = {
13498
+ ...slots,
13499
+ report: sessions.size > 0 ? { sessions, readOver: slots.report.readOver } : null
13500
+ };
13501
+ notify();
13502
+ } else if (kind === "run" && slots.run?.token === token) {
13503
+ const settled = settleRun(slots.run, token, new CommandDetachedError());
13504
+ slots = { ...slots, run: stamp(settled, slots.run.readOver) };
13505
+ notify();
13506
+ } else if (kind === "notify") {
13507
+ const running = new Map([...slots.running].filter(([, mark]) => mark.token !== token));
13508
+ if (running.size !== slots.running.size) {
13509
+ slots = { ...slots, running };
13510
+ notify();
13511
+ }
13512
+ }
13513
+ retiredTokens.add(token);
13514
+ },
13515
+ busy(kind, on) {
13516
+ if (kind === "run") {
13517
+ return slots.run?.outcome.kind === "running" ? { kind: "run" } : void 0;
13518
+ }
13519
+ if (kind !== "notify") return void 0;
13520
+ const running = slots.running.get(on);
13521
+ return running ? { kind: "notify", running } : void 0;
13522
+ },
13523
+ bumpTick() {
13524
+ tick += 1;
13525
+ notify();
13526
+ }
13527
+ };
13528
+ }
13529
+
13530
+ // src/core/define-command.ts
13531
+ function defineCommand(binding) {
13532
+ return {
13533
+ kind: "command",
13534
+ path: binding.path,
13535
+ confirms: binding.confirm !== void 0,
13536
+ resultKind: binding.result.kind,
13537
+ invalidates: binding.invalidates,
13538
+ partialArgs(ctx, target) {
13539
+ return binding.args(ctx, target);
13540
+ },
13541
+ confirmSpec(ctx, target, formArgs) {
13542
+ if (!binding.confirm) return void 0;
13543
+ const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13544
+ if (!merged.ok) return void 0;
13545
+ return binding.confirm(ctx, merged.args, target);
13546
+ },
13547
+ async start(rt, ctx, target, formArgs, signal) {
13548
+ const merged = completeArgs(binding.path, { ...binding.args(ctx, target), ...formArgs });
13549
+ if (!merged.ok) return null;
13550
+ const commands = rt.ports.commands;
13551
+ if (!commands) return null;
13552
+ const invocation = commands.invoke(binding.path, merged.args, signal, rt.cwd);
13553
+ rt.begin();
13554
+ if (binding.invalidates === "start+settle") rt.tick();
13555
+ void (async () => {
13556
+ let rendered = false;
13557
+ try {
13558
+ for await (const event of invocation.events) {
13559
+ rendered = true;
13560
+ binding.result.consume(rt, event);
13561
+ }
13562
+ if (binding.invalidates) rt.tick();
13563
+ } catch (err) {
13564
+ const settledByDocument = rendered && binding.result.kind === "notify" && (err instanceof CommandExitError || err instanceof CommandUnobservedError);
13565
+ if (!rt.fail(err) && !(err instanceof CommandDetachedError) && !settledByDocument) {
13566
+ const { message, failure } = failureSays(
13567
+ err,
13568
+ binding.result.kind === "preview" || binding.result.kind === "follow" ? { kind: "read", path: binding.path } : { kind: "write" }
13569
+ );
13570
+ rt.ports.presenter.notify("error", message, ...failure ? [failure] : []);
13571
+ }
13572
+ if (binding.invalidates) rt.tick();
13573
+ } finally {
13574
+ rt.settled?.();
13575
+ }
13576
+ })();
13577
+ return { cancel: () => invocation.cancel() };
13578
+ }
13579
+ };
13580
+ }
13581
+
13582
+ // src/core/actions.ts
13583
+ function whyNotValid(v) {
13584
+ if (v.failure) return v.failure.message;
13585
+ const errors = v.diagnostics.filter((d) => d.severity === "error");
13586
+ if (errors.length === 0) return void 0;
13587
+ return `${errors[0].message} (${errors.length} ${errors.length === 1 ? "error" : "errors"})`;
13588
+ }
13589
+ function didNotValidate(v) {
13590
+ const why = whyNotValid(v);
13591
+ 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.`;
13592
+ }
13593
+ function beside(v) {
13594
+ return v.failure ? [v.failure] : [];
13595
+ }
13596
+ function slotSink(kind) {
13597
+ return { kind, consume: (rt, e) => rt.write(kind, rt.token, e) };
13598
+ }
13599
+ var apply = defineCommand({
13600
+ kind: "command",
13601
+ path: "stack apply",
13602
+ args: (ctx) => ({ stack: ctx.stack?.id }),
13603
+ // The run sink ticks at both start and settle, so a read keyed on the
13604
+ // tick (a host's run list, the describe overlay) sees the in-flight run
13605
+ // as soon as it starts, not only once it ends.
13606
+ invalidates: "start+settle",
13607
+ result: slotSink("run")
13608
+ });
13609
+ var destroy = defineCommand({
13610
+ kind: "command",
13611
+ path: "stack destroy",
13612
+ args: (ctx) => ({ stack: ctx.stack?.id, yes: true }),
13613
+ // The typed confirmation is the stack's slug — the human-facing name a
13614
+ // user actually reads off the host's stack list — never its id, which
13615
+ // `args.stack` carries for the command itself but nobody types from
13616
+ // memory.
13617
+ confirm: (ctx) => ({
13618
+ text: `Destroy ${ctx.stack?.slug}? This runs terraform destroy on the runner.`,
13619
+ typed: ctx.stack?.slug
13620
+ }),
13621
+ invalidates: "start+settle",
13622
+ result: slotSink("run")
13623
+ });
13624
+ function scanNotice(e) {
13625
+ const { slug } = e.stack;
13626
+ const settled = e.settled;
13627
+ if (!settled) {
13628
+ return [
13629
+ "info",
13630
+ e.triggered ? `Drift scan triggered for stack ${slug} (${e.stack.id}).` : `Drift scan already in progress for stack ${slug}.`
13631
+ ];
13632
+ }
13633
+ if (settled.undeterminedMessage !== null) return ["warn", settled.undeterminedMessage];
13634
+ if (settled.footprintDestroyed) {
13635
+ return [
13636
+ "info",
13637
+ `Drift scan complete for stack ${slug}: IN_SYNC (0 drifted) \u2014 its resources were destroyed, so there was nothing to compare.`
13638
+ ];
13639
+ }
13640
+ if (settled.standingDriftFindings > 0) {
13641
+ return [
13642
+ "info",
13643
+ `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.`
13644
+ ];
13645
+ }
13646
+ return [
13647
+ "info",
13648
+ `Drift scan complete for stack ${slug}: ${settled.driftStatus} (${settled.driftCount} drifted).`
13649
+ ];
13650
+ }
13651
+ var scan = defineCommand({
13652
+ kind: "command",
13653
+ path: "stack scan",
13654
+ args: (ctx) => ({ stack: ctx.stack?.id, wait: true }),
13655
+ invalidates: true,
13656
+ result: {
13657
+ kind: "notify",
13658
+ consume: (rt, e) => rt.ports.presenter.notify(...scanNotice(e))
13659
+ }
13660
+ });
13661
+ var create = defineCommand({
13662
+ kind: "command",
13663
+ path: "stack create",
13664
+ args: (ctx) => ({ source: ctx.root }),
13665
+ invalidates: true,
13666
+ result: {
13667
+ kind: "notify",
13668
+ consume: (rt, e) => rt.ports.presenter.notify("info", `Created stack ${e.slug}`)
13669
+ }
13670
+ });
13671
+ function residualAddresses(residuals) {
13672
+ return residuals.map((r) => r.address).join(", ");
13673
+ }
13674
+ function treeChanges(e) {
13675
+ return [
13676
+ ...e.written.length === 0 ? [] : [`rewriting ${e.written.join(", ")} in place`],
13677
+ ...e.removed.length === 0 ? [] : [`removing ${e.removed.join(", ")}`]
13678
+ ];
13679
+ }
13680
+ function importNotice(e) {
13681
+ const { slug } = e.stack;
13682
+ const changes = treeChanges(e);
13683
+ const files = changes.length > 0 ? `, ${changes.join(" and ")}` : "";
13684
+ const imported = `Imported ${e.importBlocks} resource(s) into ${slug}${files}.`;
13685
+ if (e.validate.exitClass !== "ok") {
13686
+ return ["warn", `${imported} ${didNotValidate(e.validate)}`, ...beside(e.validate)];
13687
+ }
13688
+ const adopt = e.changed ? ` Review the change in git, commit it, then apply ${slug} to adopt them.` : "";
13689
+ if (e.importResiduals.length === 0) return ["info", `${imported}${adopt}`];
13690
+ return [
13691
+ "warn",
13692
+ `${imported}${adopt} Not adopted: ${residualAddresses(e.importResiduals)}; supply their import ids before applying, or the apply creates them anew.`
13693
+ ];
13694
+ }
13695
+ var importResult = {
13696
+ kind: "notify",
13697
+ consume: (rt, e) => rt.ports.presenter.notify(...importNotice(e))
13698
+ };
13699
+ var importStack = defineCommand({
13700
+ kind: "command",
13701
+ path: "stack import",
13702
+ args: (ctx) => ({ stack: ctx.stack?.id }),
13703
+ invalidates: true,
13704
+ result: importResult
13705
+ });
13706
+ var importPartial = defineCommand({
13707
+ kind: "command",
13708
+ path: "stack import",
13709
+ args: (ctx) => ({ stack: ctx.stack?.id, allowPartial: true }),
13710
+ confirm: (ctx, _args, target) => ({
13711
+ 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.`
13712
+ }),
13713
+ invalidates: true,
13714
+ result: importResult
13715
+ });
13716
+ function validateNotice(v) {
13717
+ if (v.exitClass === "ok") return ["info", `Valid for Lace \u2014 ${v.verdict}`];
13718
+ if (v.failure) return ["error", v.failure.message, v.failure];
13719
+ const why = whyNotValid(v);
13720
+ return ["warn", why === void 0 ? "Not valid for Lace" : `Not valid: ${why}`];
13721
+ }
13722
+ function convertNotice(e) {
13723
+ const converted = e.changed ? `Converted \u2014 ${e.written.length} file(s) written` : "Already lace-style \u2014 nothing to write";
13724
+ if (e.validate.exitClass === "ok") return ["info", converted];
13725
+ return ["warn", `${converted}. ${didNotValidate(e.validate)}`, ...beside(e.validate)];
13726
+ }
13727
+ var validate = defineCommand({
13728
+ kind: "command",
13729
+ path: "module validate",
13730
+ args: () => ({}),
13731
+ result: {
13732
+ kind: "notify",
13733
+ consume: (rt, e) => rt.ports.presenter.notify(...validateNotice(e))
13734
+ }
13735
+ });
13736
+ var convert = defineCommand({
13737
+ kind: "command",
13738
+ path: "module convert",
13739
+ args: () => ({}),
13740
+ result: {
13741
+ kind: "notify",
13742
+ consume: (rt, e) => rt.ports.presenter.notify(...convertNotice(e))
13743
+ }
13744
+ });
13745
+ var preview = defineCommand({
13746
+ kind: "command",
13747
+ path: "stack preview",
13748
+ args: (ctx) => ({ stack: ctx.stack?.id }),
13749
+ result: slotSink("preview")
13750
+ });
13751
+ var runCancel = defineCommand({
13752
+ kind: "command",
13753
+ path: "run cancel",
13754
+ args: (_ctx, target) => ({ run: target.runId }),
13755
+ invalidates: true,
13756
+ result: {
13757
+ kind: "notify",
13758
+ consume: (rt, e) => rt.ports.presenter.notify("info", `Run ${e.id} ${e.status}`)
13759
+ }
13760
+ });
13761
+ var followLogs = defineCommand({
13762
+ kind: "command",
13763
+ path: "run logs",
13764
+ args: (_ctx, target) => ({ run: target.runId, follow: true }),
13765
+ result: slotSink("follow")
13766
+ });
13767
+ var MODULE_COMMAND_ACTIONS = [
13768
+ {
13769
+ id: "validate",
13770
+ label: "Validate",
13771
+ icon: "validate",
13772
+ section: "check",
13773
+ placement: "toolbar",
13774
+ requiredPorts: ["commands"],
13775
+ requiredContext: ["root"],
13776
+ binding: validate
13777
+ },
13778
+ {
13779
+ id: "convert",
13780
+ label: "Convert",
13781
+ icon: "convert",
13782
+ section: "check",
13783
+ placement: "toolbar",
13784
+ requiredPorts: ["commands"],
13785
+ requiredContext: ["root"],
13786
+ binding: convert
13787
+ },
13788
+ // Convert on the source-refused banner while the tree is out of lace
13789
+ // shape: the same `module convert` the toolbar runs, and the choice the
13790
+ // banner says of it. The engine re-derives the tree it writes, which
13791
+ // accepts it and lifts the lock.
13792
+ {
13793
+ id: "convert-refused",
13794
+ label: "Convert",
13795
+ choice: "Convert restructures it in place; a stack's apply creates only what its state does not hold yet.",
13796
+ icon: "convert",
13797
+ placement: { row: "source-refused" },
13798
+ requiredPorts: ["commands"],
13799
+ requiredContext: ["root", "needsConversion"],
13800
+ binding: convert
13801
+ }
13802
+ ];
13803
+ var STACK_COMMAND_ACTIONS = [
13804
+ {
13805
+ id: "apply",
13806
+ label: "Apply",
13807
+ placement: "toolbar",
13808
+ requiredPorts: ["commands"],
13809
+ // `stack apply` gates on the tf and certification of the directory it
13810
+ // runs in (submit.Prepare(env.Root)) before it ever reaches the
13811
+ // runner, so a mount with no root can't run it even with a stack
13812
+ // chosen — the same root gate `validate`/`convert` need. It ships
13813
+ // whatever tf is on disk, not the canvas's own working IR.
13814
+ requiredContext: ["root", "stack"],
13815
+ binding: apply
13816
+ },
13817
+ {
13818
+ id: "destroy",
13819
+ label: "Destroy",
13820
+ placement: "toolbar",
13821
+ requiredPorts: ["commands"],
13822
+ // `stack destroy` shares the CLI's `executeRun` with `stack apply` and
13823
+ // runs under `env.Root`, so it needs the identical context tuple.
13824
+ requiredContext: ["root", "stack"],
13825
+ binding: destroy
13826
+ },
13827
+ {
13828
+ id: "scan",
13829
+ label: "Scan for drift",
13830
+ placement: "toolbar",
13831
+ requiredPorts: ["commands"],
13832
+ requiredContext: ["stack"],
13833
+ binding: scan
13834
+ },
13835
+ {
13836
+ id: "create",
13837
+ label: "Create stack",
13838
+ placement: "toolbar",
13839
+ requiredPorts: ["commands"],
13840
+ requiredContext: ["root"],
13841
+ binding: create
13842
+ },
13843
+ {
13844
+ id: "import",
13845
+ label: "Import existing resources",
13846
+ placement: "toolbar",
13847
+ requiredPorts: ["commands"],
13848
+ // `stack import` writes the directory it runs in, the same way
13849
+ // Convert does.
13850
+ requiredContext: ["root", "stack"],
13851
+ binding: importStack
13852
+ },
13853
+ {
13854
+ id: "import-partial",
13855
+ label: "Import the rest",
13856
+ placement: { row: "failure" },
13857
+ requiredPorts: ["commands"],
13858
+ requiredContext: ["root", "stack"],
13859
+ answers: ["import_residual"],
13860
+ binding: importPartial
13861
+ },
13862
+ {
13863
+ id: "preview",
13864
+ label: "Preview",
13865
+ placement: "toolbar",
13866
+ requiredPorts: ["commands"],
13867
+ // `stack preview` plans the tf of the directory it runs in — a stack
13868
+ // alone isn't enough, the mount needs the root too.
13869
+ requiredContext: ["root", "stack"],
13870
+ binding: preview
13871
+ },
13872
+ {
13873
+ id: "run-cancel",
13874
+ label: "Cancel",
13875
+ placement: { row: "runs" },
13876
+ requiredPorts: ["commands"],
13877
+ requiredTarget: ["runId"],
13878
+ binding: runCancel
13879
+ },
13880
+ {
13881
+ id: "follow-logs",
13882
+ label: "Follow logs",
13883
+ placement: { row: "runs" },
13884
+ requiredPorts: ["commands"],
13885
+ requiredTarget: ["runId"],
13886
+ binding: followLogs
13641
13887
  }
13642
- return {
13643
- token,
13644
- outcome: { kind: "failed", message: error instanceof Error ? error.message : String(error) },
13645
- lastLog,
13646
- submitted,
13647
- phases
13648
- };
13649
- }
13650
- function reducePreview(_prev, token, event) {
13651
- return { token, data: event };
13652
- }
13653
- function reduceReport(prev, session, result) {
13654
- const fold = foldReport(prev?.sessions.get(session) ?? EMPTY_REPORT_FOLD, result);
13655
- return { sessions: new Map(prev?.sessions).set(session, fold) };
13656
- }
13657
- function reduceFollow(prev, token, event) {
13658
- const carried = prev && prev.token === token ? prev : null;
13659
- const runId = carried?.runId ?? "";
13660
- const lines = carried?.lines ?? [];
13661
- if (event.type === "log") return { token, runId, lines: [...lines, event.text], done: false };
13662
- return { token, runId, lines, done: true };
13663
- }
13664
- function createResultStore() {
13665
- let slots = {
13666
- run: null,
13667
- preview: null,
13668
- report: null,
13669
- follow: null
13670
- };
13671
- let tick = 0;
13672
- const listeners = /* @__PURE__ */ new Set();
13673
- const notify = () => {
13674
- for (const listener of listeners) listener();
13675
- };
13676
- const retiredTokens = /* @__PURE__ */ new WeakSet();
13677
- return {
13678
- getSnapshot() {
13679
- return slots;
13680
- },
13681
- getTick() {
13682
- return tick;
13683
- },
13684
- subscribe(listener) {
13685
- listeners.add(listener);
13686
- return () => listeners.delete(listener);
13687
- },
13688
- write(kind, token, value, readOver) {
13689
- if (retiredTokens.has(token)) return;
13690
- slots = { ...slots, [kind]: applySlot(kind, slots[kind], token, value, readOver) };
13691
- notify();
13692
- },
13693
- fail(kind, token, error) {
13694
- if (kind !== "run") return false;
13695
- if (retiredTokens.has(token) || !slots.run) return true;
13696
- slots = { ...slots, run: stamp(settleRun(slots.run, token, error), slots.run.readOver) };
13697
- notify();
13698
- return true;
13699
- },
13700
- begin(kind, token, readOver, target) {
13701
- if (kind === "run") {
13702
- slots = {
13703
- ...slots,
13704
- run: {
13705
- token,
13706
- outcome: { kind: "running" },
13707
- lastLog: null,
13708
- submitted: false,
13709
- phases: [],
13710
- readOver
13711
- }
13712
- };
13713
- } else if (kind === "follow") {
13714
- slots = {
13715
- ...slots,
13716
- follow: { token, runId: target.runId ?? "", lines: [], done: false, readOver }
13717
- };
13718
- } else {
13719
- return;
13720
- }
13721
- notify();
13722
- },
13723
- detach(kind, token) {
13724
- if (kind === "follow" && slots.follow?.token === token) {
13725
- slots = { ...slots, follow: null };
13726
- notify();
13727
- } else if (kind === "report" && slots.report?.sessions.has(token)) {
13728
- const sessions = new Map(slots.report.sessions);
13729
- sessions.delete(token);
13730
- slots = {
13731
- ...slots,
13732
- report: sessions.size > 0 ? { sessions, readOver: slots.report.readOver } : null
13733
- };
13734
- notify();
13735
- } else if (kind === "run" && slots.run?.token === token) {
13736
- const settled = settleRun(slots.run, token, new CommandDetachedError());
13737
- slots = { ...slots, run: stamp(settled, slots.run.readOver) };
13738
- notify();
13739
- }
13740
- retiredTokens.add(token);
13741
- },
13742
- isBusy(kind) {
13743
- return kind === "run" && slots.run?.outcome.kind === "running";
13744
- },
13745
- bumpTick() {
13746
- tick += 1;
13747
- notify();
13748
- }
13749
- };
13750
- }
13888
+ ];
13889
+ var CORE_COMMAND_ACTIONS = [
13890
+ ...STACK_COMMAND_ACTIONS,
13891
+ ...MODULE_COMMAND_ACTIONS
13892
+ ];
13751
13893
 
13752
13894
  // src/registry.ts
13753
13895
  var CONTEXT_NEEDS = {
@@ -13778,7 +13920,16 @@ var TARGET_NEEDS = {
13778
13920
  runId: "a run",
13779
13921
  failure: "a failed command"
13780
13922
  };
13781
- var BUSY_REASON = "A run is in progress";
13923
+ function busyReason(busy) {
13924
+ return busy.kind === "run" ? "A run is in progress" : `${busy.running.label} is running`;
13925
+ }
13926
+ function runsOn(action, ctx, target) {
13927
+ if (action.requiredTarget?.includes("runId")) return `run:${target.runId}`;
13928
+ const required = action.requiredContext ?? [];
13929
+ if (required.includes("stack")) return `stack:${ctx.stack?.id}`;
13930
+ if (required.includes("root")) return `root:${ctx.root}`;
13931
+ return "";
13932
+ }
13782
13933
  function keySatisfied(ctx, key) {
13783
13934
  if (key === "editable") return ctx.editable === true;
13784
13935
  if (key === "saved") return ctx.view?.unsaved === false;
@@ -13800,8 +13951,8 @@ function keySatisfied(ctx, key) {
13800
13951
  if (key === "redoable") return ctx.view?.can_redo === true;
13801
13952
  return ctx[key] !== void 0;
13802
13953
  }
13803
- function disabledReason(action, ctx, isBusy) {
13804
- if (isBusy) return BUSY_REASON;
13954
+ function disabledReason(action, ctx, busy) {
13955
+ if (busy) return busyReason(busy);
13805
13956
  for (const { key, reason } of action.enabledWhen ?? []) {
13806
13957
  if (!keySatisfied(ctx, key)) return reason;
13807
13958
  }
@@ -13876,7 +14027,19 @@ function createActionRunner(ports, store, options = {}) {
13876
14027
  const handles = /* @__PURE__ */ new Map();
13877
14028
  const tokens = /* @__PURE__ */ new Map();
13878
14029
  const clipboard = createClipboardStore();
13879
- const notifyControllers = /* @__PURE__ */ new Set();
14030
+ const notifyControllers = /* @__PURE__ */ new Map();
14031
+ let edits = 0;
14032
+ const editingListeners = /* @__PURE__ */ new Set();
14033
+ async function asEdit(edit) {
14034
+ edits += 1;
14035
+ if (edits === 1) for (const listener of editingListeners) listener(true);
14036
+ try {
14037
+ return await edit();
14038
+ } finally {
14039
+ edits -= 1;
14040
+ if (edits === 0) for (const listener of editingListeners) listener(false);
14041
+ }
14042
+ }
13880
14043
  async function applyWith(editor, actions) {
13881
14044
  let result;
13882
14045
  try {
@@ -13916,13 +14079,14 @@ function createActionRunner(ports, store, options = {}) {
13916
14079
  async function applyActions(actions) {
13917
14080
  const editor = ports.editor;
13918
14081
  if (!editor) return;
13919
- return applyWith(editor, actions);
14082
+ return asEdit(() => applyWith(editor, actions));
13920
14083
  }
13921
14084
  function askConfirm(spec) {
13922
14085
  const confirm = ports.presenter.confirm;
13923
14086
  return confirm ? confirm(spec) : Promise.resolve(false);
13924
14087
  }
13925
- function runtimeFor(token, readOver, cwd, run, onSettle) {
14088
+ function runtimeFor(token, readOver, cwd, command, onSettle) {
14089
+ const run = command?.run;
13926
14090
  return {
13927
14091
  ports,
13928
14092
  token,
@@ -13933,7 +14097,7 @@ function createActionRunner(ports, store, options = {}) {
13933
14097
  if (run && line !== void 0) options.onRunLog?.(line, run);
13934
14098
  },
13935
14099
  begin: () => {
13936
- if (run) store.begin(run.resultKind, token, readOver, run.target);
14100
+ if (command) store.begin(command.run.resultKind, token, readOver, command.started);
13937
14101
  },
13938
14102
  fail: (error) => run ? store.fail(run.resultKind, token, error) : false,
13939
14103
  detach: (kind, tok) => store.detach(kind, tok),
@@ -13944,6 +14108,15 @@ function createActionRunner(ports, store, options = {}) {
13944
14108
  function readOverOf(ctx) {
13945
14109
  return { stack: ctx.stack?.id };
13946
14110
  }
14111
+ function busyOn(resultKind, action, ctx, target) {
14112
+ const on = runsOn(action, ctx, target);
14113
+ return { on, busy: store.busy(resultKind, on) };
14114
+ }
14115
+ function busyOf(action, ctx, target) {
14116
+ const binding = action.binding;
14117
+ if (binding.kind !== "command") return void 0;
14118
+ return busyOn(binding.resultKind, action, ctx, target).busy;
14119
+ }
13947
14120
  function cwdOf(action, ctx) {
13948
14121
  return (action.requiredContext ?? []).includes("root") ? ctx.root : void 0;
13949
14122
  }
@@ -13965,19 +14138,24 @@ function createActionRunner(ports, store, options = {}) {
13965
14138
  if (binding.kind !== "command") return;
13966
14139
  const spec = binding.confirmSpec(ctx, target, formArgs);
13967
14140
  if (spec && !await askConfirm(spec)) return;
13968
- if (store.isBusy(binding.resultKind)) {
13969
- ports.presenter.notify("warn", BUSY_REASON);
14141
+ const { on, busy } = busyOn(binding.resultKind, action, ctx, target);
14142
+ if (busy) {
14143
+ ports.presenter.notify("warn", busyReason(busy));
13970
14144
  return;
13971
14145
  }
13972
14146
  const readOver = readOverOf(ctx);
13973
14147
  const cwd = cwdOf(action, ctx);
13974
14148
  const token = {};
13975
14149
  const run = { token, path: binding.path, resultKind: binding.resultKind, ctx, target };
14150
+ const started = { target, on, path: binding.path, label: action.label };
13976
14151
  const controller = new AbortController();
13977
14152
  if (binding.resultKind === "notify") {
13978
- notifyControllers.add(controller);
14153
+ notifyControllers.set(controller, token);
13979
14154
  await binding.start(
13980
- runtimeFor(token, readOver, cwd, run, () => notifyControllers.delete(controller)),
14155
+ runtimeFor(token, readOver, cwd, { run, started }, () => {
14156
+ notifyControllers.delete(controller);
14157
+ store.detach("notify", token);
14158
+ }),
13981
14159
  ctx,
13982
14160
  target,
13983
14161
  formArgs,
@@ -13989,7 +14167,7 @@ function createActionRunner(ports, store, options = {}) {
13989
14167
  controllers.set(binding.resultKind, controller);
13990
14168
  tokens.set(binding.resultKind, token);
13991
14169
  const handle = await binding.start(
13992
- runtimeFor(token, readOver, cwd, run),
14170
+ runtimeFor(token, readOver, cwd, { run, started }),
13993
14171
  ctx,
13994
14172
  target,
13995
14173
  formArgs,
@@ -14038,7 +14216,7 @@ function createActionRunner(ports, store, options = {}) {
14038
14216
  ...envExtras
14039
14217
  };
14040
14218
  if (binding.result === "apply") {
14041
- return binding.run(env);
14219
+ return asEdit(() => binding.run(env));
14042
14220
  }
14043
14221
  if (binding.result === "generate") {
14044
14222
  for await (const event of binding.run(env)) {
@@ -14066,8 +14244,7 @@ function createActionRunner(ports, store, options = {}) {
14066
14244
  ports.presenter.notify("warn", unmet);
14067
14245
  return;
14068
14246
  }
14069
- const isBusy = action.binding.kind === "command" && store.isBusy(action.binding.resultKind);
14070
- const reason = disabledReason(action, ctx, isBusy);
14247
+ const reason = disabledReason(action, ctx, busyOf(action, ctx, target));
14071
14248
  if (reason !== void 0) {
14072
14249
  ports.presenter.notify("warn", reason);
14073
14250
  return;
@@ -14094,6 +14271,18 @@ function createActionRunner(ports, store, options = {}) {
14094
14271
  apply(actions) {
14095
14272
  return applyActions(actions);
14096
14273
  },
14274
+ editing() {
14275
+ return edits > 0;
14276
+ },
14277
+ onEditingChange(listener) {
14278
+ editingListeners.add(listener);
14279
+ return () => {
14280
+ editingListeners.delete(listener);
14281
+ };
14282
+ },
14283
+ busy(action, ctx, target) {
14284
+ return busyOf(action, ctx, target);
14285
+ },
14097
14286
  async cancel(kind) {
14098
14287
  const handle = handles.get(kind);
14099
14288
  if (!handle) return;
@@ -14105,7 +14294,10 @@ function createActionRunner(ports, store, options = {}) {
14105
14294
  },
14106
14295
  dispose() {
14107
14296
  for (const kind of [...controllers.keys()]) detachSlot(kind);
14108
- for (const controller of notifyControllers) controller.abort();
14297
+ for (const [controller, token] of notifyControllers) {
14298
+ controller.abort();
14299
+ store.detach("notify", token);
14300
+ }
14109
14301
  notifyControllers.clear();
14110
14302
  }
14111
14303
  };
@@ -14222,6 +14414,7 @@ function autosave(source, save, policy, report) {
14222
14414
  defineCommand,
14223
14415
  diagnosticsOf,
14224
14416
  diagnosticsOfDocument,
14417
+ failureSays,
14225
14418
  foldReport,
14226
14419
  isBoundPath,
14227
14420
  liveSlots,