@lotics/cli 0.101.1 → 0.103.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.
package/README.md CHANGED
@@ -239,9 +239,10 @@ lotics app agent run app_abc recognize --json # full run summar
239
239
  lotics app agent run app_abc recognize --session cli-123 '{}' # continue an existing thread
240
240
 
241
241
  # Dev-link @lotics/ui to packages/ui/src for live HMR (Vite alias; deploy bundles it)
242
- lotics ui link card # monorepo: packages/ui/src found automatically
243
- lotics ui link card --ui-src /abs/monorepo/packages/ui/src # external app (e.g. ~/lotics_apps)
244
- lotics ui link card --remove # finalize: PR + publish, then drop the alias
242
+ # Dev-link @lotics/ui to a monorepo checkout for ONE command — nothing is written to disk
243
+ LOTICS_UI_SRC=/abs/monorepo/packages/ui/src lotics app dev
244
+ LOTICS_UI_SRC=/abs/monorepo/packages/ui/src lotics app deploy -m "..." # warns: bundles YOUR kit copy
245
+ lotics app dev # unset ⇒ @lotics/ui resolves from node_modules again
245
246
  ```
246
247
 
247
248
  `app codegen` reads `package.json#lotics.queries` to decide which tables to put in `app_fields.ts`; widen the set with `package.json#lotics.codegen.tables` (an array of `tbl_…` ids) for tables the app only writes via workflows.
@@ -25066,6 +25066,7 @@ ${e.toString()}`);
25066
25066
  this._byDepthAndTag = /* @__PURE__ */ new Map();
25067
25067
  this._wildcardByDepth = /* @__PURE__ */ new Map();
25068
25068
  this._deepWildcards = [];
25069
+ this._deepByTerminalTag = /* @__PURE__ */ new Map();
25069
25070
  this._patterns = /* @__PURE__ */ new Set();
25070
25071
  this._sealed = false;
25071
25072
  }
@@ -25090,7 +25091,14 @@ ${e.toString()}`);
25090
25091
  if (this._patterns.has(expression.pattern)) return this;
25091
25092
  this._patterns.add(expression.pattern);
25092
25093
  if (expression.hasDeepWildcard()) {
25093
- this._deepWildcards.push(expression);
25094
+ const lastSeg2 = expression.segments[expression.segments.length - 1];
25095
+ if (lastSeg2 && lastSeg2.type !== "deep-wildcard" && lastSeg2.tag !== "*") {
25096
+ const tag2 = lastSeg2.tag;
25097
+ if (!this._deepByTerminalTag.has(tag2)) this._deepByTerminalTag.set(tag2, []);
25098
+ this._deepByTerminalTag.get(tag2).push(expression);
25099
+ } else {
25100
+ this._deepWildcards.push(expression);
25101
+ }
25094
25102
  return this;
25095
25103
  }
25096
25104
  const depth = expression.length;
@@ -25208,6 +25216,12 @@ ${e.toString()}`);
25208
25216
  if (matcher.matches(wildcardBucket[i3])) return wildcardBucket[i3];
25209
25217
  }
25210
25218
  }
25219
+ const deepBucket = this._deepByTerminalTag.get(tag);
25220
+ if (deepBucket) {
25221
+ for (let i3 = 0; i3 < deepBucket.length; i3++) {
25222
+ if (matcher.matches(deepBucket[i3])) return deepBucket[i3];
25223
+ }
25224
+ }
25211
25225
  for (let i3 = 0; i3 < this._deepWildcards.length; i3++) {
25212
25226
  if (matcher.matches(this._deepWildcards[i3])) return this._deepWildcards[i3];
25213
25227
  }
@@ -25267,6 +25281,24 @@ ${e.toString()}`);
25267
25281
  const current = path[path.length - 1];
25268
25282
  return current.values !== void 0 && attrName in current.values;
25269
25283
  }
25284
+ /**
25285
+ * Get the value of a "kept" attribute from the nearest ancestor (or
25286
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
25287
+ * @param {string} attrName
25288
+ * @returns {*}
25289
+ */
25290
+ getAnyParentAttr(attrName) {
25291
+ return this._matcher.getAnyParentAttr(attrName);
25292
+ }
25293
+ /**
25294
+ * Check whether any ancestor (or the current node) kept the given
25295
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
25296
+ * @param {string} attrName
25297
+ * @returns {boolean}
25298
+ */
25299
+ hasAnyParentAttr(attrName) {
25300
+ return this._matcher.hasAnyParentAttr(attrName);
25301
+ }
25270
25302
  /**
25271
25303
  * Get current node's sibling position (child index in parent).
25272
25304
  * @returns {number}
@@ -25345,30 +25377,32 @@ ${e.toString()}`);
25345
25377
  this.siblingStacks = [];
25346
25378
  this._pathStringCache = null;
25347
25379
  this._view = new MatcherView(this);
25380
+ this._keptAttrs = [];
25348
25381
  }
25349
25382
  /**
25350
25383
  * Push a new tag onto the path.
25351
25384
  * @param {string} tagName
25352
25385
  * @param {Object|null} [attrValues=null]
25353
25386
  * @param {string|null} [namespace=null]
25387
+ * @param {Object|null} [options=null]
25388
+ * @param {string[]} [options.keep] - Names of attributes (from attrValues)
25354
25389
  */
25355
- push(tagName, attrValues = null, namespace = null) {
25390
+ push(tagName, attrValues = null, namespace = null, options = null) {
25356
25391
  this._pathStringCache = null;
25357
25392
  if (this.path.length > 0) {
25358
25393
  this.path[this.path.length - 1].values = void 0;
25359
25394
  }
25360
25395
  const currentLevel = this.path.length;
25361
- if (!this.siblingStacks[currentLevel]) {
25362
- this.siblingStacks[currentLevel] = /* @__PURE__ */ new Map();
25396
+ let level2 = this.siblingStacks[currentLevel];
25397
+ if (!level2) {
25398
+ level2 = { counts: /* @__PURE__ */ new Map(), total: 0 };
25399
+ this.siblingStacks[currentLevel] = level2;
25363
25400
  }
25364
- const siblings = this.siblingStacks[currentLevel];
25365
25401
  const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;
25366
- const counter = siblings.get(siblingKey) || 0;
25367
- let position = 0;
25368
- for (const count of siblings.values()) {
25369
- position += count;
25370
- }
25371
- siblings.set(siblingKey, counter + 1);
25402
+ const counter = level2.counts.get(siblingKey) || 0;
25403
+ const position = level2.total;
25404
+ level2.counts.set(siblingKey, counter + 1);
25405
+ level2.total++;
25372
25406
  const node = {
25373
25407
  tag: tagName,
25374
25408
  position,
@@ -25381,6 +25415,16 @@ ${e.toString()}`);
25381
25415
  node.values = attrValues;
25382
25416
  }
25383
25417
  this.path.push(node);
25418
+ const depth = this.path.length;
25419
+ const keep = options !== null ? options.keep : null;
25420
+ if (keep !== null && keep !== void 0 && keep.length > 0 && attrValues) {
25421
+ for (let i3 = 0; i3 < keep.length; i3++) {
25422
+ const name = keep[i3];
25423
+ if (attrValues[name] !== void 0) {
25424
+ this._keptAttrs.push({ depth, name, value: attrValues[name] });
25425
+ }
25426
+ }
25427
+ }
25384
25428
  }
25385
25429
  /**
25386
25430
  * Pop the last tag from the path.
@@ -25393,6 +25437,10 @@ ${e.toString()}`);
25393
25437
  if (this.siblingStacks.length > this.path.length + 1) {
25394
25438
  this.siblingStacks.length = this.path.length + 1;
25395
25439
  }
25440
+ const poppedDepth = this.path.length + 1;
25441
+ while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) {
25442
+ this._keptAttrs.pop();
25443
+ }
25396
25444
  return node;
25397
25445
  }
25398
25446
  /**
@@ -25441,6 +25489,36 @@ ${e.toString()}`);
25441
25489
  const current = this.path[this.path.length - 1];
25442
25490
  return current.values !== void 0 && attrName in current.values;
25443
25491
  }
25492
+ /**
25493
+ * Get the value of a "kept" attribute from the nearest ancestor (or
25494
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
25495
+ * Unlike getAttrValue(), this works regardless of how deep the path has
25496
+ * gone since the attribute was pushed — but only for attribute names that
25497
+ * were explicitly marked with `keep` at push time. Cost is proportional to
25498
+ * the number of currently-kept attributes (typically 0-3), not path depth.
25499
+ * @param {string} attrName
25500
+ * @returns {*} the value, or undefined if no ancestor kept this attribute
25501
+ */
25502
+ getAnyParentAttr(attrName) {
25503
+ const kept = this._keptAttrs;
25504
+ for (let i3 = kept.length - 1; i3 >= 0; i3--) {
25505
+ if (kept[i3].name === attrName) return kept[i3].value;
25506
+ }
25507
+ return void 0;
25508
+ }
25509
+ /**
25510
+ * Check whether any ancestor (or the current node) kept the given
25511
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
25512
+ * @param {string} attrName
25513
+ * @returns {boolean}
25514
+ */
25515
+ hasAnyParentAttr(attrName) {
25516
+ const kept = this._keptAttrs;
25517
+ for (let i3 = kept.length - 1; i3 >= 0; i3--) {
25518
+ if (kept[i3].name === attrName) return true;
25519
+ }
25520
+ return false;
25521
+ }
25444
25522
  /**
25445
25523
  * Get current node's sibling position (child index in parent).
25446
25524
  * @returns {number}
@@ -25509,6 +25587,7 @@ ${e.toString()}`);
25509
25587
  this._pathStringCache = null;
25510
25588
  this.path = [];
25511
25589
  this.siblingStacks = [];
25590
+ this._keptAttrs = [];
25512
25591
  }
25513
25592
  /**
25514
25593
  * Match current path against an Expression.
@@ -25632,7 +25711,8 @@ ${e.toString()}`);
25632
25711
  snapshot() {
25633
25712
  return {
25634
25713
  path: this.path.map((node) => ({ ...node })),
25635
- siblingStacks: this.siblingStacks.map((map3) => new Map(map3))
25714
+ siblingStacks: this.siblingStacks.map((level2) => level2 ? { counts: new Map(level2.counts), total: level2.total } : level2),
25715
+ keptAttrs: this._keptAttrs.map((entry) => ({ ...entry }))
25636
25716
  };
25637
25717
  }
25638
25718
  /**
@@ -25642,7 +25722,8 @@ ${e.toString()}`);
25642
25722
  restore(snapshot) {
25643
25723
  this._pathStringCache = null;
25644
25724
  this.path = snapshot.path.map((node) => ({ ...node }));
25645
- this.siblingStacks = snapshot.siblingStacks.map((map3) => new Map(map3));
25725
+ this.siblingStacks = snapshot.siblingStacks.map((level2) => level2 ? { counts: new Map(level2.counts), total: level2.total } : level2);
25726
+ this._keptAttrs = (snapshot.keptAttrs || []).map((entry) => ({ ...entry }));
25646
25727
  }
25647
25728
  /**
25648
25729
  * Return the read-only {@link MatcherView} for this matcher.
package/dist/src/cli.js CHANGED
@@ -45532,7 +45532,23 @@ export default defineConfig({
45532
45532
  // is safe. Define both so dev and the deployed build behave identically.
45533
45533
  define: { __DEV__: "false", global: "globalThis" },
45534
45534
  resolve: {
45535
- alias: [{ find: "react-native", replacement: "react-native-web" }],
45535
+ // \`LOTICS_UI_SRC\` dev-links @lotics/ui to a monorepo checkout, so kit edits
45536
+ // go live (HMR) and bundle on deploy without a publish round-trip:
45537
+ // LOTICS_UI_SRC=/abs/path/to/packages/ui/src lotics app dev
45538
+ // Unset \u21D2 the kit resolves from node_modules as normal. It lives in the ENV,
45539
+ // never in this file: the link used to be written here by \`lotics ui link\`
45540
+ // and removed by \`--remove\`, which is a regex editing TypeScript \u2014 it twice
45541
+ // took the react-native alias below with it and left the app unable to build.
45542
+ // State that only exists for the length of one command belongs in the command.
45543
+ // VITE ONLY: \`tsc\` still resolves @lotics/ui from node_modules (the kit's
45544
+ // src is RN-Web and cannot typecheck inside an app), so typecheck the kit in
45545
+ // packages/ui and let the publish restore this app's own typecheck.
45546
+ alias: [
45547
+ ...(process.env.LOTICS_UI_SRC
45548
+ ? [{ find: /^@lotics\\/ui\\/(.+)$/, replacement: \`\${process.env.LOTICS_UI_SRC}/$1\` }]
45549
+ : []),
45550
+ { find: "react-native", replacement: "react-native-web" },
45551
+ ],
45536
45552
  // \`.web.js\` resolves the web build of RN packages that ship \`X.js\` (native)
45537
45553
  // beside \`X.web.js\` (web) \u2014 e.g. @react-native-picker/picker, whose compiled
45538
45554
  // \`Picker.web.js\` renders a real <select>. Without it the extensionless
@@ -64946,6 +64962,9 @@ var appWorkflowDeclarationSchema = zod_default.object({
64946
64962
  ).refine(
64947
64963
  (outputs) => outputs === void 0 || Object.values(outputs).every((o) => appWorkflowOutputDepth(o) <= MAX_APP_WORKFLOW_OUTPUT_DEPTH),
64948
64964
  { message: `output schema nesting exceeds the max depth of ${MAX_APP_WORKFLOW_OUTPUT_DEPTH}` }
64965
+ ),
64966
+ description: zod_default.string().optional().describe(
64967
+ "What this workflow does, in one line \u2014 read by an agent choosing between the app's aliases, the same job a query's `description` does. `lotics app workflow set` sends it, so it lives beside the body in version control; omitted, the workflow keeps the description already on it."
64949
64968
  )
64950
64969
  });
64951
64970
  var appWorkflowContractSchema = zod_default.object({
@@ -70248,7 +70267,10 @@ function writeAgentFiles(projectDir, agents) {
70248
70267
  }
70249
70268
  return written;
70250
70269
  }
70251
- async function writeWorkflowFiles(client, projectDir, app_id, workflows) {
70270
+ function generatedWorkflowDescription(appName, alias) {
70271
+ return `Workflow invoked by app "${appName}" via useWorkflow("${alias}").`;
70272
+ }
70273
+ async function writeWorkflowFiles(client, projectDir, app_id, appName, workflows) {
70252
70274
  const written = [];
70253
70275
  for (const [alias, declaration] of Object.entries(workflows)) {
70254
70276
  const res = await client.getAppWorkflow(app_id, alias);
@@ -70272,10 +70294,27 @@ async function writeWorkflowFiles(client, projectDir, app_id, workflows) {
70272
70294
  toWorkflowDtsDeclaration(declaration)
70273
70295
  );
70274
70296
  writeWorkflowFile(projectDir, alias, source, envelope);
70297
+ const rowDescription = res.result.description;
70298
+ if (typeof rowDescription === "string" && rowDescription !== "" && // Skip the server's GENERATED default. It is what an undescribed alias
70299
+ // carries, so writing it back would commit a line of noise per workflow
70300
+ // into every app that never authored one — and the manifest would then
70301
+ // push it back, entrenching it. Matched by reconstruction, not by
70302
+ // sniffing the wording, so it can only ever skip the exact default.
70303
+ rowDescription !== generatedWorkflowDescription(appName, alias)) {
70304
+ writeWorkflowDescription(projectDir, alias, rowDescription);
70305
+ }
70275
70306
  written.push(alias);
70276
70307
  }
70277
70308
  return written;
70278
70309
  }
70310
+ function writeWorkflowDescription(projectDir, alias, description) {
70311
+ const pkgPath2 = path5.join(projectDir, "package.json");
70312
+ const pkg2 = JSON.parse(fs4.readFileSync(pkgPath2, "utf-8"));
70313
+ const declaration = pkg2.lotics?.workflows?.[alias];
70314
+ if (!declaration) return;
70315
+ declaration.description = description;
70316
+ fs4.writeFileSync(pkgPath2, JSON.stringify(pkg2, null, 2) + "\n");
70317
+ }
70279
70318
  async function fetchWorkflowGlobals(client, projectDir, app_id, alias, declaration) {
70280
70319
  try {
70281
70320
  const { dts, envelope_prefix, envelope_suffix } = await fetchWorkflowDts(
@@ -70469,6 +70508,29 @@ function writeBindingAppFields(projectDir, binding) {
70469
70508
  ensureAppVitestSetup(projectDir);
70470
70509
  return file2;
70471
70510
  }
70511
+ function warnIfDeployingLinkedKit(projectDir) {
70512
+ const uiSrc = process.env.LOTICS_UI_SRC;
70513
+ if (!uiSrc) return;
70514
+ const viteConfigPath = path5.join(projectDir, "vite.config.ts");
70515
+ if (!fs4.existsSync(viteConfigPath)) return;
70516
+ if (!fs4.readFileSync(viteConfigPath, "utf-8").includes("LOTICS_UI_SRC")) return;
70517
+ console.error(
70518
+ `\u26A0 LOTICS_UI_SRC is set \u2014 this deploy bundles @lotics/ui from ${uiSrc}, NOT the published package. The deployed app will run kit code that exists only on this machine. Unset it and re-deploy once the kit change is published if that is not what you want.`
70519
+ );
70520
+ }
70521
+ function warnIfDevLinkIgnored(projectDir) {
70522
+ const uiSrc = process.env.LOTICS_UI_SRC;
70523
+ if (!uiSrc) return;
70524
+ const viteConfigPath = path5.join(projectDir, "vite.config.ts");
70525
+ if (!fs4.existsSync(viteConfigPath)) return;
70526
+ if (fs4.readFileSync(viteConfigPath, "utf-8").includes("LOTICS_UI_SRC")) return;
70527
+ console.error(
70528
+ `\u26A0 LOTICS_UI_SRC is set but vite.config.ts never reads it \u2014 @lotics/ui will still resolve from node_modules, so kit edits will NOT appear. Add the dev-link entry to \`resolve.alias\` (refresh vite.config.ts from the starter, or paste):
70529
+ ...(process.env.LOTICS_UI_SRC
70530
+ ? [{ find: /^@lotics\\/ui\\/(.+)$/, replacement: \`\${process.env.LOTICS_UI_SRC}/$1\` }]
70531
+ : []),`
70532
+ );
70533
+ }
70472
70534
  function ensureAppVitestSetup(projectDir) {
70473
70535
  const setupPath = path5.join(projectDir, VITEST_SETUP_FILENAME);
70474
70536
  if (!fs4.existsSync(setupPath)) {
@@ -70717,7 +70779,7 @@ async function appPull(client, args) {
70717
70779
  });
70718
70780
  const workflows = app.workflows ?? {};
70719
70781
  if (Object.keys(workflows).length > 0) {
70720
- const written = await writeWorkflowFiles(client, targetPath, app.id, workflows);
70782
+ const written = await writeWorkflowFiles(client, targetPath, app.id, app.name, workflows);
70721
70783
  if (written.length > 0) {
70722
70784
  console.error(
70723
70785
  `Wrote ${written.length} workflow ${written.length === 1 ? "body" : "bodies"} to ${WORKFLOWS_DIR}/ (${written.join(", ")})`
@@ -70758,6 +70820,7 @@ function readAppSourceText(projectDir) {
70758
70820
  async function appDeploy(client, args) {
70759
70821
  const projectDir = path5.resolve(args.projectDir ?? process.cwd());
70760
70822
  const meta3 = readAppMeta(projectDir);
70823
+ warnIfDeployingLinkedKit(projectDir);
70761
70824
  const sourceText = readAppSourceText(projectDir);
70762
70825
  const called = calledAppAliases(sourceText);
70763
70826
  if (called.dynamic.length > 0) {
@@ -70920,6 +70983,7 @@ function warnIfUnboundAliases(app, called) {
70920
70983
  async function appDev(client, args) {
70921
70984
  const projectDir = path5.resolve(args.projectDir ?? process.cwd());
70922
70985
  const meta3 = readAppMeta(projectDir);
70986
+ warnIfDevLinkIgnored(projectDir);
70923
70987
  writeAppDts(projectDir, { workflows: meta3.workflows, queries: meta3.queries, agents: meta3.agents });
70924
70988
  const app = await client.getApp(meta3.app_id);
70925
70989
  const handle = await startDevServer({
@@ -71195,7 +71259,15 @@ async function appWorkflowSet(client, args) {
71195
71259
  const res = await client.setAppWorkflow(meta3.app_id, args.alias, {
71196
71260
  source,
71197
71261
  inputs: declaration.inputs,
71198
- outputs: declaration.outputs
71262
+ outputs: declaration.outputs,
71263
+ // What an agent reads when choosing between this app's workflows. Carried
71264
+ // from the manifest, alongside `inputs`, so it lives in version control
71265
+ // beside the body and rides every push — the CLI sent no description at
71266
+ // all, which is why a CLI-authored app's aliases all rendered the generated
71267
+ // `Workflow invoked by app "X" via useWorkflow("y")`. Absent leaves
71268
+ // whatever is on the row, so this can never blank a description set
71269
+ // elsewhere.
71270
+ description: declaration.description
71199
71271
  });
71200
71272
  if (res.error) {
71201
71273
  console.error(`Failed to set workflow "${args.alias}": ${res.error}`);
@@ -71258,7 +71330,7 @@ async function appWorkflowPull(client) {
71258
71330
  console.error(`App ${meta3.app_id} has no bound workflows.`);
71259
71331
  return;
71260
71332
  }
71261
- const written = await writeWorkflowFiles(client, projectDir, meta3.app_id, workflows);
71333
+ const written = await writeWorkflowFiles(client, projectDir, meta3.app_id, app.name, workflows);
71262
71334
  console.error(
71263
71335
  `Wrote ${written.length} workflow ${written.length === 1 ? "body" : "bodies"} to ${WORKFLOWS_DIR}/` + (written.length > 0 ? ` (${written.join(", ")})` : "")
71264
71336
  );
@@ -71339,73 +71411,6 @@ All ${results.length} workflow bodies parse and type-check clean.`) + `
71339
71411
  ${totalErrors} error${totalErrors === 1 ? "" : "s"} across ${results.length - passed} of ${results.length} ${results.length === 1 ? "body" : "bodies"}.`
71340
71412
  );
71341
71413
  }
71342
- function findUiSrcDir(start) {
71343
- let dir = path5.resolve(start);
71344
- for (; ; ) {
71345
- const candidate = path5.join(dir, "packages", "ui", "src");
71346
- if (fs4.existsSync(candidate) && fs4.statSync(candidate).isDirectory()) return candidate;
71347
- const parent = path5.dirname(dir);
71348
- if (parent === dir) return null;
71349
- dir = parent;
71350
- }
71351
- }
71352
- var UI_ALIAS_FIND_SOURCE = String.raw`/^@lotics\/ui\/(.+)$/`;
71353
- function appUiLink(args) {
71354
- const projectDir = path5.resolve(args.projectDir ?? process.cwd());
71355
- const viteConfigPath = path5.join(projectDir, "vite.config.ts");
71356
- if (!fs4.existsSync(viteConfigPath)) {
71357
- throw new Error(
71358
- `No vite.config.ts at ${projectDir}. Run inside a 'lotics app' project directory.`
71359
- );
71360
- }
71361
- const explicit = args.uiSrc ?? process.env.LOTICS_UI_SRC;
71362
- const uiSrc = explicit ? path5.resolve(explicit) : findUiSrcDir(projectDir);
71363
- if (!uiSrc || !fs4.existsSync(uiSrc) || !fs4.statSync(uiSrc).isDirectory()) {
71364
- throw new Error(
71365
- explicit ? `--ui-src / LOTICS_UI_SRC points at '${explicit}', which is not a directory. Pass the absolute path to the monorepo's packages/ui/src.` : "Cannot find packages/ui/src by walking up from this directory. For an EXTERNAL app (consuming @lotics/ui from npm), pass --ui-src=<abs path to packages/ui/src> or set LOTICS_UI_SRC; inside a monorepo checkout it is found automatically."
71366
- );
71367
- }
71368
- const hasComponent = fs4.existsSync(path5.join(uiSrc, `${args.component}.tsx`)) || fs4.existsSync(path5.join(uiSrc, `${args.component}.ts`)) || fs4.existsSync(path5.join(uiSrc, args.component));
71369
- if (!hasComponent) {
71370
- throw new Error(
71371
- `No '@lotics/ui/${args.component}' under ${uiSrc} (expected ${args.component}.tsx/.ts). Check the component name.`
71372
- );
71373
- }
71374
- const source = fs4.readFileSync(viteConfigPath, "utf-8");
71375
- const aliasEntry = `{ find: ${UI_ALIAS_FIND_SOURCE}, replacement: ${JSON.stringify(`${uiSrc}/$1`)} },`;
71376
- const alreadyLinked = source.includes(UI_ALIAS_FIND_SOURCE);
71377
- if (args.remove) {
71378
- if (!alreadyLinked) {
71379
- console.error("No @lotics/ui dev-link alias present \u2014 nothing to remove.");
71380
- return;
71381
- }
71382
- const stripped = source.replace(new RegExp(`^\\s*\\{ find: ${escapeRegExp(UI_ALIAS_FIND_SOURCE)}.*$\\n?`, "m"), "");
71383
- fs4.writeFileSync(viteConfigPath, stripped);
71384
- console.error(`Removed the @lotics/ui dev-link alias from ${viteConfigPath}.`);
71385
- console.error("Restart `lotics app dev` and rm -rf node_modules/.vite to clear cached modules.");
71386
- return;
71387
- }
71388
- if (alreadyLinked) {
71389
- console.error(`@lotics/ui is already dev-linked in ${viteConfigPath}.`);
71390
- return;
71391
- }
71392
- const aliasMatch = /resolve\s*:\s*\{[\s\S]*?alias\s*:\s*\[/.exec(source);
71393
- if (!aliasMatch) {
71394
- throw new Error(
71395
- `Could not find a resolve.alias array literal in ${viteConfigPath}. Refresh vite.config.ts from the starter (packages/sdk/src/starter_template.ts) and retry.`
71396
- );
71397
- }
71398
- const insertAt = aliasMatch.index + aliasMatch[0].length;
71399
- const updated = `${source.slice(0, insertAt)}
71400
- ${aliasEntry}${source.slice(insertAt)}`;
71401
- fs4.writeFileSync(viteConfigPath, updated);
71402
- console.error(`Dev-linked @lotics/ui \u2192 ${uiSrc} in ${viteConfigPath}.`);
71403
- console.error("Restart `lotics app dev` and rm -rf node_modules/.vite to clear cached modules.");
71404
- console.error("Finalize: PR the packages/ui change \u2192 publish \u2192 `lotics ui link <component> --remove` + bump the app's dep.");
71405
- }
71406
- function escapeRegExp(s) {
71407
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
71408
- }
71409
71414
 
71410
71415
  // src/args.ts
71411
71416
  function parseArgs(argv) {
@@ -71417,7 +71422,6 @@ function parseArgs(argv) {
71417
71422
  apiKey: void 0,
71418
71423
  workspace: void 0,
71419
71424
  viewAs: void 0,
71420
- uiSrc: void 0,
71421
71425
  name: void 0,
71422
71426
  description: void 0,
71423
71427
  from: void 0,
@@ -71464,9 +71468,6 @@ function parseArgs(argv) {
71464
71468
  case "--view-as":
71465
71469
  flags.viewAs = argv[++i2];
71466
71470
  break;
71467
- case "--ui-src":
71468
- flags.uiSrc = argv[++i2];
71469
- break;
71470
71471
  case "--name":
71471
71472
  flags.name = argv[++i2];
71472
71473
  break;
@@ -74226,6 +74227,7 @@ var ExpressionSet = class {
74226
74227
  this._byDepthAndTag = /* @__PURE__ */ new Map();
74227
74228
  this._wildcardByDepth = /* @__PURE__ */ new Map();
74228
74229
  this._deepWildcards = [];
74230
+ this._deepByTerminalTag = /* @__PURE__ */ new Map();
74229
74231
  this._patterns = /* @__PURE__ */ new Set();
74230
74232
  this._sealed = false;
74231
74233
  }
@@ -74250,7 +74252,14 @@ var ExpressionSet = class {
74250
74252
  if (this._patterns.has(expression.pattern)) return this;
74251
74253
  this._patterns.add(expression.pattern);
74252
74254
  if (expression.hasDeepWildcard()) {
74253
- this._deepWildcards.push(expression);
74255
+ const lastSeg2 = expression.segments[expression.segments.length - 1];
74256
+ if (lastSeg2 && lastSeg2.type !== "deep-wildcard" && lastSeg2.tag !== "*") {
74257
+ const tag2 = lastSeg2.tag;
74258
+ if (!this._deepByTerminalTag.has(tag2)) this._deepByTerminalTag.set(tag2, []);
74259
+ this._deepByTerminalTag.get(tag2).push(expression);
74260
+ } else {
74261
+ this._deepWildcards.push(expression);
74262
+ }
74254
74263
  return this;
74255
74264
  }
74256
74265
  const depth = expression.length;
@@ -74368,6 +74377,12 @@ var ExpressionSet = class {
74368
74377
  if (matcher.matches(wildcardBucket[i2])) return wildcardBucket[i2];
74369
74378
  }
74370
74379
  }
74380
+ const deepBucket = this._deepByTerminalTag.get(tag);
74381
+ if (deepBucket) {
74382
+ for (let i2 = 0; i2 < deepBucket.length; i2++) {
74383
+ if (matcher.matches(deepBucket[i2])) return deepBucket[i2];
74384
+ }
74385
+ }
74371
74386
  for (let i2 = 0; i2 < this._deepWildcards.length; i2++) {
74372
74387
  if (matcher.matches(this._deepWildcards[i2])) return this._deepWildcards[i2];
74373
74388
  }
@@ -74427,6 +74442,24 @@ var MatcherView = class {
74427
74442
  const current = path8[path8.length - 1];
74428
74443
  return current.values !== void 0 && attrName in current.values;
74429
74444
  }
74445
+ /**
74446
+ * Get the value of a "kept" attribute from the nearest ancestor (or
74447
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
74448
+ * @param {string} attrName
74449
+ * @returns {*}
74450
+ */
74451
+ getAnyParentAttr(attrName) {
74452
+ return this._matcher.getAnyParentAttr(attrName);
74453
+ }
74454
+ /**
74455
+ * Check whether any ancestor (or the current node) kept the given
74456
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
74457
+ * @param {string} attrName
74458
+ * @returns {boolean}
74459
+ */
74460
+ hasAnyParentAttr(attrName) {
74461
+ return this._matcher.hasAnyParentAttr(attrName);
74462
+ }
74430
74463
  /**
74431
74464
  * Get current node's sibling position (child index in parent).
74432
74465
  * @returns {number}
@@ -74505,30 +74538,32 @@ var Matcher = class {
74505
74538
  this.siblingStacks = [];
74506
74539
  this._pathStringCache = null;
74507
74540
  this._view = new MatcherView(this);
74541
+ this._keptAttrs = [];
74508
74542
  }
74509
74543
  /**
74510
74544
  * Push a new tag onto the path.
74511
74545
  * @param {string} tagName
74512
74546
  * @param {Object|null} [attrValues=null]
74513
74547
  * @param {string|null} [namespace=null]
74548
+ * @param {Object|null} [options=null]
74549
+ * @param {string[]} [options.keep] - Names of attributes (from attrValues)
74514
74550
  */
74515
- push(tagName, attrValues = null, namespace = null) {
74551
+ push(tagName, attrValues = null, namespace = null, options = null) {
74516
74552
  this._pathStringCache = null;
74517
74553
  if (this.path.length > 0) {
74518
74554
  this.path[this.path.length - 1].values = void 0;
74519
74555
  }
74520
74556
  const currentLevel = this.path.length;
74521
- if (!this.siblingStacks[currentLevel]) {
74522
- this.siblingStacks[currentLevel] = /* @__PURE__ */ new Map();
74557
+ let level = this.siblingStacks[currentLevel];
74558
+ if (!level) {
74559
+ level = { counts: /* @__PURE__ */ new Map(), total: 0 };
74560
+ this.siblingStacks[currentLevel] = level;
74523
74561
  }
74524
- const siblings = this.siblingStacks[currentLevel];
74525
74562
  const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;
74526
- const counter = siblings.get(siblingKey) || 0;
74527
- let position = 0;
74528
- for (const count of siblings.values()) {
74529
- position += count;
74530
- }
74531
- siblings.set(siblingKey, counter + 1);
74563
+ const counter = level.counts.get(siblingKey) || 0;
74564
+ const position = level.total;
74565
+ level.counts.set(siblingKey, counter + 1);
74566
+ level.total++;
74532
74567
  const node = {
74533
74568
  tag: tagName,
74534
74569
  position,
@@ -74541,6 +74576,16 @@ var Matcher = class {
74541
74576
  node.values = attrValues;
74542
74577
  }
74543
74578
  this.path.push(node);
74579
+ const depth = this.path.length;
74580
+ const keep = options !== null ? options.keep : null;
74581
+ if (keep !== null && keep !== void 0 && keep.length > 0 && attrValues) {
74582
+ for (let i2 = 0; i2 < keep.length; i2++) {
74583
+ const name = keep[i2];
74584
+ if (attrValues[name] !== void 0) {
74585
+ this._keptAttrs.push({ depth, name, value: attrValues[name] });
74586
+ }
74587
+ }
74588
+ }
74544
74589
  }
74545
74590
  /**
74546
74591
  * Pop the last tag from the path.
@@ -74553,6 +74598,10 @@ var Matcher = class {
74553
74598
  if (this.siblingStacks.length > this.path.length + 1) {
74554
74599
  this.siblingStacks.length = this.path.length + 1;
74555
74600
  }
74601
+ const poppedDepth = this.path.length + 1;
74602
+ while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) {
74603
+ this._keptAttrs.pop();
74604
+ }
74556
74605
  return node;
74557
74606
  }
74558
74607
  /**
@@ -74601,6 +74650,36 @@ var Matcher = class {
74601
74650
  const current = this.path[this.path.length - 1];
74602
74651
  return current.values !== void 0 && attrName in current.values;
74603
74652
  }
74653
+ /**
74654
+ * Get the value of a "kept" attribute from the nearest ancestor (or
74655
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
74656
+ * Unlike getAttrValue(), this works regardless of how deep the path has
74657
+ * gone since the attribute was pushed — but only for attribute names that
74658
+ * were explicitly marked with `keep` at push time. Cost is proportional to
74659
+ * the number of currently-kept attributes (typically 0-3), not path depth.
74660
+ * @param {string} attrName
74661
+ * @returns {*} the value, or undefined if no ancestor kept this attribute
74662
+ */
74663
+ getAnyParentAttr(attrName) {
74664
+ const kept = this._keptAttrs;
74665
+ for (let i2 = kept.length - 1; i2 >= 0; i2--) {
74666
+ if (kept[i2].name === attrName) return kept[i2].value;
74667
+ }
74668
+ return void 0;
74669
+ }
74670
+ /**
74671
+ * Check whether any ancestor (or the current node) kept the given
74672
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
74673
+ * @param {string} attrName
74674
+ * @returns {boolean}
74675
+ */
74676
+ hasAnyParentAttr(attrName) {
74677
+ const kept = this._keptAttrs;
74678
+ for (let i2 = kept.length - 1; i2 >= 0; i2--) {
74679
+ if (kept[i2].name === attrName) return true;
74680
+ }
74681
+ return false;
74682
+ }
74604
74683
  /**
74605
74684
  * Get current node's sibling position (child index in parent).
74606
74685
  * @returns {number}
@@ -74669,6 +74748,7 @@ var Matcher = class {
74669
74748
  this._pathStringCache = null;
74670
74749
  this.path = [];
74671
74750
  this.siblingStacks = [];
74751
+ this._keptAttrs = [];
74672
74752
  }
74673
74753
  /**
74674
74754
  * Match current path against an Expression.
@@ -74792,7 +74872,8 @@ var Matcher = class {
74792
74872
  snapshot() {
74793
74873
  return {
74794
74874
  path: this.path.map((node) => ({ ...node })),
74795
- siblingStacks: this.siblingStacks.map((map3) => new Map(map3))
74875
+ siblingStacks: this.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level),
74876
+ keptAttrs: this._keptAttrs.map((entry) => ({ ...entry }))
74796
74877
  };
74797
74878
  }
74798
74879
  /**
@@ -74802,7 +74883,8 @@ var Matcher = class {
74802
74883
  restore(snapshot) {
74803
74884
  this._pathStringCache = null;
74804
74885
  this.path = snapshot.path.map((node) => ({ ...node }));
74805
- this.siblingStacks = snapshot.siblingStacks.map((map3) => new Map(map3));
74886
+ this.siblingStacks = snapshot.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level);
74887
+ this._keptAttrs = (snapshot.keptAttrs || []).map((entry) => ({ ...entry }));
74806
74888
  }
74807
74889
  /**
74808
74890
  * Return the read-only {@link MatcherView} for this matcher.
@@ -89621,180 +89703,6 @@ var runSchema = external_exports.object({
89621
89703
  formatting: formattingSchema.optional()
89622
89704
  });
89623
89705
 
89624
- // ../ooxml/src/queries.ts
89625
- function getBodyElementType(el) {
89626
- const tag = getTagName(el);
89627
- if (tag === "w:p") return "paragraph";
89628
- if (tag === "w:tbl") return "table";
89629
- return "other";
89630
- }
89631
- function extractParagraphText(el) {
89632
- const tag = getTagName(el);
89633
- if (tag !== "w:p") return "";
89634
- const parts = [];
89635
- for (const child of getChildren(el)) {
89636
- const childTag = getTagName(child);
89637
- if (childTag === "w:r") {
89638
- for (const runChild of getChildren(child)) {
89639
- if (getTagName(runChild) === "w:t") {
89640
- parts.push(getTextContent(runChild));
89641
- }
89642
- }
89643
- } else if (childTag === "w:hyperlink") {
89644
- for (const hlChild of getChildren(child)) {
89645
- if (getTagName(hlChild) === "w:r") {
89646
- for (const runChild of getChildren(hlChild)) {
89647
- if (getTagName(runChild) === "w:t") {
89648
- parts.push(getTextContent(runChild));
89649
- }
89650
- }
89651
- }
89652
- }
89653
- }
89654
- }
89655
- return parts.join("");
89656
- }
89657
- function getParagraphTextSegments(el) {
89658
- const segments = [];
89659
- for (const child of getChildren(el)) {
89660
- if (getTagName(child) !== "w:r") continue;
89661
- let pending = [];
89662
- const flush = () => {
89663
- if (pending.length === 0) return;
89664
- const text = pending.map(
89665
- (node) => getChildren(node).reduce(
89666
- (acc, tn) => typeof tn["#text"] === "string" ? acc + tn["#text"] : acc,
89667
- ""
89668
- )
89669
- ).join("");
89670
- segments.push({ element: child, textNodes: pending, text });
89671
- pending = [];
89672
- };
89673
- for (const grandchild of getChildren(child)) {
89674
- if (getTagName(grandchild) === "w:t") {
89675
- pending.push(grandchild);
89676
- continue;
89677
- }
89678
- flush();
89679
- }
89680
- flush();
89681
- }
89682
- return segments;
89683
- }
89684
- function setSegmentText(segment, newText) {
89685
- const children = getChildren(segment.element);
89686
- const textNode = {
89687
- "w:t": [{ "#text": newText }],
89688
- ":@": { "@_xml:space": "preserve" }
89689
- };
89690
- const head = children.indexOf(segment.textNodes[0]);
89691
- children[head] = textNode;
89692
- for (let i2 = segment.textNodes.length - 1; i2 >= 1; i2--) {
89693
- const at2 = children.indexOf(segment.textNodes[i2]);
89694
- if (at2 >= 0) children.splice(at2, 1);
89695
- }
89696
- segment.textNodes = [textNode];
89697
- segment.text = newText;
89698
- }
89699
- function computeReplacementRanges(text, query, replacement, matchType, maxReplacements, startCount) {
89700
- const ranges = [];
89701
- let count = startCount;
89702
- if (matchType === "exact") {
89703
- if (text === query && count < maxReplacements) {
89704
- ranges.push({ start: 0, end: text.length, replacement });
89705
- count++;
89706
- }
89707
- return { ranges, count };
89708
- }
89709
- if (matchType === "regex") {
89710
- const re2 = new RegExp(query, "gi");
89711
- let match2;
89712
- while (count < maxReplacements && (match2 = re2.exec(text)) !== null) {
89713
- ranges.push({ start: match2.index, end: match2.index + match2[0].length, replacement });
89714
- count++;
89715
- if (match2[0].length === 0) re2.lastIndex++;
89716
- }
89717
- return { ranges, count };
89718
- }
89719
- if (query.length === 0) return { ranges, count };
89720
- const lower2 = text.toLowerCase();
89721
- const lowerQuery = query.toLowerCase();
89722
- let searchFrom = 0;
89723
- while (count < maxReplacements) {
89724
- const idx = lower2.indexOf(lowerQuery, searchFrom);
89725
- if (idx === -1) break;
89726
- ranges.push({ start: idx, end: idx + query.length, replacement });
89727
- searchFrom = idx + query.length;
89728
- count++;
89729
- }
89730
- return { ranges, count };
89731
- }
89732
- function applyRangeReplacements(segments, ranges) {
89733
- if (ranges.length === 0) return;
89734
- const bounds = [];
89735
- let offset = 0;
89736
- for (const segment of segments) {
89737
- bounds.push({ segment, start: offset, end: offset + segment.text.length });
89738
- offset += segment.text.length;
89739
- }
89740
- const joined = segments.map((s) => s.text).join("");
89741
- const sorted = [...ranges].sort((a, b) => a.start - b.start);
89742
- for (const { segment, start: segStart, end: segEnd } of bounds) {
89743
- let next = "";
89744
- let cursor = segStart;
89745
- for (const range2 of sorted) {
89746
- if (range2.end <= segStart || range2.start >= segEnd) continue;
89747
- const keepUntil = Math.min(range2.start, segEnd);
89748
- const from = Math.max(cursor, segStart);
89749
- if (keepUntil > from) next += joined.slice(from, keepUntil);
89750
- if (segStart <= range2.start && range2.start < segEnd) next += range2.replacement;
89751
- cursor = Math.max(cursor, range2.end);
89752
- }
89753
- const tail = Math.max(cursor, segStart);
89754
- if (segEnd > tail) next += joined.slice(tail, segEnd);
89755
- if (next !== segment.text) setSegmentText(segment, next);
89756
- }
89757
- }
89758
- function replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade) {
89759
- if (!extractParagraphText(el)) return replacementsMade;
89760
- const segments = getParagraphTextSegments(el);
89761
- if (segments.length === 0) return replacementsMade;
89762
- const text = segments.length === 1 ? segments[0].text : segments.map((s) => s.text).join("");
89763
- const { ranges, count } = computeReplacementRanges(text, query, replacement, matchType, maxReplacements, replacementsMade);
89764
- applyRangeReplacements(segments, ranges);
89765
- return count;
89766
- }
89767
- function replaceText(bodyElements, query, replacement, matchType = "contains", maxReplacements = Infinity) {
89768
- if (matchType === "regex") {
89769
- try {
89770
- new RegExp(query);
89771
- } catch {
89772
- throw new Error(`Invalid regex pattern: ${query}`);
89773
- }
89774
- }
89775
- let replacementsMade = 0;
89776
- for (let i2 = 0; i2 < bodyElements.length && replacementsMade < maxReplacements; i2++) {
89777
- const el = bodyElements[i2];
89778
- const type = getBodyElementType(el);
89779
- if (type === "paragraph") {
89780
- replacementsMade = replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade);
89781
- } else if (type === "table") {
89782
- for (const child of getChildren(el)) {
89783
- if (getTagName(child) !== "w:tr") continue;
89784
- for (const cell of getChildren(child)) {
89785
- if (getTagName(cell) !== "w:tc") continue;
89786
- for (const p of getChildren(cell)) {
89787
- if (getTagName(p) === "w:p" && replacementsMade < maxReplacements) {
89788
- replacementsMade = replaceInParagraph(p, query, replacement, matchType, maxReplacements, replacementsMade);
89789
- }
89790
- }
89791
- }
89792
- }
89793
- }
89794
- }
89795
- return replacementsMade;
89796
- }
89797
-
89798
89706
  // ../ooxml/src/sections.ts
89799
89707
  var PAGE_SIZES = {
89800
89708
  letter: { w: 12240, h: 15840 },
@@ -90847,6 +90755,9 @@ function parseBlock(el) {
90847
90755
  if (tag === "w:sectPr") return parseBodySectPr(el);
90848
90756
  return parseOpaqueBlock(el);
90849
90757
  }
90758
+ function parseBlockXml(el) {
90759
+ return parseBlock(el);
90760
+ }
90850
90761
  function parseParagraph(el) {
90851
90762
  const properties = [];
90852
90763
  const content = [];
@@ -91064,11 +90975,11 @@ function serializeDocumentXml(doc) {
91064
90975
  function serializeBody(body) {
91065
90976
  const out = [];
91066
90977
  for (const block of body.children) {
91067
- out.push(serializeBlock(block));
90978
+ out.push(serializeBlockXml(block));
91068
90979
  }
91069
90980
  return out;
91070
90981
  }
91071
- function serializeBlock(block) {
90982
+ function serializeBlockXml(block) {
91072
90983
  switch (block.kind) {
91073
90984
  case "paragraph":
91074
90985
  return serializeParagraph(block);
@@ -91318,7 +91229,8 @@ async function docxReplaceText(filePath, rest) {
91318
91229
  const doc = await loadFile2(filePath);
91319
91230
  const { children, count } = replaceEverywhere(doc.body.children, search, replace2);
91320
91231
  if (count === 0) {
91321
- fail2(`No occurrence of ${JSON.stringify(search)} in ${filePath} \u2014 nothing written.`);
91232
+ const why = explainNoMatch(doc.body.children, search);
91233
+ fail2(`No occurrence of ${JSON.stringify(search)} in ${filePath} \u2014 nothing written.${why ? ` ${why}` : ""}`);
91322
91234
  }
91323
91235
  await writeDoc(filePath, replaceChildren(doc, children));
91324
91236
  console.error(`Wrote ${filePath} (${count} replacement${count === 1 ? "" : "s"})`);
@@ -91327,13 +91239,12 @@ function replaceEverywhere(blocks, search, replace2) {
91327
91239
  let count = 0;
91328
91240
  const children = blocks.map((b) => {
91329
91241
  if (b.kind === "paragraph") {
91330
- const [paragraph, n] = replaceInParagraph2(b, search, replace2);
91242
+ const [paragraph, n] = replaceInParagraph(b, search, replace2);
91331
91243
  count += n;
91332
91244
  return paragraph;
91333
91245
  }
91334
91246
  if (b.kind === "opaque_block") {
91335
- const xml = structuredClone(b.xml);
91336
- const n = replaceText([xml], search, replace2, "contains");
91247
+ const [xml, n] = replaceInOpaque(b.xml, search, replace2);
91337
91248
  if (n === 0) return b;
91338
91249
  count += n;
91339
91250
  return { kind: "opaque_block", xml };
@@ -91342,7 +91253,27 @@ function replaceEverywhere(blocks, search, replace2) {
91342
91253
  });
91343
91254
  return { children, count };
91344
91255
  }
91345
- function replaceInParagraph2(p, search, replace2) {
91256
+ function replaceInOpaque(el, search, replace2) {
91257
+ const tag = getTagName(el);
91258
+ if (tag === void 0) return [el, 0];
91259
+ if (tag === "w:p") {
91260
+ const block = parseBlockXml(el);
91261
+ if (block.kind !== "paragraph") return [el, 0];
91262
+ const [paragraph, n] = replaceInParagraph(block, search, replace2);
91263
+ return n === 0 ? [el, 0] : [serializeBlockXml(paragraph), n];
91264
+ }
91265
+ let count = 0;
91266
+ const children = getChildren(el).map((child) => {
91267
+ if (isTextNode(child)) return child;
91268
+ const [next, n] = replaceInOpaque(child, search, replace2);
91269
+ count += n;
91270
+ return next;
91271
+ });
91272
+ if (count === 0) return [el, 0];
91273
+ const attrs = el[":@"];
91274
+ return [{ [tag]: children, ...attrs === void 0 ? {} : { ":@": attrs } }, count];
91275
+ }
91276
+ function replaceInParagraph(p, search, replace2) {
91346
91277
  if (search === "") return [p, 0];
91347
91278
  const rewritten = /* @__PURE__ */ new Map();
91348
91279
  let count = 0;
@@ -91381,6 +91312,71 @@ function replaceInParagraph2(p, search, replace2) {
91381
91312
  });
91382
91313
  return [{ kind: "paragraph", properties: p.properties, content }, count];
91383
91314
  }
91315
+ var ZERO_WIDTH_MARKS = /* @__PURE__ */ new Set([
91316
+ "w:proofErr",
91317
+ "w:footnoteReference",
91318
+ "w:endnoteReference",
91319
+ "w:commentReference",
91320
+ "w:commentRangeStart",
91321
+ "w:commentRangeEnd",
91322
+ "w:annotationRef",
91323
+ "w:bookmarkStart",
91324
+ "w:bookmarkEnd",
91325
+ "w:lastRenderedPageBreak"
91326
+ ]);
91327
+ function interruptsText(node) {
91328
+ const tag = getTagName(node.xml);
91329
+ return tag === void 0 || !ZERO_WIDTH_MARKS.has(tag);
91330
+ }
91331
+ function paragraphText(p) {
91332
+ let out = "";
91333
+ for (const inline of p.content) {
91334
+ if (inline.kind !== "run") continue;
91335
+ for (const child of inline.content) if (child.kind === "text") out += child.value;
91336
+ }
91337
+ return out;
91338
+ }
91339
+ function interruptingTags(p) {
91340
+ const tags = [];
91341
+ for (const inline of p.content) {
91342
+ if (inline.kind !== "run") {
91343
+ if (interruptsText(inline)) tags.push(getTagName(inline.xml) ?? "?");
91344
+ continue;
91345
+ }
91346
+ for (const child of inline.content) {
91347
+ if (child.kind !== "text" && interruptsText(child)) tags.push(getTagName(child.xml) ?? "?");
91348
+ }
91349
+ }
91350
+ return [...new Set(tags)];
91351
+ }
91352
+ function explainNoMatch(blocks, search) {
91353
+ for (const { index, paragraph, nested } of everyParagraph(blocks)) {
91354
+ if (!paragraphText(paragraph).includes(search)) continue;
91355
+ const tags = interruptingTags(paragraph);
91356
+ if (tags.length === 0) continue;
91357
+ const where = nested ? `inside block ${index}` : `at block ${index}`;
91358
+ return `The text IS present ${where}, split by ${tags.join(", ")} \u2014 replace-text will not join across those, because the joined string does not represent them. Search a shorter phrase that does not cross one.`;
91359
+ }
91360
+ return void 0;
91361
+ }
91362
+ function everyParagraph(blocks) {
91363
+ const out = [];
91364
+ const walk2 = (el, index) => {
91365
+ const tag = getTagName(el);
91366
+ if (tag === void 0) return;
91367
+ if (tag === "w:p") {
91368
+ const block = parseBlockXml(el);
91369
+ if (block.kind === "paragraph") out.push({ index, paragraph: block, nested: true });
91370
+ return;
91371
+ }
91372
+ for (const child of getChildren(el)) if (!isTextNode(child)) walk2(child, index);
91373
+ };
91374
+ for (const [index, block] of blocks.entries()) {
91375
+ if (block.kind === "paragraph") out.push({ index, paragraph: block, nested: false });
91376
+ else if (block.kind === "opaque_block") walk2(block.xml, index);
91377
+ }
91378
+ return out;
91379
+ }
91384
91380
  function collectTextSegments(p) {
91385
91381
  const segments = [];
91386
91382
  let current = [];
@@ -91392,12 +91388,12 @@ function collectTextSegments(p) {
91392
91388
  };
91393
91389
  p.content.forEach((inline, inlineIndex) => {
91394
91390
  if (inline.kind !== "run") {
91395
- breakSegment();
91391
+ if (interruptsText(inline)) breakSegment();
91396
91392
  return;
91397
91393
  }
91398
91394
  inline.content.forEach((child, childIndex) => {
91399
91395
  if (child.kind !== "text") {
91400
- breakSegment();
91396
+ if (interruptsText(child)) breakSegment();
91401
91397
  return;
91402
91398
  }
91403
91399
  current.push({
@@ -91456,7 +91452,10 @@ function applyBatchOp(doc, op, index) {
91456
91452
  }
91457
91453
  case "replace-text": {
91458
91454
  const { children, count } = replaceEverywhere(doc.body.children, op.search, op.replace);
91459
- if (count === 0) fail2(`[op ${index}] No occurrence of ${JSON.stringify(op.search)} \u2014 batch aborted.`);
91455
+ if (count === 0) {
91456
+ const why = explainNoMatch(doc.body.children, op.search);
91457
+ fail2(`[op ${index}] No occurrence of ${JSON.stringify(op.search)} \u2014 batch aborted.${why ? ` ${why}` : ""}`);
91458
+ }
91460
91459
  return replaceChildren(doc, children);
91461
91460
  }
91462
91461
  default: {
@@ -91482,7 +91481,13 @@ Uses Lotics' own OOXML engine; round-trips faithfully with the Lotics editor and
91482
91481
  lotics docx batch <file> '<json-array-of-ops>' Apply many ops in one parse/serialize cycle
91483
91482
 
91484
91483
  Edit ops mutate the file atomically (temp file + rename). Structure inside opaque blocks (tables, custom XML) is
91485
- preserved verbatim; replace-text rewrites the text within them.`);
91484
+ preserved verbatim; replace-text rewrites the text within them.
91485
+
91486
+ replace-text matches across run boundaries (Word splits a run at every formatting change) and reads through marks
91487
+ that take no place in the sentence \u2014 spell-check markers, footnote/endnote/comment refs, bookmarks. It will NOT
91488
+ join across something that occupies space in the text (a line break, tab, symbol, drawing, or any other tag),
91489
+ because the joined string does not represent it. The same rule applies inside a table cell as outside it. When a
91490
+ search fails but the words ARE on the page, the error names the block and the mark that split them.`);
91486
91491
  }
91487
91492
  async function runDocxCommand(subcommand, toolArgs, restArgs) {
91488
91493
  switch (subcommand) {
@@ -91946,10 +91951,6 @@ COMMANDS
91946
91951
  lotics knowledge update <id> [--from <file.md> | --content <str>] [--name <n>] [--description <d>]
91947
91952
  Update a doc \u2014 sends only the fields you pass
91948
91953
  lotics knowledge rm <id> Archive a doc
91949
- lotics ui link <component> [--ui-src <path>] [--remove]
91950
- Dev-link @lotics/ui to packages/ui/src (Vite alias
91951
- + tsc paths) for live HMR + typecheck. Monorepo apps
91952
- auto-find it; external apps pass --ui-src / LOTICS_UI_SRC
91953
91954
  lotics xlsx <subcommand> ... Read/write/edit .xlsx files on your local filesystem
91954
91955
  (uses the bundled Lotics xlsx engine; prefer over
91955
91956
  npm xlsx/exceljs for round-trip fidelity)
@@ -92368,22 +92369,6 @@ async function main() {
92368
92369
  await runPreviewCommand(subcommand, flags);
92369
92370
  return;
92370
92371
  }
92371
- if (command === "ui") {
92372
- if (subcommand === "link") {
92373
- const component = toolArgs;
92374
- if (!component) {
92375
- console.error("Usage: lotics ui link <component> [--ui-src <abs path>] [--remove]");
92376
- console.error("Dev-links @lotics/ui to packages/ui/src (Vite + tsc) for live HMR + typecheck.");
92377
- console.error("Monorepo apps find packages/ui/src automatically; external apps pass --ui-src / LOTICS_UI_SRC.");
92378
- process.exit(1);
92379
- }
92380
- appUiLink({ component, uiSrc: flags.uiSrc, remove: restArgs.includes("--remove") });
92381
- return;
92382
- }
92383
- console.error(`Unknown ui subcommand: ${subcommand ?? "(none)"}`);
92384
- console.error("Usage: lotics ui link <component> [--ui-src <abs path>] [--remove]");
92385
- process.exit(1);
92386
- }
92387
92372
  if (command === "app" && subcommand === "workflow" && toolArgs === "check") {
92388
92373
  await appWorkflowCheck({ alias: restArgs[0] });
92389
92374
  return;
@@ -30,21 +30,21 @@ Per-command syntax, flags, contracts, and gotchas for the public `lotics` CLI. S
30
30
  | `lotics knowledge rm <id>` | Archive the doc via `delete_knowledge` (`{ knowledge_doc_id }`). The REST execute path does not gate `needsApproval`, so this runs unattended. |
31
31
  | `lotics app create <name> [path]` | Scaffold a Vite+React+TS custom-code app project; POST /v1/apps; npm install; vite build; upload as v1 |
32
32
  | `lotics app pull <app_id> [path]` | Download source archive from R2 (presigned), extract, npm install, stamp package.json's `lotics` field. With no `[path]`: refresh the cwd IN PLACE when it's already this app's own project (its manifest `app_id` matches — the documented `cd <app> && lotics app pull` flow), else clone into an `<name>/` subdir; this avoids the stray nested `./<name>/` subdir a pull-from-inside-the-app used to drop. — `workflows` and `agents` are sourced from the live App row (NOT the archived manifest), so `set_app_workflow` / `set_app_agent` authoring survives the pull. Regenerates `.lotics/app_{workflows,queries,agents}.d.ts` so `useWorkflow` / `useQuery` / `useAgentRun` stay typed. Also writes one `src/workflows/<alias>.ts` per bound workflow (faithful body from `get_app_workflow`) and one `src/agents/<alias>.md` per bound agent (its instructions, straight off the live row) — so the prose an author actually edits lives in a file, and pull always overwrites it from live, leaving no second copy to drift. A legacy workflow alias with no rendered source, or an agent with no instructions, warns and is skipped. The stamped `lotics.agents` map carries the TYPED half only (`inputs`/`outputs`/`tool_names`/`model_id`/…) — an agent's prose lives solely in its `.md`, so there is never a second local copy to desync; a stale `instructions` left by an older CLI is inert and disappears on the next pull |
33
- | `lotics app deploy -m <message>` | **`-m` is REQUIRED** (CLI errors without a non-empty message) — each deploy is a version row read back by `lotics app versions`, so a blank message loses the audit trail. npm run build; tar source + dist; POST /v1/apps/{id}/versions multipart. Carries code + capabilities only — **neither queries nor workflow/agent bindings are a deploy concern** (`set_app_workflow` / `remove_app_workflow` own `apps.workflows`; the manifest's `workflows` map is a pulled reflection used only for `useWorkflow` codegen). Deploy DOES send the manifest's `lotics.workflows` alias KEYS (not the bindings) as `workflow_aliases`, recorded on the version row so `remove_app_workflow` can refuse to unbind an alias the served version still declares. It also reports any `lotics.queries` alias whose declaration DIFFERS from the app's, naming both recoveries (`app query set --all` to push yours, `app pull` to adopt the app's) — a deploy no longer writes them, so the two are allowed to drift. After a successful deploy it **warns loudly about any alias the source CALLS that is NOT bound on the server** (a `getApp` diff via `warnIfUnboundAliases`) — since deploy never binds them, that would otherwise throw only at the app's first `useWorkflow` / `useAgentRun` call; the warning points to `lotics app workflow set` / `set_app_agent`. Advisory only (never fails the deploy). |
33
+ | `lotics app deploy -m <message>` | **`-m` is REQUIRED** (CLI errors without a non-empty message) — each deploy is a version row read back by `lotics app versions`, so a blank message loses the audit trail. npm run build; tar source + dist; POST /v1/apps/{id}/versions multipart. Carries code + capabilities only — **neither queries nor workflow/agent bindings are a deploy concern** (`set_app_workflow` / `remove_app_workflow` own `apps.workflows`; the manifest's `workflows` map is a pulled reflection, read by `useWorkflow` codegen and by `app workflow set`, never written by a deploy). Deploy DOES send the manifest's `lotics.workflows` alias KEYS (not the bindings) as `workflow_aliases`, recorded on the version row so `remove_app_workflow` can refuse to unbind an alias the served version still declares. It also reports any `lotics.queries` alias whose declaration DIFFERS from the app's, naming both recoveries (`app query set --all` to push yours, `app pull` to adopt the app's) — a deploy no longer writes them, so the two are allowed to drift. After a successful deploy it **warns loudly about any alias the source CALLS that is NOT bound on the server** (a `getApp` diff via `warnIfUnboundAliases`) — since deploy never binds them, that would otherwise throw only at the app's first `useWorkflow` / `useAgentRun` call; the warning points to `lotics app workflow set` / `set_app_agent`. Advisory only (never fails the deploy). |
34
34
  | `lotics app versions [app_id]` | `GET /v1/apps/{id}/versions` — print deploy history newest-first (version number, timestamp, deployer name, build status, the `-m` message; `*` marks the currently-served version). app_id from the local manifest, or pass one to inspect any app without pulling it. Admin-only server-side (mirrors deploy + source download). Answers "what shipped, when, by whom" — e.g. whether a fix was live at an incident's time. The deploy pipeline already persisted all of this in `app_versions`; this is the read surface. Title → stderr, table → stdout (pipeable). |
35
35
  | `lotics app codegen [path]` | Regenerate `.lotics/*` from the manifest + workspace schema **without a deploy**. The three `.d.ts` companions (`app_{workflows,queries,agents}.d.ts`) are always rewritten (synchronous, no network). When credentials resolve, also rewrites the **runtime** `.lotics/app_fields.ts` — **branched on whether the app is a package installation** (`getApp().package_id` set, from `generate_package_fields.ts`): a **linked/published** app emits the BINDING form (`F`/`OPT`/`ROLE` resolved from the installation's LIVE binding — via `appBinding` / the `binding` RPC — at module load through `getAppBinding()` + top-level await, so the source stays portable across every install); a **bespoke** app emits the BAKED form (`generate_app_fields.ts`) — a real `.ts` exporting `F` (table→field→`"fld_…"`) + `OPT` (table→select-field→option→`"opt_…"`) keyed by display-name aliases, for the tables the app's queries reference (+ optional `package.json#lotics.codegen.tables` allowlist). Both forms share the `F`/`OPT` shape (contract aliases derive from the same slugified display names), so a published origin's deployed source compiles unchanged. Writing the BINDING form also heals the project's vitest setup (`ensureAppVitestSetup`, folded into the same write boundary): the binding form awaits `getAppBinding()` (a network call) at module load, so without a stub `npm test` fails to collect any test that imports the app graph — the heal writes `vitest.setup.ts` (mocks only `getAppBinding`, returning an echo binding: any alias → a self-identifying `fld:test:…`/`opt:test:…`/`grp:test:…` id) if absent, and warns the one-liner to add to `vite.config.ts`'s `test.setupFiles` if the wiring is missing (TS source isn't safely munged, mirroring `ensureAppTsconfig`'s JSONC-tsconfig warn). New scaffolds ship both. Also refreshes each bound workflow's `.lotics/workflows/<alias>.globals.d.ts` + re-wraps its EXISTING `src/workflows/<alias>.ts` body in the current envelope (strips + re-wraps; never re-fetches the body, so local edits survive). A getApp / binding / schema / dts-fetch failure is non-fatal (warns, keeps the last-generated files). |
36
36
  | `lotics app workflow run <alias> '<json>'` | Execute a bound app workflow end-to-end via `appWorkflow`. `app_id` comes from the local manifest; the alias must be bound (`set_app_workflow`). Inputs ingest exactly like `lotics run` (inline JSON / `@file` / stdin — bulk inputs bypass `ARG_MAX`). Prints the full `{status,message,data,files,side_effects}` JSON to stdout + a one-line summary to stderr; exits non-zero on `status:"error"` (assertable). `--print-created` (alias `--report-effects`) renders the honest post-run harvest (GAP-58): created records grouped by table, a paste-ready `lotics run delete_records …` per table, then the **mandatory caveat** naming what cannot be auto-undone (external integrations + notifications) and that sub-workflows may have run. `--cleanup` (DEFAULT OFF, implies the report) additionally runs the deletes for harvested records ONLY — never files / external / notifications. Neither is a rollback — a rollback is structurally impossible here. |
37
- | `lotics app workflow set <alias>` | Push the edited `src/workflows/<alias>.ts` body through `set_app_workflow` (the single author of `apps.workflows`). Reads the body from disk (header + `/// <reference>` + `export {};` marker + the `__workflow` wrapper all stripped) + the typed `inputs`/`outputs` from `package.json#lotics.workflows.<alias>`; the **server** re-verifies the body and echoes the bound `outputs` (declared, else DERIVED from `return({ data })`). When the manifest declared NO `outputs`, the DERIVED echo is written back into `package.json#lotics.workflows.<alias>.outputs` (a SURGICAL write — preserves `knowledge`/`config` and every other manifest field) and that alias's types are refreshed in place, so `useWorkflow("<alias>")`'s `result.data` is typed immediately with no hand-copy and no second `lotics app codegen`; an explicitly-declared `outputs` is authoritative and never overwritten. Deploy still never authors workflows — this is a CLI convenience over the existing tool. Clear error + non-zero exit on a missing file, an alias absent from the manifest, or a verify failure. |
37
+ | `lotics app workflow set <alias>` | Push the edited `src/workflows/<alias>.ts` body through `set_app_workflow` (the single author of `apps.workflows`). Reads the body from disk (header + `/// <reference>` + `export {};` marker + the `__workflow` wrapper all stripped) + the typed `inputs`/`outputs` **and the `description`** from `package.json#lotics.workflows.<alias>`; the **server** re-verifies the body and echoes the bound `outputs` (declared, else DERIVED from `return({ data })`). The `description` is the one line an agent reads when choosing between the app's aliases (the workflow counterpart to a query's) — authored in the manifest so it lives beside the body in version control and rides every push; omit it and the workflow keeps whatever description it already has, so a push can never blank one set elsewhere. When the manifest declared NO `outputs`, the DERIVED echo is written back into `package.json#lotics.workflows.<alias>.outputs` (a SURGICAL write — preserves `knowledge`/`config` and every other manifest field) and that alias's types are refreshed in place, so `useWorkflow("<alias>")`'s `result.data` is typed immediately with no hand-copy and no second `lotics app codegen`; an explicitly-declared `outputs` is authoritative and never overwritten. Deploy still never authors workflows — this is a CLI convenience over the existing tool. Clear error + non-zero exit on a missing file, an alias absent from the manifest, or a verify failure. |
38
38
  | `lotics app agent set <alias>` | Push the edited `src/agents/<alias>.md` instructions back through `set_app_agent` — the agent mirror of `app workflow set`, and the deploy-free authoring path for `apps.agents`. Reads the prose from disk (the `<!-- lotics: … -->` header stripped) and the typed fields (`inputs`/`outputs`/`tool_names`/`model_id`/`effort_level`/`knowledge_doc_ids`/`query_aliases`/`workflow_aliases`) from `package.json#lotics.agents.<alias>`, then sends them as ONE declaration. That assembly is the point: **`set_app_agent` REPLACES the declaration rather than patching it**, so a hand-built payload that sets one field silently drops the instructions, the output schema and the model pin — a silent, unrecoverable edit against a live prompt. Clear error + non-zero exit on a missing file, an alias absent from the manifest, or a file that is empty once the header is stripped (refusing to push an empty prompt). `app pull` writes the file; edit, then `set`. |
39
39
  | `lotics app query set <alias>` \| `--all` | Push `package.json#lotics.queries` (`{ ast, params? }` per alias) to `apps.queries` through `set_app_query` — **the only author of a query binding**, the mirror of `app workflow set`. A deploy ships code and binds nothing. The **server** validates each one exactly as it always did (alias identifier, workspace-only tables, resolvable fields, declared params). `--all` pushes every declared alias, alias-sorted, stopping at the first failure and naming what already landed. Clear error + non-zero exit on an alias absent from the manifest or a validation failure. |
40
40
  | `lotics app agent run <app_id> <alias> ['<json>'\|@file\|stdin]` | Run a bound app agent end-to-end (GAP-87). A run needs no deployed UI bundle — just the app row + the bound agent declaration + member auth — so the **`app_id` is explicit** (not read from a local manifest). Inputs ingest exactly like `lotics run` (inline JSON / `@file` / stdin; empty = `{}`). Opens the run's SSE (`appAgentRunStream`), streams `text-delta` prose to **stderr** as live progress, then reports from the **settled run RECORD** (`listAgentRuns`, polled to a terminal status — the client stream can close a beat before the run settles, or drop while it runs on server-side): default prints the run's structured `output` (JSON) or final text to **stdout** + a status line to stderr; `--json` prints the full run summary to stdout. Selects THIS run by the `x-app-agent-run-id` header (ordering-independent). Exits 0 **only** when the settled status is `completed`; otherwise non-zero with the run's error surfaced. A settled run that never appears fails loudly (never a silent success). A fresh `session_id` is minted per run (self-contained); `--session <id>` continues an existing thread (prior runs become the agent's context). |
41
- | `lotics app workflow pull` | Rewrite every `src/workflows/<alias>.ts` from the server (faithful body per bound alias via `get_app_workflow`) **+ its `.lotics/workflows/<alias>.globals.d.ts`** (via `getAppWorkflowDts`, so the body is locally typecheckable via `lotics app workflow check`) without a full `app pull` (no source archive, no npm install). A legacy alias with no rendered source warns and is skipped; a dts-fetch failure is non-fatal (body still written with the fallback wrapper, typecheck degraded). Also idempotently patches the main `tsconfig.json` `exclude` to cover `src/workflows` + `.lotics/workflows` so a pre-existing app's `npm run typecheck` never loads the bodies or the colliding per-alias globals. |
41
+ | `lotics app workflow pull` | Rewrite every `src/workflows/<alias>.ts` from the server (faithful body per bound alias via `get_app_workflow`) **+ its `.lotics/workflows/<alias>.globals.d.ts`** (via `getAppWorkflowDts`, so the body is locally typecheckable via `lotics app workflow check`) without a full `app pull` (no source archive, no npm install). A legacy alias with no rendered source warns and is skipped; a dts-fetch failure is non-fatal (body still written with the fallback wrapper, typecheck degraded). Each alias's `description` is folded back into `package.json#lotics.workflows.<alias>` from the same read — the alias binding the manifest is otherwise stamped from carries `inputs`/`outputs` but not the description, which lives on the workflow ROW, so without this a pull would erase an authored one. The server's GENERATED default is skipped, so an app that never described its workflows gains no manifest noise. Also idempotently patches the main `tsconfig.json` `exclude` to cover `src/workflows` + `.lotics/workflows` so a pre-existing app's `npm run typecheck` never loads the bodies or the colliding per-alias globals. |
42
42
  | `lotics app workflow check [alias]` | Check the editable workflow bodies locally, no auth / no network, in the **server's own order** — parse, then type-check. **Parse** runs `parseWorkflowJs` from `@lotics/shared` (the SAME module `verifyWorkflow` calls, never a second implementation — that is what let the two diverge once) over the stripped body `set` would upload, with `toolNames: undefined` (the CLI ships no tool registry, so tool-name resolution stays a server check while every shape/scope rule runs here). A body the subset rejects reports **that error alone** and skips the compiler — it never reaches the server's compiler either, so tsc's opinion of it is noise. **Type-check** then builds an **isolated** `ts.Program` per alias from exactly that alias's `{body, globals}` pair — mirroring the server, which verifies one body at a time — so the per-alias ambient `trigger` never collides and `trigger.app_workflow.inputs` is checked against the right alias (GAP-59). All aliases run in ONE node process (N programs, not N `tsc` spawns), with the SAME compile options the server uses at set-time verify (lib `es2022` with no DOM, target ES2022, strict, NodeNext, `types:[]`, skipLibCheck) and the app's OWN `typescript` (resolved from its `node_modules`, never bundled into the CLI). What the compiler sees is the **checked source**, not the file: `rewriteAccumulatorAppends` from `@lotics/shared` — the SAME transform the server applies before its set-time compile — is applied in memory, so a pulled body's canonical `out = concat(out, [item])` accumulator checks green here exactly as it saves there (compiling the raw text went red on it), and the body on disk is never rewritten. Reports `<file>:<line>:<col> - <TS####\|subset>` at the **physical** line in `src/workflows/<alias>.ts`, so an editor jump lands on the offending code (these are deliberately NOT `set`'s body-relative numbers — `set` prints no file path, so there is no format to agree with); exits non-zero if any alias fails. Green is honest but not total: `set` additionally resolves names, lints and structurally validates against the live workspace — passes that need its tables and tool schemas, so they cannot run offline, and the success line says so. A bound alias with no body file yet warns + skips; a body with no globals errors (run a pull). |
43
43
  | `lotics app subdomain <new-subdomain>` | Rename the app's public `<slug>.lotics.app` address via `PUT /v1/apps/{id}/subdomain`. app_id comes from the local `package.json` manifest; the chosen slug must be a valid DNS label and free; the old address stops resolving. |
44
44
  | `lotics app rename "<new name>"` | Change the app's display name (launcher/title) via the `update_app` tool. app_id comes from the local `package.json` manifest; the public address (`subdomain`) and code (`deploy`) are unchanged. |
45
45
  | `lotics app dev [path] [--port=N] [--vite-port=N] [--view-as=<member_id>]` | Spawn Vite dev server + an RPC-forwarding HTTP server. The wrapper page embeds the iframe with `sandbox="allow-scripts allow-same-origin"` matching production; postMessage ops (query / workflow / members / context / upload / openExternal / urlState / agentRun) are forwarded to api.lotics.ai using the CLI's API key — file bytes move in **both** directions through the dev server's own relays, never browser↔storage (the former GAP-44): dev runs against the PROD bucket, whose CORS admits `https://*.lotics.app` and not `http://localhost:<port>`, so a direct browser transfer is blocked — no upload could complete and no preview engine (PDF/Word/Excel all FETCH the bytes) could read a file. `upload` mints a presigned URL and PUTs it **to `PUT /_upload/<file_id>`** (`dev/upload_relay.ts`) from the wrapper page — same-origin, so no preflight and no CORS — and Node forwards it on; every presigned `url`/`thumbnail_url`/`preview_url` on a **file object** in an RPC result is rewritten to **`GET /_file/<token>`** (`dev/file_relay.ts`, absolute — the iframe would resolve a relative path against Vite), which streams the bytes back with `Range` passthrough (206s intact, so PDF seeking works) and an `Access-Control-Allow-Origin` for the Vite origin (the one cross-origin hop left is OUR response to allow). Neither relay ever takes a destination from the client — it gets a `file_id`/token and transfers only to/from a URL it minted or observed itself, so there is no client-controlled target and no SSRF surface. A URL in a record's own text cell is NOT rewritten. Production is unchanged (direct-to-storage, no bytes through the API server); `openExternal` and `urlState.get/set` are handled locally (the latter read/write the wrapper page's own address bar — `set` writes in place via `replaceState` and browser back/forward broadcast a `url-state` message back, so `useUrlState` survives refresh and is shareable in the dev loop; in-app *routing* is the app's own (the iframe owns its url via `@lotics/app-sdk/router`), and the wrapper bakes the saved screen (`_loc`) into the iframe src on load so a refresh restores it, mirroring production); `agentRun` (streaming) is proxied through `POST /_agent_run`, which opens the run's SSE with the CLI key and pipes chunks back to the iframe (`stream-chunk`* → `stream-end`), so `useAgentRun` works in the dev loop just like production; `context` resolves the viewer (`member_id` from `cli/whoami` + `comments_enabled` from the local manifest) and fetches the installation's stored `config` live from the app row, so `useConfig()` renders the same values as production. `--view-as` (global flag; also `LOTICS_VIEW_AS`) threads `x-view-as-member-id` so `is_current_member` + `context` resolve to that member — **admin key only** (the server 403s a non-admin), writes stay attributed to the key owner. Hot reload via Vite; full DevTools / Playwright access via plain localhost. The dev-optimizer pre-bundle list (`optimizeDeps.include`, load-bearing for dev) is imported from `@lotics/ui/vite` (`loticsOptimizeDeps`) rather than hardcoded in the scaffold, so it tracks the installed `@lotics/ui` and can never go stale. Binds **loopback only** (`127.0.0.1`) — `/_rpc` dispatches with the developer's API key, so a socket on every interface would hand anyone on the network full read/write on the workspace. |
46
- | `lotics ui link <component> [--ui-src <path>] [--remove]` | Dev-link `@lotics/ui` to `packages/ui/src` by inserting (or removing) a package-wide `{ find: /^@lotics\/ui\/(.+)$/, replacement: "<absUiSrc>/$1" }` alias in the app's `vite.config.ts` resolve.alias — so edits to `packages/ui/src` go live (HMR) and bundle on deploy, without a publish round-trip. **`packages/ui/src` resolution:** walk up for a monorepo checkout, else the explicit `--ui-src <abs path>` / `LOTICS_UI_SRC` env — that's how an **EXTERNAL app** (one that consumes `@lotics/ui` from npm, e.g. under `~/lotics_apps`) links the local kit; fails loud when neither resolves, or when `--ui-src` isn't a directory. No auth (local file edit). Idempotent. `component` is advisory/validation only (the alias covers every subpath). **Vite-only, by design:** the app's `tsc` still resolves `@lotics/ui` from `node_modules` (the published `.d.ts`) — the kit `src` can't be typechecked inside an app because it's RN-Web (uses `react-native-web` types the app resolves as base `react-native`), so typecheck the kit in `packages/ui` and let the finalize publish restore the app's own typecheck. Reminds to restart dev + `rm node_modules/.vite`, and to finalize (`--remove` + publish-chain bump). |
46
+ | `LOTICS_UI_SRC=<abs path to packages/ui/src>` (env, not a command) | Dev-link `@lotics/ui` to a monorepo checkout for the length of ONE command: the app's own `vite.config.ts` reads the variable and adds a `{ find: /^@lotics\/ui\/(.+)$/, replacement: "<LOTICS_UI_SRC>/$1" }` entry to `resolve.alias`, so kit edits go live under `lotics app dev` (HMR) and bundle under `lotics app deploy`. Unset ⇒ the kit resolves from `node_modules` as normal. **Nothing is written to disk** — there is no link/unlink step, nothing to leave switched on, and no config for the CLI to corrupt (the `lotics ui link` command this replaces edited `vite.config.ts` by regex and twice deleted the load-bearing `react-native` → `react-native-web` alias with the array's closing bracket, breaking the app's build entirely — GAP-133/142). Identical for a monorepo app and an EXTERNAL one (e.g. `~/lotics_apps`). `app dev` **warns** when the variable is set but the app's `vite.config.ts` predates it (scaffolded earlier) and prints the lines to add; `app deploy` **warns** that the bundle carries kit code from your working copy rather than the published package. **Vite-only, by design:** the app's `tsc` still resolves `@lotics/ui` from `node_modules` (the published `.d.ts`) — the kit `src` can't be typechecked inside an app because it's RN-Web, so typecheck the kit in `packages/ui` and let the finalize publish restore the app's own typecheck. |
47
47
  | `lotics xlsx <subcmd>` | Local .xlsx read/write/edit using the bundled `@lotics/xlsx` engine (no auth, no network). 14 named subcommands (read, write, set-cell, clear-range, merge, unmerge, add-sheet, delete-sheet, rename-sheet, insert-rows, delete-rows, insert-cols, delete-cols, set-style) + `batch` for applying multiple of the same 14 ops in a single parse/export cycle. `read` also takes `--sheet <name>` (limit output to one sheet — unknown name fails with the available list) and `--range <sheet>!<A1:G60>` (limit to a cell window; the `<sheet>!` prefix is optional when `--sheet` supplies the sheet, a single cell like `S1!B2` is a 1×1 window) to trim a large workbook's JSON — the output shape is unchanged, only the `sheets` array and each sheet's `cells` map are filtered. Atomic in-place write (temp file + rename). |
48
- | `lotics docx <subcmd>` | Local .docx read/write/edit using the bundled `@lotics/docx` engine (OOXML round-trip surface only — no ProseMirror baggage). Subcommands: read, write, append-paragraph, insert-paragraph, delete-block, replace-text, batch. A legacy `.doc` (Word 97–2003 OLE2 binary) is detected in `loadFile` and routed through `@lotics/ooxml`'s `loadDocxFromBuffer` (which re-emits it as real OOXML) before reading — so `lotics docx read` works on a `.doc`, not just a `.docx`. Opaque blocks (tables, custom XML) preserved verbatim. Atomic in-place write. |
48
+ | `lotics docx <subcmd>` | Local .docx read/write/edit using the bundled `@lotics/docx` engine (OOXML round-trip surface only — no ProseMirror baggage). Subcommands: read, write, append-paragraph, insert-paragraph, delete-block, replace-text, batch. A legacy `.doc` (Word 97–2003 OLE2 binary) is detected in `loadFile` and routed through `@lotics/ooxml`'s `loadDocxFromBuffer` (which re-emits it as real OOXML) before reading — so `lotics docx read` works on a `.doc`, not just a `.docx`. Opaque blocks (tables, custom XML) preserved verbatim. Atomic in-place write. **`replace-text` matches across run boundaries** — Word splits a run at every formatting change, so a `{{marker}}` routinely lands split — and reads straight THROUGH marks that occupy no place in the sentence (`w:proofErr`, `w:footnoteReference`, endnote/comment refs + ranges, `w:bookmarkStart`/`End`, `w:lastRenderedPageBreak`). `w:proofErr` is the one that decides whether this works in practice — Word brackets every word its dictionary rejects, so on non-English text it lands between nearly every pair of runs. It still refuses to join across anything that occupies space in the text — `w:br`, `w:tab`, `w:sym`, a drawing, or any tag not on that allowlist — because the joined string does not represent the glyph and a match there would rewrite text the caller never saw. The SAME rule applies inside a table cell as outside it — both run one `replaceInParagraph` over paragraphs found at any depth, so a marker split by a line break is refused in both rather than rewritten in the cell and skipped in the body under a success message. Zero matches is always a hard error, never a silent no-op, and when the words ARE on the page the error names the block and the splitting mark (`The text IS present at block 1, split by w:br …`) rather than claiming the text is absent. |
49
49
  | `lotics file preview <file\|fil_id> [-o out.png]` | (also `lotics preview`) Render a .docx/.xlsx to a PNG using the SAME engines the frontend FilePreview uses (`@lotics/docx` `loadDocxIntoElement` / `@lotics/xlsx` `drawSpreadsheet`) — so what you see matches an operator. Accepts a **local path** OR a stored **`fil_…` id** (`isStoredFileId` — a bare id, no extension): an id is first downloaded to a temp dir via `downloadFileById` (the `signed_url` presign path — same authority as `lotics file download`), rendered, then the transient source is removed; with no `-o` the PNG lands in cwd under the stored file's base name (`defaultPreviewOutputPath`). Drives a headless Chrome over **CDP with only Node built-ins** (`WebSocket`/`fetch`/`http`/`child_process`) — zero npm deps, the CLI stays a single bundled binary. The browser render logic is a separate esbuild **browser** bundle shipped at `dist/render_page.js` (built by `build_cli.mjs`, excluded from the node `tsgo`), served over a throwaway localhost http server and screenshotted full-page. **Requires a Chrome/Chromium on the machine** — detected from `CHROME_PATH`/`LOTICS_CHROME`, then Playwright's installed chromium, then system paths — inherent to rendering these browser formats; a clear "install a browser" error otherwise. PDFs need no render (open them directly). |
50
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lotics/cli",
3
- "version": "0.101.1",
3
+ "version": "0.103.0",
4
4
  "description": "Lotics SDK and CLI for AI agents",
5
5
  "type": "module",
6
6
  "bin": {