agent-remnote 1.1.0 → 1.3.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/dist/main.js CHANGED
@@ -75988,7 +75988,37 @@ var migration6 = {
75988
75988
  };
75989
75989
 
75990
75990
  // src/internal/store/migrations/index.ts
75991
- var migrationSpecs = [migration, migration2, migration3, migration4, migration5, migration6];
75991
+ var BACKUP_ARTIFACTS_TABLE_SQL = `CREATE TABLE IF NOT EXISTS backup_artifacts (
75992
+ source_op_id TEXT PRIMARY KEY,
75993
+ source_txn TEXT NOT NULL,
75994
+ source_op_type TEXT NOT NULL CHECK (source_op_type IN ('replace_children_with_markdown','replace_selection_with_markdown')),
75995
+ backup_kind TEXT NOT NULL CHECK (backup_kind IN ('children_replace','selection_replace')),
75996
+ cleanup_policy TEXT NOT NULL CHECK (cleanup_policy IN ('auto','visible')),
75997
+ cleanup_state TEXT NOT NULL CHECK (cleanup_state IN ('pending','orphan','retained','cleaned')),
75998
+ backup_rem_id TEXT,
75999
+ source_parent_id TEXT,
76000
+ source_anchor_id TEXT,
76001
+ result_json TEXT NOT NULL DEFAULT '{}',
76002
+ created_at INTEGER NOT NULL,
76003
+ updated_at INTEGER NOT NULL,
76004
+ cleaned_at INTEGER
76005
+ );`;
76006
+ var IDX_BACKUP_ARTIFACTS_STATE_SQL = `CREATE INDEX IF NOT EXISTS idx_backup_artifacts_state ON backup_artifacts(cleanup_state, updated_at DESC);`;
76007
+ var IDX_BACKUP_ARTIFACTS_KIND_SQL = `CREATE INDEX IF NOT EXISTS idx_backup_artifacts_kind ON backup_artifacts(backup_kind, updated_at DESC);`;
76008
+ var UQ_BACKUP_ARTIFACTS_REM_SQL = `CREATE UNIQUE INDEX IF NOT EXISTS uq_backup_artifacts_backup_rem_id ON backup_artifacts(backup_rem_id) WHERE backup_rem_id IS NOT NULL;`;
76009
+ var m0007 = {
76010
+ version: 7,
76011
+ name: "add_backup_artifacts",
76012
+ checksumInput: [BACKUP_ARTIFACTS_TABLE_SQL, IDX_BACKUP_ARTIFACTS_STATE_SQL, IDX_BACKUP_ARTIFACTS_KIND_SQL, UQ_BACKUP_ARTIFACTS_REM_SQL].join(`
76013
+ `),
76014
+ apply: (db) => {
76015
+ db.exec(BACKUP_ARTIFACTS_TABLE_SQL);
76016
+ db.exec(IDX_BACKUP_ARTIFACTS_STATE_SQL);
76017
+ db.exec(IDX_BACKUP_ARTIFACTS_KIND_SQL);
76018
+ db.exec(UQ_BACKUP_ARTIFACTS_REM_SQL);
76019
+ }
76020
+ };
76021
+ var migrationSpecs = [migration, migration2, migration3, migration4, migration5, migration6, m0007];
75992
76022
 
75993
76023
  // src/internal/store/db.ts
75994
76024
  class StoreSchemaError extends Error {
@@ -76128,6 +76158,32 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_workspace_bindings_current
76128
76158
 
76129
76159
  CREATE INDEX IF NOT EXISTS idx_workspace_bindings_updated_at
76130
76160
  ON workspace_bindings(updated_at DESC);
76161
+
76162
+ CREATE TABLE IF NOT EXISTS backup_artifacts (
76163
+ source_op_id TEXT PRIMARY KEY,
76164
+ source_txn TEXT NOT NULL,
76165
+ source_op_type TEXT NOT NULL CHECK (source_op_type IN ('replace_children_with_markdown','replace_selection_with_markdown')),
76166
+ backup_kind TEXT NOT NULL CHECK (backup_kind IN ('children_replace','selection_replace')),
76167
+ cleanup_policy TEXT NOT NULL CHECK (cleanup_policy IN ('auto','visible')),
76168
+ cleanup_state TEXT NOT NULL CHECK (cleanup_state IN ('pending','orphan','retained','cleaned')),
76169
+ backup_rem_id TEXT,
76170
+ source_parent_id TEXT,
76171
+ source_anchor_id TEXT,
76172
+ result_json TEXT NOT NULL DEFAULT '{}',
76173
+ created_at INTEGER NOT NULL,
76174
+ updated_at INTEGER NOT NULL,
76175
+ cleaned_at INTEGER
76176
+ );
76177
+
76178
+ CREATE INDEX IF NOT EXISTS idx_backup_artifacts_state
76179
+ ON backup_artifacts(cleanup_state, updated_at DESC);
76180
+
76181
+ CREATE INDEX IF NOT EXISTS idx_backup_artifacts_kind
76182
+ ON backup_artifacts(backup_kind, updated_at DESC);
76183
+
76184
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_backup_artifacts_backup_rem_id
76185
+ ON backup_artifacts(backup_rem_id)
76186
+ WHERE backup_rem_id IS NOT NULL;
76131
76187
  `;
76132
76188
  function absoluteDefaultStorePath() {
76133
76189
  return path12.join(homeDir(), ".agent-remnote", "store.sqlite");
@@ -76496,6 +76552,102 @@ function maybeInitializeDefaultStoreFromLegacy(resolvedStorePath, params3) {
76496
76552
  } catch {}
76497
76553
  }
76498
76554
  }
76555
+
76556
+ // src/internal/store/index.ts
76557
+ function normalizeString(value8) {
76558
+ return typeof value8 === "string" ? value8.trim() : "";
76559
+ }
76560
+ function normalizeNullableString(value8) {
76561
+ const normalized = normalizeString(value8);
76562
+ return normalized || null;
76563
+ }
76564
+ function upsertBackupArtifact(db, params3) {
76565
+ const sourceOpId = normalizeString(params3.sourceOpId);
76566
+ const sourceTxn = normalizeString(params3.sourceTxn);
76567
+ const sourceOpType = normalizeString(params3.sourceOpType);
76568
+ if (!sourceOpId || !sourceTxn || !sourceOpType)
76569
+ return;
76570
+ const now2 = Number.isFinite(params3.now) ? Math.floor(params3.now) : Date.now();
76571
+ const existing = db.prepare(`SELECT created_at FROM backup_artifacts WHERE source_op_id=?`).get(sourceOpId);
76572
+ const createdAt = Number.isFinite(existing?.created_at) ? Math.floor(existing.created_at) : now2;
76573
+ const cleanedAt = params3.cleanedAt === null ? null : Number.isFinite(params3.cleanedAt) ? Math.floor(params3.cleanedAt) : params3.cleanupState === "cleaned" ? now2 : null;
76574
+ db.prepare(`INSERT INTO backup_artifacts(
76575
+ source_op_id, source_txn, source_op_type, backup_kind, cleanup_policy, cleanup_state,
76576
+ backup_rem_id, source_parent_id, source_anchor_id, result_json, created_at, updated_at, cleaned_at
76577
+ ) VALUES (
76578
+ @source_op_id, @source_txn, @source_op_type, @backup_kind, @cleanup_policy, @cleanup_state,
76579
+ @backup_rem_id, @source_parent_id, @source_anchor_id, @result_json, @created_at, @updated_at, @cleaned_at
76580
+ )
76581
+ ON CONFLICT(source_op_id) DO UPDATE SET
76582
+ source_txn=excluded.source_txn,
76583
+ source_op_type=excluded.source_op_type,
76584
+ backup_kind=excluded.backup_kind,
76585
+ cleanup_policy=excluded.cleanup_policy,
76586
+ cleanup_state=excluded.cleanup_state,
76587
+ backup_rem_id=excluded.backup_rem_id,
76588
+ source_parent_id=excluded.source_parent_id,
76589
+ source_anchor_id=excluded.source_anchor_id,
76590
+ result_json=excluded.result_json,
76591
+ updated_at=excluded.updated_at,
76592
+ cleaned_at=excluded.cleaned_at`).run({
76593
+ source_op_id: sourceOpId,
76594
+ source_txn: sourceTxn,
76595
+ source_op_type: sourceOpType,
76596
+ backup_kind: params3.backupKind,
76597
+ cleanup_policy: params3.cleanupPolicy,
76598
+ cleanup_state: params3.cleanupState,
76599
+ backup_rem_id: normalizeNullableString(params3.backupRemId),
76600
+ source_parent_id: normalizeNullableString(params3.sourceParentId),
76601
+ source_anchor_id: normalizeNullableString(params3.sourceAnchorId),
76602
+ result_json: JSON.stringify(params3.result ?? {}),
76603
+ created_at: createdAt,
76604
+ updated_at: now2,
76605
+ cleaned_at: cleanedAt
76606
+ });
76607
+ }
76608
+ function listBackupArtifacts(db, params3) {
76609
+ const states = Array.isArray(params3?.states) && params3.states.length > 0 ? Array.from(new Set(params3.states)) : [];
76610
+ const kinds = Array.isArray(params3?.kinds) && params3.kinds.length > 0 ? Array.from(new Set(params3.kinds)) : [];
76611
+ const limitRaw = Number(params3?.limit ?? 100);
76612
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(500, Math.floor(limitRaw)) : 100;
76613
+ const where = [];
76614
+ const args2 = [];
76615
+ if (!params3?.includeCleaned && states.length === 0) {
76616
+ where.push(`cleanup_state != 'cleaned'`);
76617
+ }
76618
+ if (states.length > 0) {
76619
+ where.push(`cleanup_state IN (${states.map(() => "?").join(", ")})`);
76620
+ args2.push(...states);
76621
+ }
76622
+ if (kinds.length > 0) {
76623
+ where.push(`backup_kind IN (${kinds.map(() => "?").join(", ")})`);
76624
+ args2.push(...kinds);
76625
+ }
76626
+ const backupRemId = normalizeString(params3?.backupRemId);
76627
+ if (backupRemId) {
76628
+ where.push(`backup_rem_id = ?`);
76629
+ args2.push(backupRemId);
76630
+ }
76631
+ const olderThanHours = Number(params3?.olderThanHours);
76632
+ if (Number.isFinite(olderThanHours) && olderThanHours > 0) {
76633
+ where.push(`created_at <= ?`);
76634
+ args2.push(Date.now() - Math.floor(olderThanHours * 60 * 60 * 1000));
76635
+ }
76636
+ const sql = `SELECT * FROM backup_artifacts` + (where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "") + ` ORDER BY updated_at DESC LIMIT ${limit}`;
76637
+ return db.prepare(sql).all(...args2);
76638
+ }
76639
+ function updateBackupArtifactsCleanupState(db, params3) {
76640
+ const sourceOpIds = Array.from(new Set(params3.sourceOpIds.map((item) => normalizeString(item)).filter(Boolean)));
76641
+ if (sourceOpIds.length === 0)
76642
+ return 0;
76643
+ const now2 = Number.isFinite(params3.now) ? Math.floor(params3.now) : Date.now();
76644
+ const cleanedAt = params3.cleanupState === "cleaned" ? now2 : null;
76645
+ const result = db.prepare(`UPDATE backup_artifacts
76646
+ SET cleanup_state=?, updated_at=?, cleaned_at=?
76647
+ WHERE source_op_id IN (${sourceOpIds.map(() => "?").join(", ")})`).run(params3.cleanupState, now2, cleanedAt, ...sourceOpIds);
76648
+ return Number(result.changes ?? 0);
76649
+ }
76650
+
76499
76651
  // src/internal/queue/db.ts
76500
76652
  class QueueSchemaError extends Error {
76501
76653
  _tag = "QueueSchemaError";
@@ -76610,10 +76762,16 @@ var OP_CATALOG = {
76610
76762
  delete_rem: {
76611
76763
  op_type: "delete_rem",
76612
76764
  aliases: ["rem.delete"],
76613
- payload: { required: ["rem_id"], optional: [] },
76765
+ payload: { required: ["rem_id"], optional: ["max_delete_subtree_nodes"] },
76614
76766
  description: "Delete a Rem.",
76615
76767
  id_fields: ["rem_id"]
76616
76768
  },
76769
+ delete_backup_artifact: {
76770
+ op_type: "delete_backup_artifact",
76771
+ payload: { required: ["rem_id"], optional: ["max_delete_subtree_nodes"] },
76772
+ description: "Delete a backup artifact and verify the Rem is actually gone.",
76773
+ id_fields: ["rem_id"]
76774
+ },
76617
76775
  create_single_rem_with_markdown: {
76618
76776
  op_type: "create_single_rem_with_markdown",
76619
76777
  aliases: ["rem.createSingleWithMarkdown"],
@@ -76635,7 +76793,7 @@ var OP_CATALOG = {
76635
76793
  op_type: "replace_selection_with_markdown",
76636
76794
  payload: {
76637
76795
  required: ["markdown"],
76638
- optional: ["target", "require_same_parent", "require_contiguous", "portal_id"]
76796
+ optional: ["target", "require_same_parent", "require_contiguous", "portal_id", "assertions"]
76639
76797
  },
76640
76798
  description: "Replace a selection of Rems with Markdown.",
76641
76799
  id_fields: ["target.rem_ids[]", "portal_id"]
@@ -76644,7 +76802,7 @@ var OP_CATALOG = {
76644
76802
  op_type: "replace_children_with_markdown",
76645
76803
  payload: {
76646
76804
  required: ["parent_id", "markdown"],
76647
- optional: ["indent_mode", "indent_size", "parse_mode", "prepared", "staged", "bundle"]
76805
+ optional: ["indent_mode", "indent_size", "parse_mode", "prepared", "staged", "bundle", "backup", "assertions"]
76648
76806
  },
76649
76807
  description: "Replace the direct children of a Rem with Markdown.",
76650
76808
  id_fields: ["parent_id"]
@@ -76872,7 +77030,7 @@ function isCreateOp(opType) {
76872
77030
  return opType.startsWith("create_") || opType === "create_tree_with_markdown" || opType === "create_single_rem_with_markdown" || opType === "create_link_rem";
76873
77031
  }
76874
77032
  function isStructureOp(opType) {
76875
- return opType === "move_rem" || opType === "delete_rem" || opType === "replace_selection_with_markdown" || opType === "replace_children_with_markdown";
77033
+ return opType === "move_rem" || opType === "delete_rem" || opType === "delete_backup_artifact" || opType === "replace_selection_with_markdown" || opType === "replace_children_with_markdown";
76876
77034
  }
76877
77035
  function deriveConflictKeys(opTypeRaw, payload) {
76878
77036
  const opType = canonicalizeOpType(opTypeRaw);
@@ -77463,11 +77621,11 @@ function riskScore(risk) {
77463
77621
  }
77464
77622
  }
77465
77623
  function computeConflictClusterRisk(params3) {
77466
- const hasDelete = params3.opTypes.has("delete_rem");
77624
+ const hasDelete = params3.opTypes.has("delete_rem") || params3.opTypes.has("delete_backup_artifact");
77467
77625
  if (hasDelete && params3.opCount > 0) {
77468
77626
  return {
77469
77627
  risk: "high",
77470
- note: "delete_rem mixed with other ops; execution order matters and may require manual review"
77628
+ note: "destructive delete op mixed with other ops; execution order matters and may require manual review"
77471
77629
  };
77472
77630
  }
77473
77631
  if (params3.conflictKey.startsWith("global:")) {
@@ -77857,6 +78015,21 @@ function handleOpAckMessage(params3) {
77857
78015
  }
77858
78016
  }
77859
78017
  ];
78018
+ try {
78019
+ syncBackupArtifactFromAck(params3.db, {
78020
+ now: params3.now,
78021
+ opId,
78022
+ status: status2,
78023
+ result: params3.msg?.result ?? null
78024
+ });
78025
+ } catch (error4) {
78026
+ actions.push({
78027
+ _tag: "Log",
78028
+ level: "warn",
78029
+ event: "backup_artifact_sync_failed",
78030
+ details: { connId: params3.connId, opId, attemptId, status: status2, error: String(error4) }
78031
+ });
78032
+ }
77860
78033
  if (status2 === "success" && ackRes.duplicate === false) {
77861
78034
  try {
77862
78035
  const mappings = [];
@@ -77950,6 +78123,36 @@ function handleOpAckMessage(params3) {
77950
78123
  });
77951
78124
  return { actions, touchAckTimestamp: true, invalidateStatusLineReason: "op_acked" };
77952
78125
  }
78126
+ function syncBackupArtifactFromAck(db, params3) {
78127
+ const opRow = db.prepare(`SELECT txn_id, type, payload_json FROM queue_ops WHERE op_id=?`).get(params3.opId);
78128
+ const opType = typeof opRow?.type === "string" ? opRow.type : "";
78129
+ if (opType !== "replace_children_with_markdown" && opType !== "replace_selection_with_markdown")
78130
+ return;
78131
+ let payload = {};
78132
+ try {
78133
+ payload = JSON.parse(String(opRow?.payload_json ?? "{}"));
78134
+ } catch {}
78135
+ const backupPolicy = typeof payload?.backup === "string" && payload.backup.trim() === "visible" ? "visible" : "auto";
78136
+ const backupKind = opType === "replace_children_with_markdown" ? "children_replace" : "selection_replace";
78137
+ const backupRemId = typeof params3.result?.backup_rem_id === "string" && params3.result.backup_rem_id.trim() ? params3.result.backup_rem_id.trim() : null;
78138
+ const cleanupState = params3.status === "success" ? backupPolicy === "visible" && backupRemId ? "retained" : backupRemId ? params3.result?.backup_hidden === true || params3.result?.backup_cleanup_state === "pending" ? "pending" : "orphan" : "cleaned" : backupRemId ? backupPolicy === "visible" ? "retained" : params3.status === "retry" ? "pending" : "orphan" : null;
78139
+ if (!cleanupState)
78140
+ return;
78141
+ upsertBackupArtifact(db, {
78142
+ sourceOpId: params3.opId,
78143
+ sourceTxn: typeof opRow?.txn_id === "string" ? opRow.txn_id : "",
78144
+ sourceOpType: opType,
78145
+ backupKind,
78146
+ cleanupPolicy: backupPolicy,
78147
+ cleanupState,
78148
+ backupRemId,
78149
+ sourceParentId: typeof params3.result?.parent_id === "string" ? params3.result.parent_id : typeof payload?.parent_id === "string" ? payload.parent_id : null,
78150
+ sourceAnchorId: opType === "replace_children_with_markdown" ? typeof payload?.parent_id === "string" ? payload.parent_id : null : Array.isArray(params3.result?.selection_rem_ids) ? String(params3.result.selection_rem_ids[0] ?? "") : Array.isArray(payload?.target?.rem_ids) ? String(payload.target.rem_ids[0] ?? "") : null,
78151
+ result: params3.result ?? {},
78152
+ now: params3.now,
78153
+ cleanedAt: cleanupState === "cleaned" ? params3.now : null
78154
+ });
78155
+ }
77953
78156
  // src/kernel/op-catalog/idFields.ts
77954
78157
  function idFieldPathsForOpType(opTypeRaw) {
77955
78158
  const opType = canonicalizeOpType(opTypeRaw);
@@ -93473,6 +93676,11 @@ function requireOkUiContext(snapshot2) {
93473
93676
  }
93474
93677
  // src/kernel/write-plan/compile.ts
93475
93678
  var ALIAS_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
93679
+ var WRITE_STRUCTURE_ASSERTIONS = new Set([
93680
+ "single-root",
93681
+ "preserve-anchor",
93682
+ "no-literal-bullet"
93683
+ ]);
93476
93684
  function getObject(value8) {
93477
93685
  return value8 && typeof value8 === "object" && !Array.isArray(value8) ? value8 : null;
93478
93686
  }
@@ -93686,6 +93894,16 @@ var ACTIONS = {
93686
93894
  }
93687
93895
  const payload = { parent_id: rem_id, markdown };
93688
93896
  Object.assign(payload, buildMarkdownPayloadFields(input));
93897
+ if (typeof input.backup === "string")
93898
+ payload.backup = input.backup;
93899
+ if (Array.isArray(input.assertions)) {
93900
+ const assertions = input.assertions;
93901
+ const valid = assertions.every((value8) => typeof value8 === "string" && WRITE_STRUCTURE_ASSERTIONS.has(value8));
93902
+ if (!valid) {
93903
+ throw new Error("rem.children.replace input.assertions must only include: single-root, preserve-anchor, no-literal-bullet");
93904
+ }
93905
+ payload.assertions = assertions;
93906
+ }
93689
93907
  return { ops: [{ type: "replace_children_with_markdown", payload }] };
93690
93908
  }
93691
93909
  },
@@ -93701,6 +93919,58 @@ var ACTIONS = {
93701
93919
  return { ops: [{ type: "replace_children_with_markdown", payload: { parent_id: rem_id, markdown: "" } }] };
93702
93920
  }
93703
93921
  },
93922
+ "rem.replace": {
93923
+ opType: "replace_children_with_markdown",
93924
+ supportsAs: false,
93925
+ aliasRefAllowlist: ["rem_ids[]"],
93926
+ compile: ({ input }) => {
93927
+ const surface = input.surface;
93928
+ const markdown = input.markdown;
93929
+ const rem_ids = Array.isArray(input.rem_ids) ? input.rem_ids.filter((value8) => typeof value8 === "string" && value8.trim().length > 0) : [];
93930
+ if (surface !== "children" && surface !== "self") {
93931
+ throw new Error("rem.replace requires input.surface to be 'children' or 'self'");
93932
+ }
93933
+ if (typeof markdown !== "string") {
93934
+ throw new Error("rem.replace requires input.markdown");
93935
+ }
93936
+ if (rem_ids.length === 0) {
93937
+ throw new Error("rem.replace requires input.rem_ids[]");
93938
+ }
93939
+ const assertions = Array.isArray(input.assertions) ? input.assertions : [];
93940
+ const validAssertions = assertions.every((value8) => typeof value8 === "string" && WRITE_STRUCTURE_ASSERTIONS.has(value8));
93941
+ if (!validAssertions) {
93942
+ throw new Error("rem.replace input.assertions must only include: single-root, preserve-anchor, no-literal-bullet");
93943
+ }
93944
+ if (surface === "self" && assertions.includes("preserve-anchor")) {
93945
+ throw new Error("rem.replace input.surface=self does not support input.assertions preserve-anchor");
93946
+ }
93947
+ if (surface === "children") {
93948
+ if (rem_ids.length !== 1) {
93949
+ throw new Error("rem.replace input.surface=children requires exactly one target");
93950
+ }
93951
+ const payload = { parent_id: rem_ids[0], markdown };
93952
+ if (assertions.length > 0)
93953
+ payload.assertions = assertions;
93954
+ return {
93955
+ ops: [{ type: "replace_children_with_markdown", payload }]
93956
+ };
93957
+ }
93958
+ return {
93959
+ ops: [
93960
+ {
93961
+ type: "replace_selection_with_markdown",
93962
+ payload: {
93963
+ markdown,
93964
+ target: { mode: "explicit", rem_ids },
93965
+ require_same_parent: true,
93966
+ require_contiguous: true,
93967
+ ...assertions.length > 0 ? { assertions } : {}
93968
+ }
93969
+ }
93970
+ ]
93971
+ };
93972
+ }
93973
+ },
93704
93974
  rem: {
93705
93975
  opType: "",
93706
93976
  supportsAs: false,
@@ -93814,6 +94084,100 @@ function compileWritePlanV1(plan, params3) {
93814
94084
  }
93815
94085
  return { alias_map: aliasMap, ops };
93816
94086
  }
94087
+ // src/kernel/write-plan/shape.ts
94088
+ var STRUCTURED_MARKDOWN_LINE_RE = /^\s{0,3}(?:#{1,6}\s+\S|[-*+]\s+\S|\d+\.\s+\S|```|~~~)/m;
94089
+ var ROOT_HEADING_RE = /^#{1,6}\s+\S/;
94090
+ var ROOT_LIST_ITEM_RE = /^(?:[-*+]|\d+\.)\s+\S/;
94091
+ function looksLikeStructuredMarkdown(input) {
94092
+ const normalized = input.replace(/\r\n?/g, `
94093
+ `).trim();
94094
+ if (!normalized)
94095
+ return false;
94096
+ return STRUCTURED_MARKDOWN_LINE_RE.test(normalized);
94097
+ }
94098
+ function trimBoundaryBlankLinesLocal(input) {
94099
+ const normalized = input.replace(/\r\n?/g, `
94100
+ `);
94101
+ const lines3 = normalized.split(`
94102
+ `);
94103
+ let start4 = 0;
94104
+ while (start4 < lines3.length && lines3[start4]?.trim().length === 0)
94105
+ start4 += 1;
94106
+ if (start4 >= lines3.length)
94107
+ return "";
94108
+ let end6 = lines3.length - 1;
94109
+ while (end6 >= start4 && lines3[end6]?.trim().length === 0)
94110
+ end6 -= 1;
94111
+ if (end6 < start4)
94112
+ return "";
94113
+ let inFence = false;
94114
+ for (let i = start4;i <= end6; i += 1) {
94115
+ if (/^\s*```/.test(lines3[i] ?? ""))
94116
+ inFence = !inFence;
94117
+ }
94118
+ const keptEnd = inFence ? lines3.length - 1 : end6;
94119
+ return lines3.slice(start4, keptEnd + 1).join(`
94120
+ `);
94121
+ }
94122
+ function countTopLevelMarkdownRoots(input) {
94123
+ const normalized = trimBoundaryBlankLinesLocal(input.replace(/\r\n?/g, `
94124
+ `));
94125
+ if (!normalized)
94126
+ return 0;
94127
+ const lines3 = normalized.split(`
94128
+ `);
94129
+ const commonIndent = lines3.filter((line4) => line4.trim().length > 0).reduce((min5, line4) => {
94130
+ const indent3 = line4.match(/^[ \t]*/)?.[0].length ?? 0;
94131
+ return min5 === null ? indent3 : Math.min(min5, indent3);
94132
+ }, null) ?? 0;
94133
+ let inFence = false;
94134
+ let count4 = 0;
94135
+ for (const rawLine of lines3) {
94136
+ const line4 = rawLine.slice(commonIndent);
94137
+ if (/^\s*(```|~~~)/.test(line4)) {
94138
+ inFence = !inFence;
94139
+ continue;
94140
+ }
94141
+ if (inFence)
94142
+ continue;
94143
+ const trimmed2 = line4.trim();
94144
+ if (!trimmed2)
94145
+ continue;
94146
+ if (/^[ \t]/.test(line4))
94147
+ continue;
94148
+ if (ROOT_HEADING_RE.test(trimmed2)) {
94149
+ count4 += 1;
94150
+ continue;
94151
+ }
94152
+ if (ROOT_LIST_ITEM_RE.test(trimmed2))
94153
+ count4 += 1;
94154
+ }
94155
+ return count4;
94156
+ }
94157
+ function decideOutlineWriteShape(params3) {
94158
+ if (params3.preserveAnchor === true) {
94159
+ return {
94160
+ shape: "expand_in_place",
94161
+ outline_suitable: true,
94162
+ top_level_roots: 0
94163
+ };
94164
+ }
94165
+ const markdown = typeof params3.markdown === "string" ? params3.markdown : "";
94166
+ const topLevelRoots = countTopLevelMarkdownRoots(markdown);
94167
+ const structured = looksLikeStructuredMarkdown(markdown);
94168
+ if (structured && topLevelRoots === 1) {
94169
+ return {
94170
+ shape: "single_root_outline",
94171
+ outline_suitable: true,
94172
+ top_level_roots: 1
94173
+ };
94174
+ }
94175
+ return {
94176
+ shape: "normal",
94177
+ outline_suitable: false,
94178
+ top_level_roots: topLevelRoots
94179
+ };
94180
+ }
93817
94181
  // src/services/Payload.ts
93818
94182
  import { promises as fs17 } from "node:fs";
93819
94183
  class Payload extends Tag2("Payload")() {
@@ -95202,13 +95566,54 @@ function trimBoundaryBlankLines(input) {
95202
95566
  return lines3.slice(start4, keptEnd + 1).join(`
95203
95567
  `);
95204
95568
  }
95205
- var STRUCTURED_MARKDOWN_LINE_RE = /^\s{0,3}(?:#{1,6}\s+\S|[-*+]\s+\S|\d+\.\s+\S|```|~~~)/m;
95206
- function looksLikeStructuredMarkdown(input) {
95569
+ var STRUCTURED_MARKDOWN_LINE_RE2 = /^\s{0,3}(?:#{1,6}\s+\S|[-*+]\s+\S|\d+\.\s+\S|```|~~~)/m;
95570
+ var ROOT_HEADING_RE2 = /^#{1,6}\s+\S/;
95571
+ var ROOT_LIST_ITEM_RE2 = /^(?:[-*+]|\d+\.)\s+\S/;
95572
+ function looksLikeStructuredMarkdown2(input) {
95207
95573
  const normalized = input.replace(/\r\n?/g, `
95208
95574
  `).trim();
95209
95575
  if (!normalized)
95210
95576
  return false;
95211
- return STRUCTURED_MARKDOWN_LINE_RE.test(normalized);
95577
+ return STRUCTURED_MARKDOWN_LINE_RE2.test(normalized);
95578
+ }
95579
+ function countTopLevelMarkdownRoots2(input) {
95580
+ const normalized = trimBoundaryBlankLines(input.replace(/\r\n?/g, `
95581
+ `));
95582
+ if (!normalized)
95583
+ return 0;
95584
+ const lines3 = normalized.split(`
95585
+ `);
95586
+ const commonIndent = lines3.filter((line4) => line4.trim().length > 0).reduce((min5, line4) => {
95587
+ const indent3 = line4.match(/^[ \t]*/)?.[0].length ?? 0;
95588
+ return min5 === null ? indent3 : Math.min(min5, indent3);
95589
+ }, null) ?? 0;
95590
+ let inFence = false;
95591
+ let count4 = 0;
95592
+ for (const rawLine of lines3) {
95593
+ const line4 = rawLine.slice(commonIndent);
95594
+ if (/^\s*(```|~~~)/.test(line4)) {
95595
+ inFence = !inFence;
95596
+ continue;
95597
+ }
95598
+ if (inFence)
95599
+ continue;
95600
+ const trimmed2 = line4.trim();
95601
+ if (!trimmed2)
95602
+ continue;
95603
+ if (/^[ \t]/.test(line4))
95604
+ continue;
95605
+ if (ROOT_HEADING_RE2.test(trimmed2)) {
95606
+ count4 += 1;
95607
+ continue;
95608
+ }
95609
+ if (ROOT_LIST_ITEM_RE2.test(trimmed2)) {
95610
+ count4 += 1;
95611
+ }
95612
+ }
95613
+ return count4;
95614
+ }
95615
+ function isSingleRootOutlineMarkdown(input) {
95616
+ return countTopLevelMarkdownRoots2(input) === 1;
95212
95617
  }
95213
95618
 
95214
95619
  // src/lib/hostApiUseCases.ts
@@ -95301,24 +95706,91 @@ function executeReadOutlineUseCase(params3) {
95301
95706
  if (!resolvedId) {
95302
95707
  return yield* fail8(new CliError({ code: "INVALID_ARGS", message: "You must provide --id or --ref", exitCode: 2 }));
95303
95708
  }
95304
- return yield* tryPromise2({
95709
+ const activeBackupRemIds = yield* sync3(() => {
95710
+ const db = openStoreDb(cfg.storeDb);
95711
+ try {
95712
+ return new Set(listBackupArtifacts(db, { includeCleaned: false, limit: 1000 }).map((item) => String(item.backup_rem_id ?? "").trim()).filter(Boolean));
95713
+ } finally {
95714
+ db.close();
95715
+ }
95716
+ }).pipe(catchAll2(() => succeed8(new Set)));
95717
+ const result = yield* tryPromise2({
95305
95718
  try: async () => await executeOutlineRemSubtree({
95306
95719
  id: resolvedId,
95307
95720
  dbPath: cfg.remnoteDb ?? workspace.dbPath,
95308
95721
  maxDepth: params3.depth,
95309
95722
  startOffset: params3.offset,
95310
95723
  maxNodes: params3.nodes,
95311
- format: params3.format === "json" ? "json" : "markdown",
95724
+ format: "json",
95312
95725
  excludeProperties: params3.excludeProperties === true,
95313
95726
  includeEmpty: params3.includeEmpty === true,
95314
95727
  expandReferences: params3.expandReferences === false ? false : undefined,
95315
95728
  maxReferenceDepth: params3.maxReferenceDepth,
95316
- detail: params3.detail === true
95729
+ detail: true
95317
95730
  }),
95318
95731
  catch: (error4) => cliErrorFromUnknown(error4, { code: "DB_UNAVAILABLE" })
95319
95732
  });
95733
+ if (activeBackupRemIds.size === 0) {
95734
+ if (params3.format === "json")
95735
+ return result;
95736
+ const tree2 = Array.isArray(result.tree) ? result.tree : [];
95737
+ return {
95738
+ ...result,
95739
+ markdown: outlineNodesToMarkdown(tree2),
95740
+ ...params3.detail === true ? {} : { tree: simplifyOutlineTree(tree2) }
95741
+ };
95742
+ }
95743
+ const tree = Array.isArray(result.tree) ? result.tree : [];
95744
+ const filteredTree = filterOutlineTreeByHiddenBackupSubtrees(tree, activeBackupRemIds, resolvedId);
95745
+ const filtered = {
95746
+ ...result,
95747
+ nodeCount: filteredTree.length,
95748
+ totalNodeCount: filteredTree.length,
95749
+ hasMore: Boolean(result.hasMore),
95750
+ nextOffset: result.nextOffset ?? null,
95751
+ markdown: outlineNodesToMarkdown(filteredTree),
95752
+ tree: params3.detail === true ? filteredTree : simplifyOutlineTree(filteredTree)
95753
+ };
95754
+ if (params3.format === "json")
95755
+ return filtered;
95756
+ return filtered;
95320
95757
  });
95321
95758
  }
95759
+ function filterOutlineTreeByHiddenBackupSubtrees(tree, hiddenIds, rootId) {
95760
+ const out = [];
95761
+ let skipDepth = null;
95762
+ for (const node of tree) {
95763
+ const depth = Number(node?.depth ?? 0);
95764
+ if (skipDepth !== null) {
95765
+ if (depth > skipDepth)
95766
+ continue;
95767
+ skipDepth = null;
95768
+ }
95769
+ const id2 = typeof node?.id === "string" ? node.id : "";
95770
+ if (id2 && id2 !== rootId && hiddenIds.has(id2)) {
95771
+ skipDepth = depth;
95772
+ continue;
95773
+ }
95774
+ out.push(node);
95775
+ }
95776
+ return out;
95777
+ }
95778
+ function outlineNodesToMarkdown(nodes) {
95779
+ return nodes.map((node) => {
95780
+ const depth = Number(node?.depth ?? 0);
95781
+ const text14 = typeof node?.text === "string" && node.text.trim() ? node.text : "(empty)";
95782
+ return `${" ".repeat(Math.max(0, depth))}- ${text14}`;
95783
+ }).join(`
95784
+ `);
95785
+ }
95786
+ function simplifyOutlineTree(nodes) {
95787
+ return nodes.map((node) => ({
95788
+ id: node.id,
95789
+ depth: node.depth,
95790
+ text: node.text,
95791
+ references: Array.isArray(node.references) ? node.references : []
95792
+ }));
95793
+ }
95322
95794
  function executeDailyRemIdUseCase(params3) {
95323
95795
  return gen2(function* () {
95324
95796
  if (params3.date && params3.offsetDays !== undefined) {
@@ -96013,7 +96485,7 @@ var dailyWriteCommand = exports_Command.make("write", {
96013
96485
  const markdownRaw = markdownInput !== undefined ? yield* readMarkdownTextFromInputSpec(markdownInput) : undefined;
96014
96486
  const markdownValue = markdownRaw !== undefined ? trimBoundaryBlankLines(markdownRaw) : undefined;
96015
96487
  const textValue = text15 !== undefined ? trimBoundaryBlankLines(text15) : undefined;
96016
- if (textValue && !forceText2 && looksLikeStructuredMarkdown(textValue)) {
96488
+ if (textValue && !forceText2 && looksLikeStructuredMarkdown2(textValue)) {
96017
96489
  return yield* fail8(new CliError({
96018
96490
  code: "INVALID_ARGS",
96019
96491
  message: "Input passed to --text looks like structured Markdown. Use --markdown instead.",
@@ -96036,7 +96508,8 @@ var dailyWriteCommand = exports_Command.make("write", {
96036
96508
  const lines3 = content.split(`
96037
96509
  `).length;
96038
96510
  const chars = content.length;
96039
- const shouldBundle = bulkMode === "always" || bulkMode === "auto" && (hasBundleTitle || lines3 >= BULK_THRESHOLD_LINES || chars >= BULK_THRESHOLD_CHARS);
96511
+ const writeShape = decideOutlineWriteShape({ markdown: markdownValue });
96512
+ const shouldBundle = bulkMode === "always" || bulkMode === "auto" && (hasBundleTitle || (lines3 >= BULK_THRESHOLD_LINES || chars >= BULK_THRESHOLD_CHARS) && !(markdownValue !== undefined && !hasBundleTitle && writeShape.shape === "single_root_outline" && isSingleRootOutlineMarkdown(markdownValue)));
96040
96513
  const metaValue = meta ? yield* payloadSvc.readJson(meta) : undefined;
96041
96514
  const body = {
96042
96515
  version: 1,
@@ -96321,78 +96794,272 @@ var readDbCommand = exports_Command.make("db", {}).pipe(exports_Command.withSubc
96321
96794
  // src/commands/db/index.ts
96322
96795
  var dbCommand = readDbCommand;
96323
96796
 
96324
- // src/commands/ops/list.ts
96325
- var opsListCommand = exports_Command.make("list", {}, () => gen2(function* () {
96326
- const types = Object.keys(TYPES).sort();
96327
- yield* writeSuccess({
96328
- data: { types },
96329
- ids: types,
96330
- md: types.map((t) => `- ${t}`).join(`
96331
- `)
96332
- });
96333
- }).pipe(catchAll2(writeFailure)));
96334
-
96335
- // src/commands/ops/schema.ts
96336
- function typeHint(field) {
96337
- const f = field.toLowerCase();
96338
- if (f.includes("markdown"))
96339
- return "string(markdown)";
96340
- if (f.endsWith("id") || f.endsWith("ids") || f.includes("parentid"))
96341
- return "string(remId)";
96342
- if (f.includes("tags") || f.endsWith("ids"))
96343
- return "string[]";
96344
- if (f.startsWith("is") || f.startsWith("include") || f.startsWith("exclude") || f.includes("create"))
96345
- return "boolean";
96346
- if (f.includes("count") || f.includes("size") || f.includes("position") || f.includes("max") || f.includes("ms"))
96347
- return "number";
96348
- return "unknown";
96349
- }
96350
- function exampleValue(field) {
96351
- const f = field.toLowerCase();
96352
- if (f.includes("markdown"))
96353
- return "# Markdown...";
96354
- if (f.endsWith("ids") || f === "tags")
96355
- return [];
96356
- if (f.endsWith("id") || f.includes("parentid"))
96357
- return "<remId>";
96358
- if (f.startsWith("is") || f.startsWith("include") || f.startsWith("exclude") || f.includes("create"))
96359
- return true;
96360
- if (f.includes("count") || f.includes("size") || f.includes("position") || f.includes("max") || f.includes("ms"))
96361
- return 0;
96362
- if (f.includes("url"))
96363
- return "https://example.com";
96364
- return "<value>";
96797
+ // src/commands/backup/cleanup.ts
96798
+ function optionToUndefined14(opt) {
96799
+ return isSome2(opt) ? opt.value : undefined;
96365
96800
  }
96366
- var opsSchemaCommand = exports_Command.make("schema", { type: text9("type") }, ({ type: type2 }) => gen2(function* () {
96367
- const spec = TYPES[type2];
96368
- if (!spec) {
96801
+ var backupCleanupCommand = exports_Command.make("cleanup", {
96802
+ apply: boolean8("apply"),
96803
+ backupRemId: text9("backup-rem-id").pipe(optional5, map34(optionToUndefined14)),
96804
+ maxDeleteSubtreeNodes: integer7("max-delete-subtree-nodes").pipe(optional5, map34(optionToUndefined14)),
96805
+ state: choice5("state", ["pending", "orphan", "retained", "cleaned"]).pipe(repeated5),
96806
+ kind: choice5("kind", ["children_replace", "selection_replace"]).pipe(repeated5),
96807
+ olderThanHours: integer7("older-than-hours").pipe(optional5, map34(optionToUndefined14)),
96808
+ limit: integer7("limit").pipe(withDefault5(100)),
96809
+ wait: boolean8("wait"),
96810
+ timeoutMs: integer7("timeout-ms").pipe(optional5, map34(optionToUndefined14)),
96811
+ pollMs: integer7("poll-ms").pipe(optional5, map34(optionToUndefined14)),
96812
+ notify: boolean8("no-notify").pipe(map34((value8) => !value8)),
96813
+ ensureDaemon: boolean8("no-ensure-daemon").pipe(map34((value8) => !value8))
96814
+ }, ({
96815
+ apply,
96816
+ backupRemId,
96817
+ maxDeleteSubtreeNodes,
96818
+ state,
96819
+ kind,
96820
+ olderThanHours,
96821
+ limit: limit2,
96822
+ wait: wait2,
96823
+ timeoutMs: timeoutMs2,
96824
+ pollMs: pollMs2,
96825
+ notify: notify2,
96826
+ ensureDaemon: ensureDaemon3
96827
+ }) => gen2(function* () {
96828
+ if (maxDeleteSubtreeNodes !== undefined && maxDeleteSubtreeNodes <= 0) {
96369
96829
  return yield* fail8(new CliError({
96370
96830
  code: "INVALID_ARGS",
96371
- message: `Unknown op type: ${type2}`,
96372
- exitCode: 2,
96373
- hint: ["agent-remnote ops list"]
96831
+ message: "--max-delete-subtree-nodes must be >= 1",
96832
+ exitCode: 2
96374
96833
  }));
96375
96834
  }
96376
- const required2 = Array.isArray(spec.required) ? spec.required : [];
96377
- const optional6 = Array.isArray(spec.optional) ? spec.optional : [];
96378
- const examplePayload = {};
96379
- for (const f of required2)
96380
- examplePayload[f] = exampleValue(f);
96381
- const fields = [
96382
- ...required2.map((name) => ({ name, required: true, type: typeHint(name) })),
96383
- ...optional6.map((name) => ({ name, required: false, type: typeHint(name) }))
96384
- ];
96385
- const data = {
96386
- type: type2,
96387
- description: spec.description ?? "",
96388
- fields,
96389
- example: { type: type2, payload: examplePayload }
96390
- };
96391
- const md = [
96392
- `# ${type2}`,
96393
- spec.description ? `- description: ${spec.description}` : "",
96394
- required2.length > 0 ? `
96395
- ## required` : "",
96835
+ if (olderThanHours !== undefined && olderThanHours < 0) {
96836
+ return yield* fail8(new CliError({
96837
+ code: "INVALID_ARGS",
96838
+ message: "--older-than-hours must be a non-negative integer",
96839
+ exitCode: 2
96840
+ }));
96841
+ }
96842
+ if (limit2 < 1) {
96843
+ return yield* fail8(new CliError({
96844
+ code: "INVALID_ARGS",
96845
+ message: "--limit must be >= 1",
96846
+ exitCode: 2
96847
+ }));
96848
+ }
96849
+ if (!wait2 && (timeoutMs2 !== undefined || pollMs2 !== undefined)) {
96850
+ return yield* fail8(new CliError({
96851
+ code: "INVALID_ARGS",
96852
+ message: "Use --wait to enable --timeout-ms/--poll-ms",
96853
+ exitCode: 2
96854
+ }));
96855
+ }
96856
+ if (!apply && wait2) {
96857
+ return yield* fail8(new CliError({
96858
+ code: "INVALID_ARGS",
96859
+ message: "--wait requires --apply",
96860
+ exitCode: 2
96861
+ }));
96862
+ }
96863
+ yield* failInRemoteMode({
96864
+ command: "backup cleanup",
96865
+ reason: "backup governance currently reads and updates the local store registry directly"
96866
+ });
96867
+ const cfg = yield* AppConfig;
96868
+ const payloadSvc = yield* Payload;
96869
+ const db = openStoreDb(cfg.storeDb);
96870
+ try {
96871
+ const states = state.length > 0 ? state : backupRemId ? [] : ["orphan"];
96872
+ const items = listBackupArtifacts(db, {
96873
+ states,
96874
+ kinds: kind,
96875
+ backupRemId,
96876
+ olderThanHours,
96877
+ limit: limit2
96878
+ }).filter((item) => typeof item.backup_rem_id === "string" && item.backup_rem_id.length > 0);
96879
+ if (backupRemId && items.length === 0) {
96880
+ return yield* fail8(new CliError({
96881
+ code: "INVALID_ARGS",
96882
+ message: `No backup artifact found for --backup-rem-id ${backupRemId}`,
96883
+ exitCode: 2
96884
+ }));
96885
+ }
96886
+ if (!apply) {
96887
+ yield* writeSuccess({
96888
+ data: { dry_run: true, items, count: items.length },
96889
+ ids: items.map((item) => item.backup_rem_id).filter(Boolean),
96890
+ md: [`- dry_run: true`, `- count: ${items.length}`].join(`
96891
+ `)
96892
+ });
96893
+ return;
96894
+ }
96895
+ const ops = items.map((item) => normalizeOp({
96896
+ type: "delete_backup_artifact",
96897
+ payload: {
96898
+ rem_id: item.backup_rem_id,
96899
+ ...maxDeleteSubtreeNodes !== undefined ? { max_delete_subtree_nodes: maxDeleteSubtreeNodes } : {}
96900
+ }
96901
+ }, payloadSvc.normalizeKeys));
96902
+ const data = ops.length > 0 ? yield* enqueueOps({
96903
+ ops,
96904
+ notify: notify2,
96905
+ ensureDaemon: ensureDaemon3
96906
+ }) : { txn_id: "", op_ids: [], notified: false };
96907
+ updateBackupArtifactsCleanupState(db, {
96908
+ sourceOpIds: items.map((item) => item.source_op_id),
96909
+ cleanupState: wait2 && ops.length === 0 ? "cleaned" : "pending"
96910
+ });
96911
+ const waited = wait2 && data.txn_id ? yield* waitForTxn({ txnId: data.txn_id, timeoutMs: timeoutMs2, pollMs: pollMs2 }) : null;
96912
+ if (waited?.status === "succeeded") {
96913
+ updateBackupArtifactsCleanupState(db, {
96914
+ sourceOpIds: items.map((item) => item.source_op_id),
96915
+ cleanupState: "cleaned"
96916
+ });
96917
+ }
96918
+ yield* writeSuccess({
96919
+ data: {
96920
+ dry_run: false,
96921
+ items,
96922
+ count: items.length,
96923
+ ...data.txn_id ? data : {},
96924
+ ...waited ? waited : {}
96925
+ },
96926
+ ids: [data.txn_id, ...data.op_ids].filter(Boolean),
96927
+ md: [
96928
+ `- dry_run: false`,
96929
+ `- count: ${items.length}`,
96930
+ ...data.txn_id ? [`- txn_id: ${data.txn_id}`] : [],
96931
+ ...waited ? [`- status: ${waited.status}`, `- elapsed_ms: ${waited.elapsed_ms ?? ""}`] : []
96932
+ ].join(`
96933
+ `)
96934
+ });
96935
+ } finally {
96936
+ db.close();
96937
+ }
96938
+ }).pipe(catchAll2(writeFailure))).pipe(exports_Command.withDescription("Dry-run by default. Use --apply to enqueue delete_backup_artifact cleanup for backup artifacts."));
96939
+
96940
+ // src/commands/backup/list.ts
96941
+ function optionToUndefined15(opt) {
96942
+ return isSome2(opt) ? opt.value : undefined;
96943
+ }
96944
+ var backupListCommand = exports_Command.make("list", {
96945
+ state: choice5("state", ["pending", "orphan", "retained", "cleaned"]).pipe(repeated5),
96946
+ kind: choice5("kind", ["children_replace", "selection_replace"]).pipe(repeated5),
96947
+ olderThanHours: integer7("older-than-hours").pipe(optional5, map34(optionToUndefined15)),
96948
+ limit: integer7("limit").pipe(withDefault5(100))
96949
+ }, ({ state, kind, olderThanHours, limit: limit2 }) => gen2(function* () {
96950
+ if (olderThanHours !== undefined && olderThanHours < 0) {
96951
+ return yield* fail8(new CliError({
96952
+ code: "INVALID_ARGS",
96953
+ message: "--older-than-hours must be a non-negative integer",
96954
+ exitCode: 2
96955
+ }));
96956
+ }
96957
+ if (limit2 < 1) {
96958
+ return yield* fail8(new CliError({
96959
+ code: "INVALID_ARGS",
96960
+ message: "--limit must be >= 1",
96961
+ exitCode: 2
96962
+ }));
96963
+ }
96964
+ yield* failInRemoteMode({
96965
+ command: "backup list",
96966
+ reason: "backup governance currently reads the local store registry directly"
96967
+ });
96968
+ const cfg = yield* AppConfig;
96969
+ const db = openStoreDb(cfg.storeDb);
96970
+ try {
96971
+ const items = listBackupArtifacts(db, {
96972
+ states: state,
96973
+ kinds: kind,
96974
+ olderThanHours,
96975
+ limit: limit2
96976
+ });
96977
+ yield* writeSuccess({
96978
+ data: { items, count: items.length },
96979
+ ids: items.map((item) => item.backup_rem_id).filter((item) => typeof item === "string" && item.length > 0),
96980
+ md: [`- count: ${items.length}`, ...items.map((item) => `- ${item.source_op_id}: ${item.cleanup_state}`)].join(`
96981
+ `)
96982
+ });
96983
+ } finally {
96984
+ db.close();
96985
+ }
96986
+ }).pipe(catchAll2(writeFailure))).pipe(exports_Command.withDescription("List backup artifacts from the local store registry."));
96987
+
96988
+ // src/commands/backup/index.ts
96989
+ var backupCommand = exports_Command.make("backup", {}).pipe(exports_Command.withSubcommands([backupListCommand, backupCleanupCommand]), exports_Command.withDescription("Backup artifact governance commands."));
96990
+
96991
+ // src/commands/ops/list.ts
96992
+ var opsListCommand = exports_Command.make("list", {}, () => gen2(function* () {
96993
+ const types = Object.keys(TYPES).sort();
96994
+ yield* writeSuccess({
96995
+ data: { types },
96996
+ ids: types,
96997
+ md: types.map((t) => `- ${t}`).join(`
96998
+ `)
96999
+ });
97000
+ }).pipe(catchAll2(writeFailure)));
97001
+
97002
+ // src/commands/ops/schema.ts
97003
+ function typeHint(field) {
97004
+ const f = field.toLowerCase();
97005
+ if (f.includes("markdown"))
97006
+ return "string(markdown)";
97007
+ if (f.endsWith("id") || f.endsWith("ids") || f.includes("parentid"))
97008
+ return "string(remId)";
97009
+ if (f.includes("tags") || f.endsWith("ids"))
97010
+ return "string[]";
97011
+ if (f.startsWith("is") || f.startsWith("include") || f.startsWith("exclude") || f.includes("create"))
97012
+ return "boolean";
97013
+ if (f.includes("count") || f.includes("size") || f.includes("position") || f.includes("max") || f.includes("ms"))
97014
+ return "number";
97015
+ return "unknown";
97016
+ }
97017
+ function exampleValue(field) {
97018
+ const f = field.toLowerCase();
97019
+ if (f.includes("markdown"))
97020
+ return "# Markdown...";
97021
+ if (f.endsWith("ids") || f === "tags")
97022
+ return [];
97023
+ if (f.endsWith("id") || f.includes("parentid"))
97024
+ return "<remId>";
97025
+ if (f.startsWith("is") || f.startsWith("include") || f.startsWith("exclude") || f.includes("create"))
97026
+ return true;
97027
+ if (f.includes("count") || f.includes("size") || f.includes("position") || f.includes("max") || f.includes("ms"))
97028
+ return 0;
97029
+ if (f.includes("url"))
97030
+ return "https://example.com";
97031
+ return "<value>";
97032
+ }
97033
+ var opsSchemaCommand = exports_Command.make("schema", { type: text9("type") }, ({ type: type2 }) => gen2(function* () {
97034
+ const spec = TYPES[type2];
97035
+ if (!spec) {
97036
+ return yield* fail8(new CliError({
97037
+ code: "INVALID_ARGS",
97038
+ message: `Unknown op type: ${type2}`,
97039
+ exitCode: 2,
97040
+ hint: ["agent-remnote ops list"]
97041
+ }));
97042
+ }
97043
+ const required2 = Array.isArray(spec.required) ? spec.required : [];
97044
+ const optional6 = Array.isArray(spec.optional) ? spec.optional : [];
97045
+ const examplePayload = {};
97046
+ for (const f of required2)
97047
+ examplePayload[f] = exampleValue(f);
97048
+ const fields = [
97049
+ ...required2.map((name) => ({ name, required: true, type: typeHint(name) })),
97050
+ ...optional6.map((name) => ({ name, required: false, type: typeHint(name) }))
97051
+ ];
97052
+ const data = {
97053
+ type: type2,
97054
+ description: spec.description ?? "",
97055
+ fields,
97056
+ example: { type: type2, payload: examplePayload }
97057
+ };
97058
+ const md = [
97059
+ `# ${type2}`,
97060
+ spec.description ? `- description: ${spec.description}` : "",
97061
+ required2.length > 0 ? `
97062
+ ## required` : "",
96396
97063
  ...required2.map((f) => `- ${f} (${typeHint(f)})`),
96397
97064
  optional6.length > 0 ? `
96398
97065
  ## optional` : "",
@@ -96411,22 +97078,22 @@ var opsSchemaCommand = exports_Command.make("schema", { type: text9("type") }, (
96411
97078
  var opsCommand = exports_Command.make("ops", {}).pipe(exports_Command.withSubcommands([opsListCommand, opsSchemaCommand]));
96412
97079
 
96413
97080
  // src/commands/apply.ts
96414
- function optionToUndefined14(opt) {
97081
+ function optionToUndefined16(opt) {
96415
97082
  return isSome2(opt) ? opt.value : undefined;
96416
97083
  }
96417
97084
  function readOptionalText2(name) {
96418
- return text9(name).pipe(optional5, map34(optionToUndefined14));
97085
+ return text9(name).pipe(optional5, map34(optionToUndefined16));
96419
97086
  }
96420
97087
  var payloadSpec = text9("payload");
96421
97088
  var metaSpec2 = readOptionalText2("meta");
96422
97089
  var clientId2 = readOptionalText2("client-id");
96423
97090
  var idempotencyKey2 = readOptionalText2("idempotency-key");
96424
- var priority2 = integer7("priority").pipe(optional5, map34(optionToUndefined14));
97091
+ var priority2 = integer7("priority").pipe(optional5, map34(optionToUndefined16));
96425
97092
  var notify2 = boolean8("no-notify").pipe(map34((v) => !v));
96426
97093
  var ensureDaemon3 = boolean8("no-ensure-daemon").pipe(map34((v) => !v));
96427
97094
  var wait2 = boolean8("wait");
96428
- var timeoutMs2 = integer7("timeout-ms").pipe(optional5, map34(optionToUndefined14));
96429
- var pollMs2 = integer7("poll-ms").pipe(optional5, map34(optionToUndefined14));
97095
+ var timeoutMs2 = integer7("timeout-ms").pipe(optional5, map34(optionToUndefined16));
97096
+ var pollMs2 = integer7("poll-ms").pipe(optional5, map34(optionToUndefined16));
96430
97097
  var applyCommand = exports_Command.make("apply", {
96431
97098
  payload: payloadSpec,
96432
97099
  notify: notify2,
@@ -96861,14 +97528,14 @@ function ensureApiDaemon(params3) {
96861
97528
  }
96862
97529
 
96863
97530
  // src/commands/api/ensure.ts
96864
- function optionToUndefined15(opt) {
97531
+ function optionToUndefined17(opt) {
96865
97532
  return isSome2(opt) ? opt.value : undefined;
96866
97533
  }
96867
- var host = text9("host").pipe(optional5, map34(optionToUndefined15));
96868
- var port3 = integer7("port").pipe(optional5, map34(optionToUndefined15));
96869
- var pidFile8 = text9("pid-file").pipe(optional5, map34(optionToUndefined15));
96870
- var logFile5 = text9("log-file").pipe(optional5, map34(optionToUndefined15));
96871
- var stateFile3 = text9("state-file").pipe(optional5, map34(optionToUndefined15));
97534
+ var host = text9("host").pipe(optional5, map34(optionToUndefined17));
97535
+ var port3 = integer7("port").pipe(optional5, map34(optionToUndefined17));
97536
+ var pidFile8 = text9("pid-file").pipe(optional5, map34(optionToUndefined17));
97537
+ var logFile5 = text9("log-file").pipe(optional5, map34(optionToUndefined17));
97538
+ var stateFile3 = text9("state-file").pipe(optional5, map34(optionToUndefined17));
96872
97539
  var apiEnsureCommand = exports_Command.make("ensure", {
96873
97540
  host,
96874
97541
  port: port3,
@@ -96891,11 +97558,11 @@ var apiEnsureCommand = exports_Command.make("ensure", {
96891
97558
  }).pipe(catchAll2(writeFailure)));
96892
97559
 
96893
97560
  // src/commands/api/logs.ts
96894
- function optionToUndefined16(opt) {
97561
+ function optionToUndefined18(opt) {
96895
97562
  return isSome2(opt) ? opt.value : undefined;
96896
97563
  }
96897
- var pidFile9 = text9("pid-file").pipe(optional5, map34(optionToUndefined16));
96898
- var file7 = text9("file").pipe(optional5, map34(optionToUndefined16));
97564
+ var pidFile9 = text9("pid-file").pipe(optional5, map34(optionToUndefined18));
97565
+ var file7 = text9("file").pipe(optional5, map34(optionToUndefined18));
96899
97566
  var apiLogsCommand = exports_Command.make("logs", { pidFile: pidFile9, file: file7, lines: integer7("lines").pipe(withDefault5(200)), follow: boolean8("follow") }, ({ pidFile: pidFile10, file: file8, lines: lines3, follow }) => gen2(function* () {
96900
97567
  const cfg = yield* AppConfig;
96901
97568
  const apiFiles = yield* ApiDaemonFiles;
@@ -96948,14 +97615,14 @@ var apiLogsCommand = exports_Command.make("logs", { pidFile: pidFile9, file: fil
96948
97615
  }).pipe(catchAll2(writeFailure)));
96949
97616
 
96950
97617
  // src/commands/api/restart.ts
96951
- function optionToUndefined17(opt) {
97618
+ function optionToUndefined19(opt) {
96952
97619
  return isSome2(opt) ? opt.value : undefined;
96953
97620
  }
96954
- var host2 = text9("host").pipe(optional5, map34(optionToUndefined17));
96955
- var port4 = integer7("port").pipe(optional5, map34(optionToUndefined17));
96956
- var pidFile10 = text9("pid-file").pipe(optional5, map34(optionToUndefined17));
96957
- var logFile6 = text9("log-file").pipe(optional5, map34(optionToUndefined17));
96958
- var stateFile4 = text9("state-file").pipe(optional5, map34(optionToUndefined17));
97621
+ var host2 = text9("host").pipe(optional5, map34(optionToUndefined19));
97622
+ var port4 = integer7("port").pipe(optional5, map34(optionToUndefined19));
97623
+ var pidFile10 = text9("pid-file").pipe(optional5, map34(optionToUndefined19));
97624
+ var logFile6 = text9("log-file").pipe(optional5, map34(optionToUndefined19));
97625
+ var stateFile4 = text9("state-file").pipe(optional5, map34(optionToUndefined19));
96959
97626
  var apiRestartCommand = exports_Command.make("restart", {
96960
97627
  force: boolean8("force"),
96961
97628
  host: host2,
@@ -97446,23 +98113,23 @@ function runHttpApiRuntime(params3) {
97446
98113
  }
97447
98114
 
97448
98115
  // src/commands/api/serve.ts
97449
- function optionToUndefined18(opt) {
98116
+ function optionToUndefined20(opt) {
97450
98117
  return isSome2(opt) ? opt.value : undefined;
97451
98118
  }
97452
- var host3 = text9("host").pipe(optional5, map34(optionToUndefined18));
97453
- var port5 = integer7("port").pipe(optional5, map34(optionToUndefined18));
97454
- var stateFile5 = text9("state-file").pipe(optional5, map34(optionToUndefined18));
98119
+ var host3 = text9("host").pipe(optional5, map34(optionToUndefined20));
98120
+ var port5 = integer7("port").pipe(optional5, map34(optionToUndefined20));
98121
+ var stateFile5 = text9("state-file").pipe(optional5, map34(optionToUndefined20));
97455
98122
  var apiServeCommand = exports_Command.make("serve", { host: host3, port: port5, stateFile: stateFile5 }, ({ host: host4, port: port6, stateFile: stateFile6 }) => runHttpApiRuntime({ host: host4, port: port6, stateFile: stateFile6 }).pipe(catchAll2(writeFailure)));
97456
98123
 
97457
98124
  // src/commands/api/start.ts
97458
- function optionToUndefined19(opt) {
98125
+ function optionToUndefined21(opt) {
97459
98126
  return isSome2(opt) ? opt.value : undefined;
97460
98127
  }
97461
- var host4 = text9("host").pipe(optional5, map34(optionToUndefined19));
97462
- var port6 = integer7("port").pipe(optional5, map34(optionToUndefined19));
97463
- var pidFile11 = text9("pid-file").pipe(optional5, map34(optionToUndefined19));
97464
- var logFile7 = text9("log-file").pipe(optional5, map34(optionToUndefined19));
97465
- var stateFile6 = text9("state-file").pipe(optional5, map34(optionToUndefined19));
98128
+ var host4 = text9("host").pipe(optional5, map34(optionToUndefined21));
98129
+ var port6 = integer7("port").pipe(optional5, map34(optionToUndefined21));
98130
+ var pidFile11 = text9("pid-file").pipe(optional5, map34(optionToUndefined21));
98131
+ var logFile7 = text9("log-file").pipe(optional5, map34(optionToUndefined21));
98132
+ var stateFile6 = text9("state-file").pipe(optional5, map34(optionToUndefined21));
97466
98133
  var apiStartCommand = exports_Command.make("start", {
97467
98134
  host: host4,
97468
98135
  port: port6,
@@ -97485,11 +98152,11 @@ var apiStartCommand = exports_Command.make("start", {
97485
98152
  }).pipe(catchAll2(writeFailure)));
97486
98153
 
97487
98154
  // src/commands/api/status.ts
97488
- function optionToUndefined20(opt) {
98155
+ function optionToUndefined22(opt) {
97489
98156
  return isSome2(opt) ? opt.value : undefined;
97490
98157
  }
97491
- var pidFile12 = text9("pid-file").pipe(optional5, map34(optionToUndefined20));
97492
- var stateFile7 = text9("state-file").pipe(optional5, map34(optionToUndefined20));
98158
+ var pidFile12 = text9("pid-file").pipe(optional5, map34(optionToUndefined22));
98159
+ var stateFile7 = text9("state-file").pipe(optional5, map34(optionToUndefined22));
97493
98160
  var apiStatusCommand = exports_Command.make("status", { pidFile: pidFile12, stateFile: stateFile7 }, ({ pidFile: pidFile13, stateFile: stateFile8 }) => gen2(function* () {
97494
98161
  const cfg = yield* AppConfig;
97495
98162
  const apiFiles = yield* ApiDaemonFiles;
@@ -97548,11 +98215,11 @@ var apiStatusCommand = exports_Command.make("status", { pidFile: pidFile12, stat
97548
98215
  }).pipe(catchAll2(writeFailure)));
97549
98216
 
97550
98217
  // src/commands/api/stop.ts
97551
- function optionToUndefined21(opt) {
98218
+ function optionToUndefined23(opt) {
97552
98219
  return isSome2(opt) ? opt.value : undefined;
97553
98220
  }
97554
- var pidFile13 = text9("pid-file").pipe(optional5, map34(optionToUndefined21));
97555
- var stateFile8 = text9("state-file").pipe(optional5, map34(optionToUndefined21));
98221
+ var pidFile13 = text9("pid-file").pipe(optional5, map34(optionToUndefined23));
98222
+ var stateFile8 = text9("state-file").pipe(optional5, map34(optionToUndefined23));
97556
98223
  var apiStopCommand = exports_Command.make("stop", { force: boolean8("force"), pidFile: pidFile13, stateFile: stateFile8 }, ({ force, pidFile: pidFile14, stateFile: stateFile9 }) => gen2(function* () {
97557
98224
  const apiFiles = yield* ApiDaemonFiles;
97558
98225
  const proc = yield* Process;
@@ -97628,11 +98295,11 @@ var apiCommand = exports_Command.make("api", {}).pipe(exports_Command.withSubcom
97628
98295
  ]));
97629
98296
 
97630
98297
  // src/commands/read/selection/current.ts
97631
- function optionToUndefined22(opt) {
98298
+ function optionToUndefined24(opt) {
97632
98299
  return isSome2(opt) ? opt.value : undefined;
97633
98300
  }
97634
- var stateFile9 = text9("state-file").pipe(optional5, map34(optionToUndefined22));
97635
- var staleMs2 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined22));
98301
+ var stateFile9 = text9("state-file").pipe(optional5, map34(optionToUndefined24));
98302
+ var staleMs2 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined24));
97636
98303
  function toCompact(data) {
97637
98304
  return {
97638
98305
  selection_kind: data?.selection_kind ?? "",
@@ -97678,11 +98345,11 @@ var readSelectionCurrentCommand = exports_Command.make("current", { stateFile: s
97678
98345
  }).pipe(catchAll2(writeFailure)));
97679
98346
 
97680
98347
  // src/commands/read/selection/outline.ts
97681
- function optionToUndefined23(opt) {
98348
+ function optionToUndefined25(opt) {
97682
98349
  return isSome2(opt) ? opt.value : undefined;
97683
98350
  }
97684
- var stateFile10 = text9("state-file").pipe(optional5, map34(optionToUndefined23));
97685
- var staleMs3 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined23));
98351
+ var stateFile10 = text9("state-file").pipe(optional5, map34(optionToUndefined25));
98352
+ var staleMs3 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined25));
97686
98353
  var maxDepth = integer7("max-depth").pipe(withDefault5(10));
97687
98354
  var maxNodes = integer7("max-nodes").pipe(withDefault5(1000));
97688
98355
  var readSelectionOutlineCommand = exports_Command.make("outline", {
@@ -97693,7 +98360,7 @@ var readSelectionOutlineCommand = exports_Command.make("outline", {
97693
98360
  excludeProperties: boolean8("exclude-properties"),
97694
98361
  includeEmpty: boolean8("include-empty"),
97695
98362
  expandReferences: boolean8("expand-references"),
97696
- maxReferenceDepth: integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined23)),
98363
+ maxReferenceDepth: integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined25)),
97697
98364
  detail: boolean8("detail")
97698
98365
  }, ({
97699
98366
  stateFile: stateFile11,
@@ -97836,11 +98503,11 @@ var readSelectionOutlineCommand = exports_Command.make("outline", {
97836
98503
  }).pipe(catchAll2(writeFailure)));
97837
98504
 
97838
98505
  // src/commands/read/selection/roots.ts
97839
- function optionToUndefined24(opt) {
98506
+ function optionToUndefined26(opt) {
97840
98507
  return isSome2(opt) ? opt.value : undefined;
97841
98508
  }
97842
- var stateFile11 = text9("state-file").pipe(optional5, map34(optionToUndefined24));
97843
- var staleMs4 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined24));
98509
+ var stateFile11 = text9("state-file").pipe(optional5, map34(optionToUndefined26));
98510
+ var staleMs4 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined26));
97844
98511
  var readSelectionRootsCommand = exports_Command.make("roots", { stateFile: stateFile11, staleMs: staleMs4 }, ({ stateFile: stateFile12, staleMs: staleMs5 }) => gen2(function* () {
97845
98512
  const cfg = yield* AppConfig;
97846
98513
  const hostApi = yield* HostApiClient;
@@ -97877,11 +98544,11 @@ var readSelectionRootsCommand = exports_Command.make("roots", { stateFile: state
97877
98544
  }).pipe(catchAll2(writeFailure)));
97878
98545
 
97879
98546
  // src/commands/read/selection/snapshot.ts
97880
- function optionToUndefined25(opt) {
98547
+ function optionToUndefined27(opt) {
97881
98548
  return isSome2(opt) ? opt.value : undefined;
97882
98549
  }
97883
- var stateFile12 = text9("state-file").pipe(optional5, map34(optionToUndefined25));
97884
- var staleMs5 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined25));
98550
+ var stateFile12 = text9("state-file").pipe(optional5, map34(optionToUndefined27));
98551
+ var staleMs5 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined27));
97885
98552
  var readSelectionSnapshotCommand = exports_Command.make("snapshot", { stateFile: stateFile12, staleMs: staleMs5 }, ({ stateFile: stateFile13, staleMs: staleMs6 }) => gen2(function* () {
97886
98553
  const cfg = yield* AppConfig;
97887
98554
  const hostApi = yield* HostApiClient;
@@ -97928,11 +98595,11 @@ var readSelectionSnapshotCommand = exports_Command.make("snapshot", { stateFile:
97928
98595
  var readSelectionCommand = exports_Command.make("selection", {}).pipe(exports_Command.withSubcommands([readSelectionSnapshotCommand, readSelectionRootsCommand, readSelectionCurrentCommand, readSelectionOutlineCommand]));
97929
98596
 
97930
98597
  // src/commands/read/uiContext/describe.ts
97931
- function optionToUndefined26(opt) {
98598
+ function optionToUndefined28(opt) {
97932
98599
  return isSome2(opt) ? opt.value : undefined;
97933
98600
  }
97934
- var stateFile13 = text9("state-file").pipe(optional5, map34(optionToUndefined26));
97935
- var staleMs6 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined26));
98601
+ var stateFile13 = text9("state-file").pipe(optional5, map34(optionToUndefined28));
98602
+ var staleMs6 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined28));
97936
98603
  var selectionLimit = integer7("selection-limit").pipe(withDefault5(5));
97937
98604
  function normalizeText4(value8) {
97938
98605
  return typeof value8 === "string" ? value8.trim() : "";
@@ -98191,11 +98858,11 @@ var readUiContextDescribeCommand = exports_Command.make("describe", { stateFile:
98191
98858
  }).pipe(catchAll2(writeFailure)));
98192
98859
 
98193
98860
  // src/commands/read/uiContext/focused-rem.ts
98194
- function optionToUndefined27(opt) {
98861
+ function optionToUndefined29(opt) {
98195
98862
  return isSome2(opt) ? opt.value : undefined;
98196
98863
  }
98197
- var stateFile14 = text9("state-file").pipe(optional5, map34(optionToUndefined27));
98198
- var staleMs7 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined27));
98864
+ var stateFile14 = text9("state-file").pipe(optional5, map34(optionToUndefined29));
98865
+ var staleMs7 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined29));
98199
98866
  var readUiContextFocusedRemCommand = exports_Command.make("focused-rem", { stateFile: stateFile14, staleMs: staleMs7 }, ({ stateFile: stateFile15, staleMs: staleMs8 }) => gen2(function* () {
98200
98867
  const cfg = yield* AppConfig;
98201
98868
  const hostApi = yield* HostApiClient;
@@ -98223,11 +98890,11 @@ var readUiContextFocusedRemCommand = exports_Command.make("focused-rem", { state
98223
98890
  }).pipe(catchAll2(writeFailure)));
98224
98891
 
98225
98892
  // src/commands/read/uiContext/page.ts
98226
- function optionToUndefined28(opt) {
98893
+ function optionToUndefined30(opt) {
98227
98894
  return isSome2(opt) ? opt.value : undefined;
98228
98895
  }
98229
- var stateFile15 = text9("state-file").pipe(optional5, map34(optionToUndefined28));
98230
- var staleMs8 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined28));
98896
+ var stateFile15 = text9("state-file").pipe(optional5, map34(optionToUndefined30));
98897
+ var staleMs8 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined30));
98231
98898
  var readUiContextPageCommand = exports_Command.make("page", { stateFile: stateFile15, staleMs: staleMs8 }, ({ stateFile: stateFile16, staleMs: staleMs9 }) => gen2(function* () {
98232
98899
  const cfg = yield* AppConfig;
98233
98900
  const hostApi = yield* HostApiClient;
@@ -98254,159 +98921,1102 @@ var readUiContextPageCommand = exports_Command.make("page", { stateFile: stateFi
98254
98921
  });
98255
98922
  }).pipe(catchAll2(writeFailure)));
98256
98923
 
98257
- // src/commands/read/uiContext/snapshot.ts
98258
- function optionToUndefined29(opt) {
98924
+ // src/commands/read/uiContext/snapshot.ts
98925
+ function optionToUndefined31(opt) {
98926
+ return isSome2(opt) ? opt.value : undefined;
98927
+ }
98928
+ var stateFile16 = text9("state-file").pipe(optional5, map34(optionToUndefined31));
98929
+ var staleMs9 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined31));
98930
+ var readUiContextSnapshotCommand = exports_Command.make("snapshot", { stateFile: stateFile16, staleMs: staleMs9 }, ({ stateFile: stateFile17, staleMs: staleMs10 }) => gen2(function* () {
98931
+ const cfg = yield* AppConfig;
98932
+ const hostApi = yield* HostApiClient;
98933
+ const snapshot2 = cfg.apiBaseUrl ? yield* hostApi.uiContextSnapshot({ baseUrl: cfg.apiBaseUrl, stateFile: stateFile17, staleMs: staleMs10 }) : loadBridgeUiContextSnapshot({ stateFile: stateFile17, staleMs: staleMs10 });
98934
+ const ui = snapshot2.ui_context;
98935
+ const md = [
98936
+ `- status: ${snapshot2.status}`,
98937
+ `- kb_id: ${ui?.kbId ?? ""}`,
98938
+ `- kb_name: ${ui?.kbName ?? ""}`,
98939
+ `- url: ${ui?.url ?? ""}`,
98940
+ `- pane_id: ${ui?.paneId ?? ""}`,
98941
+ `- page_rem_id: ${ui?.pageRemId ?? ""}`,
98942
+ `- focused_rem_id: ${ui?.focusedRemId ?? ""}`,
98943
+ `- focused_portal_id: ${ui?.focusedPortalId ?? ""}`,
98944
+ `- source: ${ui?.source ?? ""}`,
98945
+ `- clients: ${snapshot2.clients}`,
98946
+ `- state_file: ${snapshot2.state_file}`,
98947
+ `- updated_at: ${snapshot2.updatedAt || ""}`,
98948
+ `- ui_updated_at: ${ui?.updatedAt || ""}`
98949
+ ].filter(Boolean).join(`
98950
+ `);
98951
+ yield* writeSuccess({ data: snapshot2, md });
98952
+ }).pipe(catchAll2(writeFailure)));
98953
+
98954
+ // src/commands/read/uiContext/index.ts
98955
+ var readUiContextCommand = exports_Command.make("ui-context", {}).pipe(exports_Command.withSubcommands([
98956
+ readUiContextSnapshotCommand,
98957
+ readUiContextPageCommand,
98958
+ readUiContextFocusedRemCommand,
98959
+ readUiContextDescribeCommand
98960
+ ]));
98961
+
98962
+ // src/commands/plugin/current.ts
98963
+ function optionToUndefined32(opt) {
98964
+ return isSome2(opt) ? opt.value : undefined;
98965
+ }
98966
+ var stateFile17 = text9("state-file").pipe(optional5, map34(optionToUndefined32));
98967
+ var staleMs10 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined32));
98968
+ var selectionLimit2 = integer7("selection-limit").pipe(withDefault5(5));
98969
+ function toCompact2(data) {
98970
+ return {
98971
+ current_source: typeof data?.current?.source === "string" ? data.current.source : "none",
98972
+ current_id: typeof data?.current?.id === "string" ? data.current.id : "",
98973
+ current_title: typeof data?.current?.title === "string" ? data.current.title : undefined,
98974
+ page_id: typeof data?.page?.id === "string" ? data.page.id : "",
98975
+ page_title: typeof data?.page?.title === "string" ? data.page.title : undefined,
98976
+ focus_id: typeof data?.focus?.id === "string" ? data.focus.id : "",
98977
+ focus_title: typeof data?.focus?.title === "string" ? data.focus.title : undefined,
98978
+ selection_kind: typeof data?.selection?.kind === "string" ? data.selection.kind : "none",
98979
+ selection_count: typeof data?.selection?.total_count === "number" ? data.selection.total_count : 0,
98980
+ selection_truncated: data?.selection?.truncated === true,
98981
+ selection_ids: Array.isArray(data?.selection?.ids) ? data.selection.ids.map(String) : []
98982
+ };
98983
+ }
98984
+ var pluginCurrentCommand = exports_Command.make("current", { stateFile: stateFile17, staleMs: staleMs10, selectionLimit: selectionLimit2, compact: boolean8("compact") }, ({ stateFile: stateFile18, staleMs: staleMs11, selectionLimit: selectionLimit3, compact: compact4 }) => gen2(function* () {
98985
+ const cfg = yield* AppConfig;
98986
+ const hostApi = yield* HostApiClient;
98987
+ const data = cfg.apiBaseUrl ? yield* hostApi.pluginCurrent({ baseUrl: cfg.apiBaseUrl, stateFile: stateFile18, staleMs: staleMs11, selectionLimit: selectionLimit3 }) : yield* collectPluginCurrentUseCase({ stateFile: stateFile18, staleMs: staleMs11, selectionLimit: selectionLimit3 });
98988
+ const out = compact4 ? toCompact2(data) : data;
98989
+ const currentId = String((compact4 ? out.current_id : data?.current?.id) || "").trim();
98990
+ const pageId = String((compact4 ? out.page_id : data?.page?.id) || "").trim();
98991
+ const focusId = String((compact4 ? out.focus_id : data?.focus?.id) || "").trim();
98992
+ const md = compact4 ? [
98993
+ `- current: ${currentId ? `${out.current_title ?? ""} [id=${currentId}]`.trim() : "(none)"}`,
98994
+ `- page: ${pageId ? `${out.page_title ?? ""} [id=${pageId}]`.trim() : "(none)"}`,
98995
+ `- focus: ${focusId ? `${out.focus_title ?? ""} [id=${focusId}]`.trim() : "(none)"}`,
98996
+ `- selection_count: ${out.selection_count}`,
98997
+ `- selection_kind: ${out.selection_kind}`,
98998
+ `- selection_truncated: ${out.selection_truncated ? "true" : "false"}`
98999
+ ].join(`
99000
+ `) : [
99001
+ `- current: ${currentId ? `${data?.current?.title ?? ""} [id=${currentId}]`.trim() : "(none)"}`,
99002
+ `- page: ${pageId ? `${data?.page?.title ?? ""} [id=${pageId}]`.trim() : "(none)"}`,
99003
+ `- focus: ${focusId ? `${data?.focus?.title ?? ""} [id=${focusId}]`.trim() : "(none)"}`,
99004
+ `- selection_count: ${data?.selection?.total_count ?? 0}`,
99005
+ `- selection_kind: ${data?.selection?.kind ?? "none"}`,
99006
+ `- selection_truncated: ${data?.selection?.truncated ? "true" : "false"}`
99007
+ ].join(`
99008
+ `);
99009
+ const ids3 = compact4 ? [currentId].filter(Boolean) : [currentId, pageId, focusId].filter(Boolean);
99010
+ yield* writeSuccess({ data: out, ids: ids3, md });
99011
+ }).pipe(catchAll2(writeFailure)));
99012
+
99013
+ // src/lib/pluginServerHealth.ts
99014
+ function checkPluginServerHealth(baseUrl, timeoutMs3) {
99015
+ return tryPromise2({
99016
+ try: async () => {
99017
+ const controller = new AbortController;
99018
+ const timer2 = setTimeout(() => controller.abort(), timeoutMs3);
99019
+ try {
99020
+ const res = await fetch(`${baseUrl}/manifest.json`, { signal: controller.signal });
99021
+ if (!res.ok) {
99022
+ throw new Error(`Unexpected response status: ${res.status}`);
99023
+ }
99024
+ return { base_url: baseUrl };
99025
+ } finally {
99026
+ clearTimeout(timer2);
99027
+ }
99028
+ },
99029
+ catch: (error4) => new CliError({
99030
+ code: "PLUGIN_UNAVAILABLE",
99031
+ message: "Plugin server is unavailable",
99032
+ exitCode: 1,
99033
+ details: { base_url: baseUrl, error: String(error4?.message || error4) }
99034
+ })
99035
+ });
99036
+ }
99037
+ function waitForPluginServerHealth(baseUrl, waitMs, timeoutMs3) {
99038
+ return gen2(function* () {
99039
+ if (!Number.isFinite(waitMs) || waitMs < 0) {
99040
+ return yield* fail8(new CliError({
99041
+ code: "INVALID_ARGS",
99042
+ message: "--wait must be a non-negative integer (ms)",
99043
+ exitCode: 2,
99044
+ details: { wait_ms: waitMs }
99045
+ }));
99046
+ }
99047
+ if (waitMs === 0)
99048
+ return;
99049
+ const deadline = Date.now() + waitMs;
99050
+ while (Date.now() < deadline) {
99051
+ const remaining = Math.max(0, deadline - Date.now());
99052
+ const res = yield* checkPluginServerHealth(baseUrl, Math.min(timeoutMs3, Math.max(1, remaining))).pipe(either3);
99053
+ if (isRight2(res))
99054
+ return;
99055
+ yield* sleep4(millis(300));
99056
+ }
99057
+ return yield* fail8(new CliError({
99058
+ code: "PLUGIN_UNAVAILABLE",
99059
+ message: `Timed out waiting for plugin server to become available (${waitMs}ms)`,
99060
+ exitCode: 1,
99061
+ details: { base_url: baseUrl, wait_ms: waitMs },
99062
+ hint: ["agent-remnote plugin status --json", "agent-remnote plugin logs --lines 200"]
99063
+ }));
99064
+ });
99065
+ }
99066
+
99067
+ // src/services/PluginServerFiles.ts
99068
+ import { promises as fs20 } from "node:fs";
99069
+ import path26 from "node:path";
99070
+ class PluginServerFiles extends Tag2("PluginServerFiles")() {
99071
+ }
99072
+ function ensureDir10(p3) {
99073
+ return fs20.mkdir(path26.dirname(p3), { recursive: true }).then(() => {
99074
+ return;
99075
+ });
99076
+ }
99077
+ function defaultPidFile3() {
99078
+ const envPidFile = process.env.REMNOTE_PLUGIN_SERVER_PID_FILE;
99079
+ if (typeof envPidFile === "string" && envPidFile.trim())
99080
+ return resolveUserFilePath(envPidFile);
99081
+ return path26.join(homeDir(), ".agent-remnote", "plugin-server.pid");
99082
+ }
99083
+ function defaultLogFile3() {
99084
+ const envLogFile = process.env.REMNOTE_PLUGIN_SERVER_LOG_FILE;
99085
+ if (typeof envLogFile === "string" && envLogFile.trim())
99086
+ return resolveUserFilePath(envLogFile);
99087
+ return path26.join(homeDir(), ".agent-remnote", "plugin-server.log");
99088
+ }
99089
+ function defaultStateFile3() {
99090
+ const envStateFile = process.env.REMNOTE_PLUGIN_SERVER_STATE_FILE;
99091
+ if (typeof envStateFile === "string" && envStateFile.trim())
99092
+ return resolveUserFilePath(envStateFile);
99093
+ return path26.join(homeDir(), ".agent-remnote", "plugin-server.state.json");
99094
+ }
99095
+ function parseJson3(raw4, filePath) {
99096
+ try {
99097
+ return JSON.parse(raw4);
99098
+ } catch (error4) {
99099
+ throw new CliError({
99100
+ code: "INTERNAL",
99101
+ message: `Failed to parse JSON file: ${filePath}`,
99102
+ exitCode: 1,
99103
+ details: { file_path: filePath, error: String(error4?.message || error4) }
99104
+ });
99105
+ }
99106
+ }
99107
+ var PluginServerFilesLive = succeed10(PluginServerFiles, {
99108
+ defaultPidFile: defaultPidFile3,
99109
+ defaultLogFile: defaultLogFile3,
99110
+ defaultStateFile: defaultStateFile3,
99111
+ readPidFile: (pidFilePath) => tryPromise2({
99112
+ try: async () => {
99113
+ const resolved = resolveUserFilePath(pidFilePath);
99114
+ const raw4 = await fs20.readFile(resolved, "utf8");
99115
+ return parseJson3(raw4, resolved);
99116
+ },
99117
+ catch: (error4) => {
99118
+ const code2 = error4?.code;
99119
+ if (code2 === "ENOENT")
99120
+ return;
99121
+ if (isCliError(error4))
99122
+ return error4;
99123
+ return new CliError({
99124
+ code: "INTERNAL",
99125
+ message: "Failed to read plugin server pid file",
99126
+ exitCode: 1,
99127
+ details: { file_path: pidFilePath, error: String(error4?.message || error4) }
99128
+ });
99129
+ }
99130
+ }).pipe(catchAll2((error4) => {
99131
+ if (error4 === undefined)
99132
+ return succeed8(undefined);
99133
+ return fail8(error4);
99134
+ })),
99135
+ writePidFile: (pidFilePath, value8) => tryPromise2({
99136
+ try: async () => {
99137
+ const resolved = resolveUserFilePath(pidFilePath);
99138
+ await ensureDir10(resolved);
99139
+ await fs20.writeFile(resolved, `${JSON.stringify(value8, null, 2)}
99140
+ `, "utf8");
99141
+ },
99142
+ catch: (error4) => new CliError({
99143
+ code: "INTERNAL",
99144
+ message: "Failed to write plugin server pid file",
99145
+ exitCode: 1,
99146
+ details: { file_path: pidFilePath, error: String(error4?.message || error4) }
99147
+ })
99148
+ }),
99149
+ deletePidFile: (pidFilePath) => tryPromise2({
99150
+ try: async () => {
99151
+ const resolved = resolveUserFilePath(pidFilePath);
99152
+ await fs20.rm(resolved, { force: true });
99153
+ },
99154
+ catch: (error4) => new CliError({
99155
+ code: "INTERNAL",
99156
+ message: "Failed to delete plugin server pid file",
99157
+ exitCode: 1,
99158
+ details: { file_path: pidFilePath, error: String(error4?.message || error4) }
99159
+ })
99160
+ }),
99161
+ readStateFile: (stateFilePath) => tryPromise2({
99162
+ try: async () => {
99163
+ const resolved = resolveUserFilePath(stateFilePath);
99164
+ const raw4 = await fs20.readFile(resolved, "utf8");
99165
+ return parseJson3(raw4, resolved);
99166
+ },
99167
+ catch: (error4) => {
99168
+ const code2 = error4?.code;
99169
+ if (code2 === "ENOENT")
99170
+ return;
99171
+ if (isCliError(error4))
99172
+ return error4;
99173
+ return new CliError({
99174
+ code: "INTERNAL",
99175
+ message: "Failed to read plugin server state file",
99176
+ exitCode: 1,
99177
+ details: { file_path: stateFilePath, error: String(error4?.message || error4) }
99178
+ });
99179
+ }
99180
+ }).pipe(catchAll2((error4) => {
99181
+ if (error4 === undefined)
99182
+ return succeed8(undefined);
99183
+ return fail8(error4);
99184
+ })),
99185
+ writeStateFile: (stateFilePath, value8) => tryPromise2({
99186
+ try: async () => {
99187
+ const resolved = resolveUserFilePath(stateFilePath);
99188
+ await ensureDir10(resolved);
99189
+ await fs20.writeFile(resolved, `${JSON.stringify(value8, null, 2)}
99190
+ `, "utf8");
99191
+ },
99192
+ catch: (error4) => new CliError({
99193
+ code: "INTERNAL",
99194
+ message: "Failed to write plugin server state file",
99195
+ exitCode: 1,
99196
+ details: { file_path: stateFilePath, error: String(error4?.message || error4) }
99197
+ })
99198
+ }),
99199
+ deleteStateFile: (stateFilePath) => tryPromise2({
99200
+ try: async () => {
99201
+ const resolved = resolveUserFilePath(stateFilePath);
99202
+ await fs20.rm(resolved, { force: true });
99203
+ },
99204
+ catch: (error4) => new CliError({
99205
+ code: "INTERNAL",
99206
+ message: "Failed to delete plugin server state file",
99207
+ exitCode: 1,
99208
+ details: { file_path: stateFilePath, error: String(error4?.message || error4) }
99209
+ })
99210
+ })
99211
+ });
99212
+
99213
+ // src/commands/plugin/_shared.ts
99214
+ var PLUGIN_SERVER_HEALTH_TIMEOUT_MS = 2000;
99215
+ var PLUGIN_SERVER_START_WAIT_DEFAULT_MS = 15000;
99216
+ var PLUGIN_SERVER_STOP_WAIT_DEFAULT_MS = 5000;
99217
+ var PLUGIN_SERVER_DEFAULT_HOST = "127.0.0.1";
99218
+ var PLUGIN_SERVER_DEFAULT_PORT = 8080;
99219
+ function pluginServerLocalBaseUrl(host5, port7) {
99220
+ const normalizedHost = host5 === "0.0.0.0" || host5 === "::" ? "127.0.0.1" : host5;
99221
+ return `http://${normalizedHost}:${port7}`;
99222
+ }
99223
+ function childCommandLine3(params3) {
99224
+ const command = process.argv[0];
99225
+ const script = process.argv[1];
99226
+ if (!command || !script) {
99227
+ throw new CliError({
99228
+ code: "INTERNAL",
99229
+ message: "Unable to determine the current executable entrypoint (process.argv is incomplete)",
99230
+ exitCode: 1,
99231
+ details: { argv: process.argv }
99232
+ });
99233
+ }
99234
+ const execArgv = Array.isArray(process.execArgv) ? process.execArgv : [];
99235
+ const args2 = [...execArgv, script, "plugin", "serve", "--host", params3.host, "--port", String(params3.port), "--state-file", params3.stateFile];
99236
+ return { command, args: args2 };
99237
+ }
99238
+ function toPidFileValue3(params3) {
99239
+ return {
99240
+ pid: params3.pid,
99241
+ started_at: params3.startedAt,
99242
+ host: params3.host,
99243
+ port: params3.port,
99244
+ log_file: params3.logFile,
99245
+ state_file: params3.stateFile,
99246
+ cmd: params3.cmd
99247
+ };
99248
+ }
99249
+ function startPluginServer(params3) {
99250
+ return gen2(function* () {
99251
+ const files = yield* PluginServerFiles;
99252
+ const proc = yield* Process;
99253
+ const host5 = params3.host ?? PLUGIN_SERVER_DEFAULT_HOST;
99254
+ const port7 = params3.port ?? PLUGIN_SERVER_DEFAULT_PORT;
99255
+ const pidFilePath = resolveUserFilePath(params3.pidFile ?? files.defaultPidFile());
99256
+ const logFilePath = resolveUserFilePath(params3.logFile ?? files.defaultLogFile());
99257
+ const stateFilePath = resolveUserFilePath(params3.stateFile ?? files.defaultStateFile());
99258
+ const baseUrl = pluginServerLocalBaseUrl(host5, port7);
99259
+ const existing = yield* files.readPidFile(pidFilePath);
99260
+ if (existing) {
99261
+ const alive = yield* proc.isPidRunning(existing.pid);
99262
+ if (!alive) {
99263
+ yield* files.deletePidFile(pidFilePath);
99264
+ } else {
99265
+ return {
99266
+ started: false,
99267
+ pid: existing.pid,
99268
+ pid_file: pidFilePath,
99269
+ log_file: existing.log_file ?? logFilePath,
99270
+ state_file: existing.state_file ?? stateFilePath,
99271
+ base_url: baseUrl
99272
+ };
99273
+ }
99274
+ }
99275
+ const pre = yield* checkPluginServerHealth(baseUrl, PLUGIN_SERVER_HEALTH_TIMEOUT_MS).pipe(either3);
99276
+ if (isRight2(pre)) {
99277
+ return {
99278
+ started: false,
99279
+ pid_file: pidFilePath,
99280
+ log_file: logFilePath,
99281
+ state_file: stateFilePath,
99282
+ base_url: baseUrl
99283
+ };
99284
+ }
99285
+ const cmd = yield* try_3({
99286
+ try: () => childCommandLine3({ host: host5, port: port7, stateFile: stateFilePath }),
99287
+ catch: (error4) => isCliError(error4) ? error4 : new CliError({
99288
+ code: "INTERNAL",
99289
+ message: "Failed to start plugin server",
99290
+ exitCode: 1,
99291
+ details: { error: String(error4?.message || error4) }
99292
+ })
99293
+ });
99294
+ const pid = yield* proc.spawnDetached({ command: cmd.command, args: cmd.args, logFile: logFilePath });
99295
+ yield* files.writePidFile(pidFilePath, toPidFileValue3({
99296
+ pid,
99297
+ startedAt: Date.now(),
99298
+ host: host5,
99299
+ port: port7,
99300
+ logFile: logFilePath,
99301
+ stateFile: stateFilePath,
99302
+ cmd: [cmd.command, ...cmd.args]
99303
+ }));
99304
+ yield* waitForPluginServerHealth(baseUrl, params3.waitMs, PLUGIN_SERVER_HEALTH_TIMEOUT_MS);
99305
+ return {
99306
+ started: true,
99307
+ pid,
99308
+ pid_file: pidFilePath,
99309
+ log_file: logFilePath,
99310
+ state_file: stateFilePath,
99311
+ base_url: baseUrl
99312
+ };
99313
+ });
99314
+ }
99315
+ function ensurePluginServer(params3) {
99316
+ return gen2(function* () {
99317
+ const files = yield* PluginServerFiles;
99318
+ const proc = yield* Process;
99319
+ const host5 = params3.host ?? PLUGIN_SERVER_DEFAULT_HOST;
99320
+ const port7 = params3.port ?? PLUGIN_SERVER_DEFAULT_PORT;
99321
+ const pidFilePath = resolveUserFilePath(params3.pidFile ?? files.defaultPidFile());
99322
+ const logFilePath = resolveUserFilePath(params3.logFile ?? files.defaultLogFile());
99323
+ const stateFilePath = resolveUserFilePath(params3.stateFile ?? files.defaultStateFile());
99324
+ const baseUrl = pluginServerLocalBaseUrl(host5, port7);
99325
+ const pre = yield* checkPluginServerHealth(baseUrl, PLUGIN_SERVER_HEALTH_TIMEOUT_MS).pipe(either3);
99326
+ if (isRight2(pre)) {
99327
+ const existing = yield* files.readPidFile(pidFilePath);
99328
+ if (existing) {
99329
+ const alive = yield* proc.isPidRunning(existing.pid);
99330
+ if (alive) {
99331
+ return {
99332
+ started: false,
99333
+ pid: existing.pid,
99334
+ pid_file: pidFilePath,
99335
+ log_file: existing.log_file ?? logFilePath,
99336
+ state_file: existing.state_file ?? stateFilePath,
99337
+ base_url: baseUrl
99338
+ };
99339
+ }
99340
+ }
99341
+ return {
99342
+ started: false,
99343
+ pid_file: pidFilePath,
99344
+ log_file: logFilePath,
99345
+ state_file: stateFilePath,
99346
+ base_url: baseUrl
99347
+ };
99348
+ }
99349
+ return yield* startPluginServer(params3);
99350
+ });
99351
+ }
99352
+
99353
+ // src/commands/plugin/ensure.ts
99354
+ function optionToUndefined33(opt) {
99355
+ return isSome2(opt) ? opt.value : undefined;
99356
+ }
99357
+ var host5 = text9("host").pipe(optional5, map34(optionToUndefined33));
99358
+ var port7 = integer7("port").pipe(optional5, map34(optionToUndefined33));
99359
+ var pidFile14 = text9("pid-file").pipe(optional5, map34(optionToUndefined33));
99360
+ var logFile8 = text9("log-file").pipe(optional5, map34(optionToUndefined33));
99361
+ var stateFile18 = text9("state-file").pipe(optional5, map34(optionToUndefined33));
99362
+ var pluginEnsureCommand = exports_Command.make("ensure", {
99363
+ host: host5,
99364
+ port: port7,
99365
+ wait: integer7("wait").pipe(withDefault5(PLUGIN_SERVER_START_WAIT_DEFAULT_MS)),
99366
+ pidFile: pidFile14,
99367
+ logFile: logFile8,
99368
+ stateFile: stateFile18
99369
+ }, ({ host: host6, port: port8, wait: wait3, pidFile: pidFile15, logFile: logFile9, stateFile: stateFile19 }) => gen2(function* () {
99370
+ const result = yield* ensurePluginServer({ host: host6, port: port8, waitMs: wait3, pidFile: pidFile15, logFile: logFile9, stateFile: stateFile19 });
99371
+ yield* writeSuccess({
99372
+ data: result,
99373
+ md: `- started: ${result.started}
99374
+ - pid: ${result.pid ?? ""}
99375
+ - pid_file: ${result.pid_file}
99376
+ - log_file: ${result.log_file}
99377
+ - state_file: ${result.state_file}
99378
+ - base_url: ${result.base_url}
99379
+ `
99380
+ });
99381
+ }).pipe(catchAll2(writeFailure)));
99382
+
99383
+ // src/commands/plugin/logs.ts
99384
+ function optionToUndefined34(opt) {
99385
+ return isSome2(opt) ? opt.value : undefined;
99386
+ }
99387
+ var pidFile15 = text9("pid-file").pipe(optional5, map34(optionToUndefined34));
99388
+ var file8 = text9("file").pipe(optional5, map34(optionToUndefined34));
99389
+ var pluginLogsCommand = exports_Command.make("logs", { pidFile: pidFile15, file: file8, lines: integer7("lines").pipe(withDefault5(200)), follow: boolean8("follow") }, ({ pidFile: pidFile16, file: file9, lines: lines3, follow }) => gen2(function* () {
99390
+ const cfg = yield* AppConfig;
99391
+ const files = yield* PluginServerFiles;
99392
+ const fsAccess = yield* FsAccess;
99393
+ const subprocess = yield* Subprocess;
99394
+ if (!Number.isFinite(lines3) || lines3 <= 0) {
99395
+ return yield* fail8(new CliError({ code: "INVALID_ARGS", message: "--lines must be a positive integer", exitCode: 2 }));
99396
+ }
99397
+ if (cfg.format === "ids") {
99398
+ return yield* fail8(new CliError({ code: "INVALID_ARGS", message: "This command does not support --ids output", exitCode: 2 }));
99399
+ }
99400
+ const pidFilePath = resolveUserFilePath(pidFile16 ?? files.defaultPidFile());
99401
+ const pidInfo = yield* files.readPidFile(pidFilePath);
99402
+ const logFilePath = resolveUserFilePath(file9 ?? pidInfo?.log_file ?? files.defaultLogFile());
99403
+ const exists3 = yield* fsAccess.isFile(logFilePath);
99404
+ if (!exists3) {
99405
+ return yield* fail8(new CliError({
99406
+ code: "INTERNAL",
99407
+ message: `Log file not found: ${logFilePath}`,
99408
+ exitCode: 1,
99409
+ hint: ["agent-remnote plugin start", "agent-remnote plugin status"]
99410
+ }));
99411
+ }
99412
+ if (follow) {
99413
+ if (cfg.format === "json") {
99414
+ return yield* fail8(new CliError({ code: "INVALID_ARGS", message: "--follow is not compatible with --json", exitCode: 2 }));
99415
+ }
99416
+ yield* subprocess.runInherit({ command: "tail", args: ["-n", String(lines3), "-f", logFilePath] });
99417
+ return;
99418
+ }
99419
+ const res = yield* subprocess.run({
99420
+ command: "tail",
99421
+ args: ["-n", String(lines3), logFilePath],
99422
+ timeoutMs: 1e4
99423
+ });
99424
+ if (res.exitCode !== 0) {
99425
+ return yield* fail8(new CliError({
99426
+ code: "INTERNAL",
99427
+ message: "Failed to read log file",
99428
+ exitCode: 1,
99429
+ details: { file: logFilePath, exitCode: res.exitCode, stderr: res.stderr.trim() }
99430
+ }));
99431
+ }
99432
+ const tailLines = res.stdout.trimEnd();
99433
+ yield* writeSuccess({
99434
+ data: { file: logFilePath, lines: lines3, content: tailLines },
99435
+ md: tailLines.length > 0 ? `${tailLines}
99436
+ ` : ""
99437
+ });
99438
+ }).pipe(catchAll2(writeFailure)));
99439
+
99440
+ // src/commands/plugin/restart.ts
99441
+ function optionToUndefined35(opt) {
99442
+ return isSome2(opt) ? opt.value : undefined;
99443
+ }
99444
+ var host6 = text9("host").pipe(optional5, map34(optionToUndefined35));
99445
+ var port8 = integer7("port").pipe(optional5, map34(optionToUndefined35));
99446
+ var pidFile16 = text9("pid-file").pipe(optional5, map34(optionToUndefined35));
99447
+ var logFile9 = text9("log-file").pipe(optional5, map34(optionToUndefined35));
99448
+ var stateFile19 = text9("state-file").pipe(optional5, map34(optionToUndefined35));
99449
+ var pluginRestartCommand = exports_Command.make("restart", {
99450
+ force: boolean8("force"),
99451
+ host: host6,
99452
+ port: port8,
99453
+ wait: integer7("wait").pipe(withDefault5(PLUGIN_SERVER_START_WAIT_DEFAULT_MS)),
99454
+ pidFile: pidFile16,
99455
+ logFile: logFile9,
99456
+ stateFile: stateFile19
99457
+ }, ({ force, host: host7, port: port9, wait: wait3, pidFile: pidFile17, logFile: logFile10, stateFile: stateFile20 }) => gen2(function* () {
99458
+ const files = yield* PluginServerFiles;
99459
+ const proc = yield* Process;
99460
+ const pidFilePath = resolveUserFilePath(pidFile17 ?? files.defaultPidFile());
99461
+ const existing = yield* files.readPidFile(pidFilePath);
99462
+ let stoppedPid;
99463
+ if (existing) {
99464
+ const alive = yield* proc.isPidRunning(existing.pid);
99465
+ if (alive) {
99466
+ yield* proc.kill(existing.pid, "SIGTERM");
99467
+ const exited = yield* proc.waitForExit({ pid: existing.pid, timeoutMs: PLUGIN_SERVER_STOP_WAIT_DEFAULT_MS });
99468
+ if (!exited && force) {
99469
+ yield* proc.kill(existing.pid, "SIGKILL");
99470
+ yield* proc.waitForExit({ pid: existing.pid, timeoutMs: PLUGIN_SERVER_STOP_WAIT_DEFAULT_MS });
99471
+ }
99472
+ stoppedPid = existing.pid;
99473
+ }
99474
+ yield* files.deletePidFile(pidFilePath).pipe(catchAll2(() => _void));
99475
+ yield* files.deleteStateFile(existing.state_file ?? resolveUserFilePath(stateFile20 ?? files.defaultStateFile())).pipe(catchAll2(() => _void));
99476
+ }
99477
+ const started = yield* startPluginServer({ host: host7, port: port9, waitMs: wait3, pidFile: pidFile17, logFile: logFile10, stateFile: stateFile20 });
99478
+ yield* writeSuccess({
99479
+ data: { stopped_pid: stoppedPid, ...started },
99480
+ md: `- stopped_pid: ${stoppedPid ?? ""}
99481
+ - started: ${started.started}
99482
+ - pid: ${started.pid ?? ""}
99483
+ - pid_file: ${started.pid_file}
99484
+ - base_url: ${started.base_url}
99485
+ `
99486
+ });
99487
+ }).pipe(catchAll2(writeFailure)));
99488
+
99489
+ // src/commands/plugin/search.ts
99490
+ function optionToUndefined36(opt) {
99491
+ return isSome2(opt) ? opt.value : undefined;
99492
+ }
99493
+ var searchContextRemId = text9("context-rem-id").pipe(optional5, map34(optionToUndefined36));
99494
+ var limit2 = integer7("limit").pipe(withDefault5(20));
99495
+ var timeoutMs3 = integer7("timeout-ms").pipe(withDefault5(3000));
99496
+ var ensureDaemon4 = boolean8("no-ensure-daemon").pipe(map34((v) => !v));
99497
+ function clampInt6(value8, min5, max7) {
99498
+ if (!Number.isFinite(value8))
99499
+ return min5;
99500
+ return Math.max(min5, Math.min(max7, Math.floor(value8)));
99501
+ }
99502
+ var pluginSearchCommand = exports_Command.make("search", { query: text9("query"), searchContextRemId, limit: limit2, timeoutMs: timeoutMs3, ensureDaemon: ensureDaemon4 }, ({ query, searchContextRemId: searchContextRemId2, limit: limit3, timeoutMs: timeoutMs4, ensureDaemon: ensureDaemon5 }) => gen2(function* () {
99503
+ const cfg = yield* AppConfig;
99504
+ const ws = yield* WsClient;
99505
+ const hostApi = yield* HostApiClient;
99506
+ const limitEffective = clampInt6(limit3, 1, 100);
99507
+ const rpcTimeoutMs = clampInt6(timeoutMs4, 1, 5000);
99508
+ const wsTimeoutMs = clampInt6(rpcTimeoutMs + 2000, 2000, 15000);
99509
+ const result = cfg.apiBaseUrl ? yield* hostApi.searchPlugin({
99510
+ baseUrl: cfg.apiBaseUrl,
99511
+ query,
99512
+ searchContextRemId: searchContextRemId2,
99513
+ limit: limitEffective,
99514
+ timeoutMs: rpcTimeoutMs,
99515
+ ensureDaemon: ensureDaemon5
99516
+ }) : yield* gen2(function* () {
99517
+ if (ensureDaemon5) {
99518
+ yield* ensureWsSupervisor({ waitMs: WS_START_WAIT_DEFAULT_MS });
99519
+ }
99520
+ return yield* ws.search({
99521
+ url: cfg.wsUrl,
99522
+ timeoutMs: wsTimeoutMs,
99523
+ queryText: query,
99524
+ searchContextRemId: searchContextRemId2,
99525
+ limit: limitEffective,
99526
+ rpcTimeoutMs
99527
+ });
99528
+ });
99529
+ const results = Array.isArray(result.results) ? result.results : [];
99530
+ const mdLines = [`- ok: ${result.ok === true ? "true" : "false"}`, `- results: ${results.length}`];
99531
+ for (const r of results) {
99532
+ const remId = typeof r?.remId === "string" ? r.remId : "";
99533
+ const title = typeof r?.title === "string" ? r.title : "";
99534
+ const snippet = typeof r?.snippet === "string" ? r.snippet : "";
99535
+ mdLines.push(`- ${title || remId}`);
99536
+ if (remId)
99537
+ mdLines.push(` - id: ${remId}`);
99538
+ if (snippet)
99539
+ mdLines.push(` - snippet: ${snippet}`);
99540
+ }
99541
+ yield* writeSuccess({ data: result, md: mdLines.join(`
99542
+ `) });
99543
+ }).pipe(catchAll2(writeFailure)));
99544
+
99545
+ // src/lib/pluginArtifacts.ts
99546
+ import { existsSync as existsSync2, statSync } from "node:fs";
99547
+ import path27 from "node:path";
99548
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
99549
+ function currentDir(moduleUrl) {
99550
+ return path27.dirname(fileURLToPath2(moduleUrl));
99551
+ }
99552
+ function isDirectory(targetPath) {
99553
+ try {
99554
+ return statSync(targetPath).isDirectory();
99555
+ } catch {
99556
+ return false;
99557
+ }
99558
+ }
99559
+ function distCandidates(moduleUrl) {
99560
+ const dir2 = currentDir(moduleUrl);
99561
+ return [
99562
+ path27.resolve(dir2, "../../plugin-artifacts/dist"),
99563
+ path27.resolve(dir2, "../plugin-artifacts/dist"),
99564
+ path27.resolve(dir2, "../../../plugin/dist"),
99565
+ path27.resolve(dir2, "../../plugin/dist")
99566
+ ];
99567
+ }
99568
+ function validateDistPath(targetPath) {
99569
+ return isDirectory(targetPath) && existsSync2(path27.join(targetPath, "manifest.json"));
99570
+ }
99571
+ function resolvePluginDistPath(moduleUrl = import.meta.url) {
99572
+ for (const candidate of distCandidates(moduleUrl)) {
99573
+ if (validateDistPath(candidate))
99574
+ return candidate;
99575
+ }
99576
+ throw new CliError({
99577
+ code: "DEPENDENCY_MISSING",
99578
+ message: "Plugin build artifacts are unavailable",
99579
+ exitCode: 1,
99580
+ details: { candidates: distCandidates(moduleUrl) },
99581
+ hint: [
99582
+ "Run npm run build --workspace @remnote/plugin in the repository checkout",
99583
+ "Or install a packaged agent-remnote release that includes plugin artifacts"
99584
+ ]
99585
+ });
99586
+ }
99587
+
99588
+ // src/runtime/plugin-static/runPluginStaticRuntime.ts
99589
+ import { createServer as createServer2 } from "node:http";
99590
+
99591
+ // src/lib/pluginStaticFiles.ts
99592
+ import { promises as fs21 } from "node:fs";
99593
+ import path28 from "node:path";
99594
+ var CONTENT_TYPES = new Map([
99595
+ [".css", "text/css; charset=utf-8"],
99596
+ [".html", "text/html; charset=utf-8"],
99597
+ [".js", "application/javascript; charset=utf-8"],
99598
+ [".json", "application/json; charset=utf-8"],
99599
+ [".md", "text/markdown; charset=utf-8"],
99600
+ [".txt", "text/plain; charset=utf-8"]
99601
+ ]);
99602
+ function contentTypeFor(filePath) {
99603
+ return CONTENT_TYPES.get(path28.extname(filePath).toLowerCase()) ?? "application/octet-stream";
99604
+ }
99605
+ function normalizeAssetPath(pathname) {
99606
+ let decoded;
99607
+ try {
99608
+ decoded = decodeURIComponent(pathname);
99609
+ } catch {
99610
+ return null;
99611
+ }
99612
+ const raw4 = decoded === "/" ? "index.html" : decoded.replace(/^\/+/, "");
99613
+ const normalized = path28.posix.normalize(raw4);
99614
+ if (!normalized || normalized === "." || normalized.startsWith("../") || normalized === "..")
99615
+ return null;
99616
+ return normalized;
99617
+ }
99618
+ async function readPluginStaticAsset(params3) {
99619
+ const method = params3.method || "GET";
99620
+ if (method !== "GET" && method !== "HEAD") {
99621
+ return { ok: false, statusCode: 405, message: "Method not allowed" };
99622
+ }
99623
+ const relativePath = normalizeAssetPath(params3.pathname);
99624
+ if (!relativePath) {
99625
+ return { ok: false, statusCode: 404, message: "Not found" };
99626
+ }
99627
+ const filePath = path28.resolve(params3.distPath, relativePath);
99628
+ if (filePath !== params3.distPath && !filePath.startsWith(`${params3.distPath}${path28.sep}`)) {
99629
+ return { ok: false, statusCode: 404, message: "Not found" };
99630
+ }
99631
+ try {
99632
+ const stat3 = await fs21.stat(filePath);
99633
+ if (!stat3.isFile()) {
99634
+ return { ok: false, statusCode: 404, message: "Not found" };
99635
+ }
99636
+ const body = method === "HEAD" ? undefined : await fs21.readFile(filePath);
99637
+ return {
99638
+ ok: true,
99639
+ statusCode: 200,
99640
+ contentType: contentTypeFor(filePath),
99641
+ contentLength: stat3.size,
99642
+ body
99643
+ };
99644
+ } catch {
99645
+ return { ok: false, statusCode: 404, message: "Not found" };
99646
+ }
99647
+ }
99648
+
99649
+ // src/runtime/plugin-static/runPluginStaticRuntime.ts
99650
+ function sendText(res, statusCode, message2) {
99651
+ res.statusCode = statusCode;
99652
+ res.setHeader("content-type", "text/plain; charset=utf-8");
99653
+ res.end(message2);
99654
+ }
99655
+ function requestPathname(req) {
99656
+ return new URL(req.url || "/", "http://127.0.0.1").pathname;
99657
+ }
99658
+ async function handleRequest(req, res, distPath) {
99659
+ const result = await readPluginStaticAsset({
99660
+ distPath,
99661
+ pathname: requestPathname(req),
99662
+ method: req.method || "GET"
99663
+ });
99664
+ if (!result.ok) {
99665
+ sendText(res, result.statusCode, result.message);
99666
+ return;
99667
+ }
99668
+ res.statusCode = result.statusCode;
99669
+ res.setHeader("content-type", result.contentType);
99670
+ res.setHeader("content-length", String(result.contentLength));
99671
+ if (result.body === undefined)
99672
+ res.end();
99673
+ else
99674
+ res.end(result.body);
99675
+ }
99676
+ function runPluginStaticRuntime(params3) {
99677
+ return gen2(function* () {
99678
+ const distPath = params3?.distPath ?? (yield* try_3({
99679
+ try: () => resolvePluginDistPath(),
99680
+ catch: (error4) => isCliError(error4) ? error4 : new CliError({
99681
+ code: "DEPENDENCY_MISSING",
99682
+ message: "Plugin build artifacts are unavailable",
99683
+ exitCode: 1,
99684
+ details: { error: String(error4?.message || error4) }
99685
+ })
99686
+ }));
99687
+ const host7 = params3?.host ?? "127.0.0.1";
99688
+ const port9 = params3?.port ?? 8080;
99689
+ const server = createServer2((req, res) => {
99690
+ handleRequest(req, res, distPath).catch(() => {
99691
+ if (!res.headersSent) {
99692
+ sendText(res, 500, "Internal server error");
99693
+ }
99694
+ });
99695
+ });
99696
+ const listen = async((resume2) => {
99697
+ const onError4 = (error4) => {
99698
+ cleanup();
99699
+ resume2(fail8(new CliError({
99700
+ code: "PLUGIN_UNAVAILABLE",
99701
+ message: "Failed to start plugin static server",
99702
+ exitCode: 1,
99703
+ details: { host: host7, port: port9, error: String(error4?.message || error4) }
99704
+ })));
99705
+ };
99706
+ const onListening = () => {
99707
+ cleanup();
99708
+ resume2(_void);
99709
+ };
99710
+ const cleanup = () => {
99711
+ server.off("error", onError4);
99712
+ server.off("listening", onListening);
99713
+ };
99714
+ server.once("error", onError4);
99715
+ server.once("listening", onListening);
99716
+ server.listen(port9, host7);
99717
+ return sync3(cleanup);
99718
+ });
99719
+ yield* listen;
99720
+ const actualPort = (() => {
99721
+ const addr = server.address();
99722
+ return addr && typeof addr === "object" ? addr.port : port9;
99723
+ })();
99724
+ if (params3?.onStarted) {
99725
+ yield* params3.onStarted({ host: host7, port: actualPort, distPath });
99726
+ }
99727
+ const waitForStop = async((resume2) => {
99728
+ let stopping = false;
99729
+ const stop2 = () => {
99730
+ if (stopping)
99731
+ return;
99732
+ stopping = true;
99733
+ try {
99734
+ server.close(() => resume2(_void));
99735
+ } catch {
99736
+ resume2(_void);
99737
+ }
99738
+ };
99739
+ const onTerm = () => stop2();
99740
+ const onInt = () => stop2();
99741
+ process.on("SIGTERM", onTerm);
99742
+ process.on("SIGINT", onInt);
99743
+ return sync3(() => {
99744
+ process.off("SIGTERM", onTerm);
99745
+ process.off("SIGINT", onInt);
99746
+ stop2();
99747
+ });
99748
+ });
99749
+ yield* waitForStop;
99750
+ });
99751
+ }
99752
+
99753
+ // src/commands/plugin/serve.ts
99754
+ function optionToUndefined37(opt) {
99755
+ return isSome2(opt) ? opt.value : undefined;
99756
+ }
99757
+ var host7 = text9("host").pipe(optional5, map34(optionToUndefined37));
99758
+ var port9 = integer7("port").pipe(optional5, map34(optionToUndefined37));
99759
+ var stateFile20 = text9("state-file").pipe(optional5, map34(optionToUndefined37));
99760
+ var pluginServeCommand = exports_Command.make("serve", { host: host7, port: port9, stateFile: stateFile20 }, ({ host: host8, port: port10, stateFile: stateFile21 }) => gen2(function* () {
99761
+ const cfg = yield* AppConfig;
99762
+ const out = yield* Output;
99763
+ const files = yield* PluginServerFiles;
99764
+ const distPath = yield* try_3({
99765
+ try: () => resolvePluginDistPath(),
99766
+ catch: (error4) => isCliError(error4) ? error4 : new CliError({
99767
+ code: "DEPENDENCY_MISSING",
99768
+ message: "Plugin build artifacts are unavailable",
99769
+ exitCode: 1,
99770
+ details: { error: String(error4?.message || error4) }
99771
+ })
99772
+ });
99773
+ const bindHost = host8 ?? "127.0.0.1";
99774
+ const bindPort = port10 ?? 8080;
99775
+ const stateFilePath = stateFile21 ? resolveUserFilePath(stateFile21) : undefined;
99776
+ const runtime6 = runPluginStaticRuntime({
99777
+ host: bindHost,
99778
+ port: bindPort,
99779
+ distPath,
99780
+ onStarted: ({ host: host9, port: port11, distPath: distPath2 }) => gen2(function* () {
99781
+ const baseUrl = pluginServerLocalBaseUrl(host9, port11);
99782
+ if (stateFilePath) {
99783
+ yield* files.writeStateFile(stateFilePath, {
99784
+ running: true,
99785
+ pid: process.pid,
99786
+ host: host9,
99787
+ port: port11,
99788
+ startedAt: Date.now(),
99789
+ localBaseUrl: baseUrl,
99790
+ distPath: distPath2
99791
+ });
99792
+ }
99793
+ if (cfg.format === "json" || cfg.quiet || cfg.format === "ids")
99794
+ return;
99795
+ yield* out.stdout(cfg.debug ? `
99796
+ agent-remnote plugin ready
99797
+
99798
+ Local: ${baseUrl}/
99799
+ Dist: ${distPath2}
99800
+ ` : `
99801
+ agent-remnote plugin ready
99802
+
99803
+ Local: ${baseUrl}/
99804
+ `);
99805
+ })
99806
+ }).pipe(ensuring2(stateFilePath ? files.deleteStateFile(stateFilePath).pipe(catchAll2(() => _void)) : _void));
99807
+ yield* runtime6;
99808
+ }).pipe(catchAll2(writeFailure)));
99809
+
99810
+ // src/commands/plugin/start.ts
99811
+ function optionToUndefined38(opt) {
98259
99812
  return isSome2(opt) ? opt.value : undefined;
98260
99813
  }
98261
- var stateFile16 = text9("state-file").pipe(optional5, map34(optionToUndefined29));
98262
- var staleMs9 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined29));
98263
- var readUiContextSnapshotCommand = exports_Command.make("snapshot", { stateFile: stateFile16, staleMs: staleMs9 }, ({ stateFile: stateFile17, staleMs: staleMs10 }) => gen2(function* () {
98264
- const cfg = yield* AppConfig;
98265
- const hostApi = yield* HostApiClient;
98266
- const snapshot2 = cfg.apiBaseUrl ? yield* hostApi.uiContextSnapshot({ baseUrl: cfg.apiBaseUrl, stateFile: stateFile17, staleMs: staleMs10 }) : loadBridgeUiContextSnapshot({ stateFile: stateFile17, staleMs: staleMs10 });
98267
- const ui = snapshot2.ui_context;
98268
- const md = [
98269
- `- status: ${snapshot2.status}`,
98270
- `- kb_id: ${ui?.kbId ?? ""}`,
98271
- `- kb_name: ${ui?.kbName ?? ""}`,
98272
- `- url: ${ui?.url ?? ""}`,
98273
- `- pane_id: ${ui?.paneId ?? ""}`,
98274
- `- page_rem_id: ${ui?.pageRemId ?? ""}`,
98275
- `- focused_rem_id: ${ui?.focusedRemId ?? ""}`,
98276
- `- focused_portal_id: ${ui?.focusedPortalId ?? ""}`,
98277
- `- source: ${ui?.source ?? ""}`,
98278
- `- clients: ${snapshot2.clients}`,
98279
- `- state_file: ${snapshot2.state_file}`,
98280
- `- updated_at: ${snapshot2.updatedAt || ""}`,
98281
- `- ui_updated_at: ${ui?.updatedAt || ""}`
98282
- ].filter(Boolean).join(`
98283
- `);
98284
- yield* writeSuccess({ data: snapshot2, md });
99814
+ var host8 = text9("host").pipe(optional5, map34(optionToUndefined38));
99815
+ var port10 = integer7("port").pipe(optional5, map34(optionToUndefined38));
99816
+ var pidFile17 = text9("pid-file").pipe(optional5, map34(optionToUndefined38));
99817
+ var logFile10 = text9("log-file").pipe(optional5, map34(optionToUndefined38));
99818
+ var stateFile21 = text9("state-file").pipe(optional5, map34(optionToUndefined38));
99819
+ var pluginStartCommand = exports_Command.make("start", {
99820
+ host: host8,
99821
+ port: port10,
99822
+ wait: integer7("wait").pipe(withDefault5(PLUGIN_SERVER_START_WAIT_DEFAULT_MS)),
99823
+ pidFile: pidFile17,
99824
+ logFile: logFile10,
99825
+ stateFile: stateFile21
99826
+ }, ({ host: host9, port: port11, wait: wait3, pidFile: pidFile18, logFile: logFile11, stateFile: stateFile22 }) => gen2(function* () {
99827
+ const result = yield* startPluginServer({ host: host9, port: port11, waitMs: wait3, pidFile: pidFile18, logFile: logFile11, stateFile: stateFile22 });
99828
+ yield* writeSuccess({
99829
+ data: result,
99830
+ md: `- started: ${result.started}
99831
+ - pid: ${result.pid ?? ""}
99832
+ - pid_file: ${result.pid_file}
99833
+ - log_file: ${result.log_file}
99834
+ - state_file: ${result.state_file}
99835
+ - base_url: ${result.base_url}
99836
+ `
99837
+ });
98285
99838
  }).pipe(catchAll2(writeFailure)));
98286
99839
 
98287
- // src/commands/read/uiContext/index.ts
98288
- var readUiContextCommand = exports_Command.make("ui-context", {}).pipe(exports_Command.withSubcommands([
98289
- readUiContextSnapshotCommand,
98290
- readUiContextPageCommand,
98291
- readUiContextFocusedRemCommand,
98292
- readUiContextDescribeCommand
98293
- ]));
98294
-
98295
- // src/commands/plugin/current.ts
98296
- function optionToUndefined30(opt) {
99840
+ // src/commands/plugin/status.ts
99841
+ function optionToUndefined39(opt) {
98297
99842
  return isSome2(opt) ? opt.value : undefined;
98298
99843
  }
98299
- var stateFile17 = text9("state-file").pipe(optional5, map34(optionToUndefined30));
98300
- var staleMs10 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined30));
98301
- var selectionLimit2 = integer7("selection-limit").pipe(withDefault5(5));
98302
- function toCompact2(data) {
98303
- return {
98304
- current_source: typeof data?.current?.source === "string" ? data.current.source : "none",
98305
- current_id: typeof data?.current?.id === "string" ? data.current.id : "",
98306
- current_title: typeof data?.current?.title === "string" ? data.current.title : undefined,
98307
- page_id: typeof data?.page?.id === "string" ? data.page.id : "",
98308
- page_title: typeof data?.page?.title === "string" ? data.page.title : undefined,
98309
- focus_id: typeof data?.focus?.id === "string" ? data.focus.id : "",
98310
- focus_title: typeof data?.focus?.title === "string" ? data.focus.title : undefined,
98311
- selection_kind: typeof data?.selection?.kind === "string" ? data.selection.kind : "none",
98312
- selection_count: typeof data?.selection?.total_count === "number" ? data.selection.total_count : 0,
98313
- selection_truncated: data?.selection?.truncated === true,
98314
- selection_ids: Array.isArray(data?.selection?.ids) ? data.selection.ids.map(String) : []
98315
- };
99844
+ var pidFile18 = text9("pid-file").pipe(optional5, map34(optionToUndefined39));
99845
+ var stateFile22 = text9("state-file").pipe(optional5, map34(optionToUndefined39));
99846
+ function getPluginStatus(params3) {
99847
+ return gen2(function* () {
99848
+ const files = yield* PluginServerFiles;
99849
+ const proc = yield* Process;
99850
+ const pidInfo = yield* files.readPidFile(params3.pidFilePath);
99851
+ const effectiveStateFilePath = resolveUserFilePath(params3.explicitStateFilePath ?? pidInfo?.state_file ?? files.defaultStateFile());
99852
+ const state = yield* files.readStateFile(effectiveStateFilePath);
99853
+ const pid = pidInfo?.pid;
99854
+ const running4 = typeof pid === "number" ? yield* proc.isPidRunning(pid) : false;
99855
+ const host9 = pidInfo?.host ?? state?.host ?? PLUGIN_SERVER_DEFAULT_HOST;
99856
+ const port11 = pidInfo?.port ?? state?.port ?? PLUGIN_SERVER_DEFAULT_PORT;
99857
+ const baseUrl = pluginServerLocalBaseUrl(host9, port11);
99858
+ const health = yield* checkPluginServerHealth(baseUrl, PLUGIN_SERVER_HEALTH_TIMEOUT_MS).pipe(either3);
99859
+ return {
99860
+ service: {
99861
+ running: running4,
99862
+ pid: pid ?? null,
99863
+ pid_file: params3.pidFilePath,
99864
+ log_file: pidInfo?.log_file ?? files.defaultLogFile(),
99865
+ state_file: effectiveStateFilePath,
99866
+ started_at: pidInfo?.started_at ?? state?.startedAt ?? null
99867
+ },
99868
+ state: state ?? null,
99869
+ plugin_server: {
99870
+ healthy: health._tag === "Right",
99871
+ base_url: baseUrl,
99872
+ host: host9,
99873
+ port: port11,
99874
+ dist_path: state?.distPath ?? "",
99875
+ error: health._tag === "Left" ? health.left.message : undefined
99876
+ }
99877
+ };
99878
+ });
98316
99879
  }
98317
- var pluginCurrentCommand = exports_Command.make("current", { stateFile: stateFile17, staleMs: staleMs10, selectionLimit: selectionLimit2, compact: boolean8("compact") }, ({ stateFile: stateFile18, staleMs: staleMs11, selectionLimit: selectionLimit3, compact: compact4 }) => gen2(function* () {
98318
- const cfg = yield* AppConfig;
98319
- const hostApi = yield* HostApiClient;
98320
- const data = cfg.apiBaseUrl ? yield* hostApi.pluginCurrent({ baseUrl: cfg.apiBaseUrl, stateFile: stateFile18, staleMs: staleMs11, selectionLimit: selectionLimit3 }) : yield* collectPluginCurrentUseCase({ stateFile: stateFile18, staleMs: staleMs11, selectionLimit: selectionLimit3 });
98321
- const out = compact4 ? toCompact2(data) : data;
98322
- const currentId = String((compact4 ? out.current_id : data?.current?.id) || "").trim();
98323
- const pageId = String((compact4 ? out.page_id : data?.page?.id) || "").trim();
98324
- const focusId = String((compact4 ? out.focus_id : data?.focus?.id) || "").trim();
98325
- const md = compact4 ? [
98326
- `- current: ${currentId ? `${out.current_title ?? ""} [id=${currentId}]`.trim() : "(none)"}`,
98327
- `- page: ${pageId ? `${out.page_title ?? ""} [id=${pageId}]`.trim() : "(none)"}`,
98328
- `- focus: ${focusId ? `${out.focus_title ?? ""} [id=${focusId}]`.trim() : "(none)"}`,
98329
- `- selection_count: ${out.selection_count}`,
98330
- `- selection_kind: ${out.selection_kind}`,
98331
- `- selection_truncated: ${out.selection_truncated ? "true" : "false"}`
98332
- ].join(`
98333
- `) : [
98334
- `- current: ${currentId ? `${data?.current?.title ?? ""} [id=${currentId}]`.trim() : "(none)"}`,
98335
- `- page: ${pageId ? `${data?.page?.title ?? ""} [id=${pageId}]`.trim() : "(none)"}`,
98336
- `- focus: ${focusId ? `${data?.focus?.title ?? ""} [id=${focusId}]`.trim() : "(none)"}`,
98337
- `- selection_count: ${data?.selection?.total_count ?? 0}`,
98338
- `- selection_kind: ${data?.selection?.kind ?? "none"}`,
98339
- `- selection_truncated: ${data?.selection?.truncated ? "true" : "false"}`
99880
+ var pluginStatusCommand = exports_Command.make("status", { pidFile: pidFile18, stateFile: stateFile22 }, ({ pidFile: pidFile19, stateFile: stateFile23 }) => gen2(function* () {
99881
+ const files = yield* PluginServerFiles;
99882
+ const pidFilePath = resolveUserFilePath(pidFile19 ?? files.defaultPidFile());
99883
+ const data = yield* getPluginStatus({
99884
+ pidFilePath,
99885
+ explicitStateFilePath: stateFile23 ? resolveUserFilePath(stateFile23) : undefined
99886
+ });
99887
+ const md = [
99888
+ `- service_running: ${data.service.running}`,
99889
+ `- pid: ${data.service.pid ?? ""}`,
99890
+ `- pid_file: ${data.service.pid_file}`,
99891
+ `- log_file: ${data.service.log_file}`,
99892
+ `- state_file: ${data.service.state_file}`,
99893
+ `- started_at: ${data.service.started_at ?? ""}`,
99894
+ `- plugin_server_healthy: ${data.plugin_server.healthy}`,
99895
+ `- base_url: ${data.plugin_server.base_url}`,
99896
+ `- host: ${data.plugin_server.host}`,
99897
+ `- port: ${data.plugin_server.port}`,
99898
+ `- dist_path: ${data.plugin_server.dist_path}`
98340
99899
  ].join(`
98341
99900
  `);
98342
- const ids3 = compact4 ? [currentId].filter(Boolean) : [currentId, pageId, focusId].filter(Boolean);
98343
- yield* writeSuccess({ data: out, ids: ids3, md });
99901
+ yield* writeSuccess({ data, md });
98344
99902
  }).pipe(catchAll2(writeFailure)));
98345
99903
 
98346
- // src/commands/plugin/search.ts
98347
- function optionToUndefined31(opt) {
99904
+ // src/commands/plugin/stop.ts
99905
+ function optionToUndefined40(opt) {
98348
99906
  return isSome2(opt) ? opt.value : undefined;
98349
99907
  }
98350
- var searchContextRemId = text9("context-rem-id").pipe(optional5, map34(optionToUndefined31));
98351
- var limit2 = integer7("limit").pipe(withDefault5(20));
98352
- var timeoutMs3 = integer7("timeout-ms").pipe(withDefault5(3000));
98353
- var ensureDaemon4 = boolean8("no-ensure-daemon").pipe(map34((v) => !v));
98354
- function clampInt6(value8, min5, max7) {
98355
- if (!Number.isFinite(value8))
98356
- return min5;
98357
- return Math.max(min5, Math.min(max7, Math.floor(value8)));
99908
+ var pidFile19 = text9("pid-file").pipe(optional5, map34(optionToUndefined40));
99909
+ var stateFile23 = text9("state-file").pipe(optional5, map34(optionToUndefined40));
99910
+ function isEsrch(error4) {
99911
+ if (!(error4 instanceof CliError))
99912
+ return false;
99913
+ const code2 = error4.details?.code;
99914
+ const message2 = String(error4.details?.error ?? error4.message ?? "");
99915
+ return code2 === "ESRCH" || message2.includes("ESRCH");
98358
99916
  }
98359
- var pluginSearchCommand = exports_Command.make("search", { query: text9("query"), searchContextRemId, limit: limit2, timeoutMs: timeoutMs3, ensureDaemon: ensureDaemon4 }, ({ query, searchContextRemId: searchContextRemId2, limit: limit3, timeoutMs: timeoutMs4, ensureDaemon: ensureDaemon5 }) => gen2(function* () {
98360
- const cfg = yield* AppConfig;
98361
- const ws = yield* WsClient;
98362
- const hostApi = yield* HostApiClient;
98363
- const limitEffective = clampInt6(limit3, 1, 100);
98364
- const rpcTimeoutMs = clampInt6(timeoutMs4, 1, 5000);
98365
- const wsTimeoutMs = clampInt6(rpcTimeoutMs + 2000, 2000, 15000);
98366
- const result = cfg.apiBaseUrl ? yield* hostApi.searchPlugin({
98367
- baseUrl: cfg.apiBaseUrl,
98368
- query,
98369
- searchContextRemId: searchContextRemId2,
98370
- limit: limitEffective,
98371
- timeoutMs: rpcTimeoutMs,
98372
- ensureDaemon: ensureDaemon5
98373
- }) : yield* gen2(function* () {
98374
- if (ensureDaemon5) {
98375
- yield* ensureWsSupervisor({ waitMs: WS_START_WAIT_DEFAULT_MS });
99917
+ function stopPluginServer(params3) {
99918
+ return gen2(function* () {
99919
+ const files = yield* PluginServerFiles;
99920
+ const proc = yield* Process;
99921
+ const existing = yield* files.readPidFile(params3.pidFilePath);
99922
+ if (!existing) {
99923
+ yield* files.deleteStateFile(params3.stateFilePath).pipe(catchAll2(() => _void));
99924
+ return {
99925
+ stopped: true,
99926
+ pid_file: params3.pidFilePath
99927
+ };
98376
99928
  }
98377
- return yield* ws.search({
98378
- url: cfg.wsUrl,
98379
- timeoutMs: wsTimeoutMs,
98380
- queryText: query,
98381
- searchContextRemId: searchContextRemId2,
98382
- limit: limitEffective,
98383
- rpcTimeoutMs
99929
+ const cleanupStale = () => gen2(function* () {
99930
+ yield* files.deletePidFile(params3.pidFilePath);
99931
+ yield* files.deleteStateFile(existing.state_file ?? params3.stateFilePath).pipe(catchAll2(() => _void));
99932
+ return {
99933
+ stopped: true,
99934
+ stale: true,
99935
+ pid: existing.pid,
99936
+ pid_file: params3.pidFilePath
99937
+ };
98384
99938
  });
99939
+ const alive = yield* proc.isPidRunning(existing.pid);
99940
+ if (!alive) {
99941
+ return yield* cleanupStale();
99942
+ }
99943
+ const termResult = yield* proc.kill(existing.pid, "SIGTERM").pipe(either3);
99944
+ if (termResult._tag === "Left") {
99945
+ if (isEsrch(termResult.left)) {
99946
+ return yield* cleanupStale();
99947
+ }
99948
+ return yield* fail8(termResult.left);
99949
+ }
99950
+ const exited = yield* proc.waitForExit({ pid: existing.pid, timeoutMs: PLUGIN_SERVER_STOP_WAIT_DEFAULT_MS });
99951
+ if (!exited) {
99952
+ if (!params3.force) {
99953
+ return yield* fail8(new CliError({
99954
+ code: "INTERNAL",
99955
+ message: `Plugin server did not exit within ${PLUGIN_SERVER_STOP_WAIT_DEFAULT_MS}ms; use --force`,
99956
+ exitCode: 1,
99957
+ details: { pid: existing.pid, pid_file: params3.pidFilePath }
99958
+ }));
99959
+ }
99960
+ yield* proc.kill(existing.pid, "SIGKILL");
99961
+ const killed = yield* proc.waitForExit({ pid: existing.pid, timeoutMs: PLUGIN_SERVER_STOP_WAIT_DEFAULT_MS });
99962
+ if (!killed) {
99963
+ return yield* fail8(new CliError({
99964
+ code: "INTERNAL",
99965
+ message: "Force stop failed (process is still alive)",
99966
+ exitCode: 1,
99967
+ details: { pid: existing.pid, pid_file: params3.pidFilePath }
99968
+ }));
99969
+ }
99970
+ }
99971
+ yield* files.deletePidFile(params3.pidFilePath);
99972
+ yield* files.deleteStateFile(existing.state_file ?? params3.stateFilePath).pipe(catchAll2(() => _void));
99973
+ return {
99974
+ stopped: true,
99975
+ pid: existing.pid,
99976
+ pid_file: params3.pidFilePath
99977
+ };
99978
+ });
99979
+ }
99980
+ var pluginStopCommand = exports_Command.make("stop", { force: boolean8("force"), pidFile: pidFile19, stateFile: stateFile23 }, ({ force, pidFile: pidFile20, stateFile: stateFile24 }) => gen2(function* () {
99981
+ const files = yield* PluginServerFiles;
99982
+ const pidFilePath = resolveUserFilePath(pidFile20 ?? files.defaultPidFile());
99983
+ const stateFilePath = resolveUserFilePath(stateFile24 ?? files.defaultStateFile());
99984
+ const result = yield* stopPluginServer({ force, pidFilePath, stateFilePath });
99985
+ yield* writeSuccess({
99986
+ data: result,
99987
+ md: result.stale === true ? `- stopped: true
99988
+ - stale: true
99989
+ - pid: ${result.pid ?? ""}
99990
+ - pid_file: ${pidFilePath}
99991
+ ` : result.pid ? `- stopped: true
99992
+ - pid: ${result.pid}
99993
+ - pid_file: ${pidFilePath}
99994
+ ` : `- stopped: true
99995
+ - pid_file: ${pidFilePath}
99996
+ `
98385
99997
  });
98386
- const results = Array.isArray(result.results) ? result.results : [];
98387
- const mdLines = [`- ok: ${result.ok === true ? "true" : "false"}`, `- results: ${results.length}`];
98388
- for (const r of results) {
98389
- const remId = typeof r?.remId === "string" ? r.remId : "";
98390
- const title = typeof r?.title === "string" ? r.title : "";
98391
- const snippet = typeof r?.snippet === "string" ? r.snippet : "";
98392
- mdLines.push(`- ${title || remId}`);
98393
- if (remId)
98394
- mdLines.push(` - id: ${remId}`);
98395
- if (snippet)
98396
- mdLines.push(` - snippet: ${snippet}`);
98397
- }
98398
- yield* writeSuccess({ data: result, md: mdLines.join(`
98399
- `) });
98400
99998
  }).pipe(catchAll2(writeFailure)));
98401
99999
 
98402
100000
  // src/commands/plugin/index.ts
98403
- var pluginCommand = exports_Command.make("plugin", {}).pipe(exports_Command.withSubcommands([pluginCurrentCommand, pluginSearchCommand, readUiContextCommand, readSelectionCommand]));
100001
+ var pluginCommand = exports_Command.make("plugin", {}).pipe(exports_Command.withSubcommands([
100002
+ pluginCurrentCommand,
100003
+ pluginSearchCommand,
100004
+ pluginServeCommand,
100005
+ pluginStartCommand,
100006
+ pluginStopCommand,
100007
+ pluginRestartCommand,
100008
+ pluginEnsureCommand,
100009
+ pluginStatusCommand,
100010
+ pluginLogsCommand,
100011
+ readUiContextCommand,
100012
+ readSelectionCommand
100013
+ ]));
98404
100014
 
98405
100015
  // src/commands/read/powerup/list.ts
98406
- function optionToUndefined32(opt) {
100016
+ function optionToUndefined41(opt) {
98407
100017
  return isSome2(opt) ? opt.value : undefined;
98408
100018
  }
98409
- var query = text9("query").pipe(optional5, map34(optionToUndefined32));
100019
+ var query = text9("query").pipe(optional5, map34(optionToUndefined41));
98410
100020
  var limit3 = integer7("limit").pipe(withDefault5(50));
98411
100021
  var offset = integer7("offset").pipe(withDefault5(0));
98412
100022
  function safeJsonParse3(input) {
@@ -98761,11 +100371,11 @@ var readPowerupResolveCommand = exports_Command.make("resolve", { powerup: text9
98761
100371
  })), catchAll2(writeFailure)));
98762
100372
 
98763
100373
  // src/commands/read/powerup/schema.ts
98764
- function optionToUndefined33(opt) {
100374
+ function optionToUndefined42(opt) {
98765
100375
  return isSome2(opt) ? opt.value : undefined;
98766
100376
  }
98767
- var powerup = text9("powerup").pipe(optional5, map34(optionToUndefined33));
98768
- var id2 = text9("id").pipe(optional5, map34(optionToUndefined33));
100377
+ var powerup = text9("powerup").pipe(optional5, map34(optionToUndefined42));
100378
+ var id2 = text9("id").pipe(optional5, map34(optionToUndefined42));
98769
100379
  var limit4 = integer7("limit").pipe(withDefault5(50));
98770
100380
  var offset2 = integer7("offset").pipe(withDefault5(0));
98771
100381
  var readPowerupSchemaCommand = exports_Command.make("schema", { powerup, id: id2, includeOptions: boolean8("include-options"), limit: limit4, offset: offset2 }, ({ powerup: powerup2, id: id3, includeOptions, limit: limit5, offset: offset3 }) => gen2(function* () {
@@ -99046,33 +100656,33 @@ function compileTableValueOps(params3) {
99046
100656
  }
99047
100657
 
99048
100658
  // src/commands/write/_shared.ts
99049
- function optionToUndefined34(opt) {
100659
+ function optionToUndefined43(opt) {
99050
100660
  return isSome2(opt) ? opt.value : undefined;
99051
100661
  }
99052
100662
  function readOptionalText3(name) {
99053
- return text9(name).pipe(optional5, map34(optionToUndefined34));
100663
+ return text9(name).pipe(optional5, map34(optionToUndefined43));
99054
100664
  }
99055
100665
  var writeCommonOptions = {
99056
100666
  notify: boolean8("no-notify").pipe(map34((v) => !v)),
99057
100667
  ensureDaemon: boolean8("no-ensure-daemon").pipe(map34((v) => !v)),
99058
100668
  wait: boolean8("wait"),
99059
- timeoutMs: integer7("timeout-ms").pipe(optional5, map34(optionToUndefined34)),
99060
- pollMs: integer7("poll-ms").pipe(optional5, map34(optionToUndefined34)),
100669
+ timeoutMs: integer7("timeout-ms").pipe(optional5, map34(optionToUndefined43)),
100670
+ pollMs: integer7("poll-ms").pipe(optional5, map34(optionToUndefined43)),
99061
100671
  dryRun: boolean8("dry-run"),
99062
- priority: integer7("priority").pipe(optional5, map34(optionToUndefined34)),
100672
+ priority: integer7("priority").pipe(optional5, map34(optionToUndefined43)),
99063
100673
  clientId: readOptionalText3("client-id"),
99064
100674
  idempotencyKey: readOptionalText3("idempotency-key"),
99065
100675
  meta: readOptionalText3("meta")
99066
100676
  };
99067
100677
 
99068
100678
  // src/commands/write/powerup/apply.ts
99069
- var dispatchMode = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined34));
100679
+ var dispatchMode = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined43));
99070
100680
  var writePowerupApplyCommand = exports_Command.make("apply", {
99071
100681
  rem: text9("rem"),
99072
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
99073
- powerup: text9("powerup").pipe(optional5, map34(optionToUndefined34)),
99074
- text: text9("text").pipe(optional5, map34(optionToUndefined34)),
99075
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
100682
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
100683
+ powerup: text9("powerup").pipe(optional5, map34(optionToUndefined43)),
100684
+ text: text9("text").pipe(optional5, map34(optionToUndefined43)),
100685
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
99076
100686
  ensureTag: boolean8("no-ensure-tag").pipe(map34((v) => !v)),
99077
100687
  notify: writeCommonOptions.notify,
99078
100688
  ensureDaemon: writeCommonOptions.ensureDaemon,
@@ -99535,11 +101145,11 @@ var writePowerupOptionCommand = exports_Command.make("option", {}).pipe(exports_
99535
101145
 
99536
101146
  // src/commands/write/powerup/property/add.ts
99537
101147
  var writePowerupPropertyAddCommand = exports_Command.make("add", {
99538
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
99539
- powerup: text9("powerup").pipe(optional5, map34(optionToUndefined34)),
101148
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
101149
+ powerup: text9("powerup").pipe(optional5, map34(optionToUndefined43)),
99540
101150
  name: text9("name"),
99541
- type: text9("type").pipe(optional5, map34(optionToUndefined34)),
99542
- options: text9("options").pipe(optional5, map34(optionToUndefined34)),
101151
+ type: text9("type").pipe(optional5, map34(optionToUndefined43)),
101152
+ options: text9("options").pipe(optional5, map34(optionToUndefined43)),
99543
101153
  notify: writeCommonOptions.notify,
99544
101154
  ensureDaemon: writeCommonOptions.ensureDaemon,
99545
101155
  wait: writeCommonOptions.wait,
@@ -99703,14 +101313,14 @@ var writePowerupPropertySetTypeCommand = exports_Command.make("set-type", {
99703
101313
  var writePowerupPropertyCommand = exports_Command.make("property", {}).pipe(exports_Command.withSubcommands([writePowerupPropertyAddCommand, writePowerupPropertySetTypeCommand]));
99704
101314
 
99705
101315
  // src/commands/write/powerup/record/add.ts
99706
- var dispatchMode2 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined34));
101316
+ var dispatchMode2 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined43));
99707
101317
  var writePowerupRecordAddCommand = exports_Command.make("add", {
99708
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
99709
- powerup: text9("powerup").pipe(optional5, map34(optionToUndefined34)),
99710
- parent: text9("parent").pipe(optional5, map34(optionToUndefined34)),
99711
- ref: text9("ref").pipe(optional5, map34(optionToUndefined34)),
99712
- text: text9("text").pipe(optional5, map34(optionToUndefined34)),
99713
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
101318
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
101319
+ powerup: text9("powerup").pipe(optional5, map34(optionToUndefined43)),
101320
+ parent: text9("parent").pipe(optional5, map34(optionToUndefined43)),
101321
+ ref: text9("ref").pipe(optional5, map34(optionToUndefined43)),
101322
+ text: text9("text").pipe(optional5, map34(optionToUndefined43)),
101323
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
99714
101324
  extraTag: text9("extra-tag").pipe(repeated5),
99715
101325
  notify: writeCommonOptions.notify,
99716
101326
  ensureDaemon: writeCommonOptions.ensureDaemon,
@@ -99928,8 +101538,8 @@ function rowHasTag(doc, tagId) {
99928
101538
  return Object.prototype.hasOwnProperty.call(tp, tagId);
99929
101539
  }
99930
101540
  var writePowerupRecordDeleteCommand = exports_Command.make("delete", {
99931
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
99932
- powerup: text9("powerup").pipe(optional5, map34(optionToUndefined34)),
101541
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
101542
+ powerup: text9("powerup").pipe(optional5, map34(optionToUndefined43)),
99933
101543
  rem: text9("rem"),
99934
101544
  validateMembership: boolean8("no-validate-membership").pipe(map34((v) => !v)),
99935
101545
  notify: writeCommonOptions.notify,
@@ -100078,7 +101688,7 @@ var writePowerupRecordDeleteCommand = exports_Command.make("delete", {
100078
101688
  }).pipe(catchAll2(writeFailure)));
100079
101689
 
100080
101690
  // src/commands/write/powerup/record/update.ts
100081
- var dispatchMode3 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined34));
101691
+ var dispatchMode3 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined43));
100082
101692
  function rowHasTag2(doc, tagId) {
100083
101693
  const tp = doc?.tp;
100084
101694
  if (!tp || typeof tp !== "object" || Array.isArray(tp))
@@ -100086,11 +101696,11 @@ function rowHasTag2(doc, tagId) {
100086
101696
  return Object.prototype.hasOwnProperty.call(tp, tagId);
100087
101697
  }
100088
101698
  var writePowerupRecordUpdateCommand = exports_Command.make("update", {
100089
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
100090
- powerup: text9("powerup").pipe(optional5, map34(optionToUndefined34)),
101699
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
101700
+ powerup: text9("powerup").pipe(optional5, map34(optionToUndefined43)),
100091
101701
  rem: text9("rem"),
100092
- text: text9("text").pipe(optional5, map34(optionToUndefined34)),
100093
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
101702
+ text: text9("text").pipe(optional5, map34(optionToUndefined43)),
101703
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
100094
101704
  validateMembership: boolean8("no-validate-membership").pipe(map34((v) => !v)),
100095
101705
  notify: writeCommonOptions.notify,
100096
101706
  ensureDaemon: writeCommonOptions.ensureDaemon,
@@ -100311,9 +101921,9 @@ var writePowerupRecordCommand = exports_Command.make("record", {}).pipe(exports_
100311
101921
  // src/commands/write/powerup/remove.ts
100312
101922
  var writePowerupRemoveCommand = exports_Command.make("remove", {
100313
101923
  rem: text9("rem"),
100314
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
100315
- powerup: text9("powerup").pipe(optional5, map34(optionToUndefined34)),
100316
- removeProperties: boolean8("remove-properties").pipe(optional5, map34(optionToUndefined34)),
101924
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
101925
+ powerup: text9("powerup").pipe(optional5, map34(optionToUndefined43)),
101926
+ removeProperties: boolean8("remove-properties").pipe(optional5, map34(optionToUndefined43)),
100317
101927
  notify: writeCommonOptions.notify,
100318
101928
  ensureDaemon: writeCommonOptions.ensureDaemon,
100319
101929
  wait: writeCommonOptions.wait,
@@ -100448,7 +102058,7 @@ var powerupCommand = exports_Command.make("powerup", {}).pipe(exports_Command.wi
100448
102058
  ]));
100449
102059
 
100450
102060
  // src/commands/read/query.ts
100451
- function optionToUndefined35(opt) {
102061
+ function optionToUndefined44(opt) {
100452
102062
  return isSome2(opt) ? opt.value : undefined;
100453
102063
  }
100454
102064
  function buildMarkdown3(items, total) {
@@ -100463,14 +102073,14 @@ function buildMarkdown3(items, total) {
100463
102073
  return lines3.join(`
100464
102074
  `);
100465
102075
  }
100466
- var payload = text9("payload").pipe(optional5, map34(optionToUndefined35));
100467
- var text15 = text9("text").pipe(optional5, map34(optionToUndefined35));
102076
+ var payload = text9("payload").pipe(optional5, map34(optionToUndefined44));
102077
+ var text15 = text9("text").pipe(optional5, map34(optionToUndefined44));
100468
102078
  var tag7 = text9("tag").pipe(repeated5);
100469
102079
  var limit5 = integer7("limit").pipe(withDefault5(20));
100470
102080
  var offset3 = integer7("offset").pipe(withDefault5(0));
100471
102081
  var snippetLength = integer7("snippet-length").pipe(withDefault5(200));
100472
- var sort2 = choice5("sort", ["rank", "updatedAt", "createdAt"]).pipe(optional5, map34(optionToUndefined35));
100473
- var sortDirection = choice5("sort-direction", ["asc", "desc"]).pipe(optional5, map34(optionToUndefined35));
102082
+ var sort2 = choice5("sort", ["rank", "updatedAt", "createdAt"]).pipe(optional5, map34(optionToUndefined44));
102083
+ var sortDirection = choice5("sort-direction", ["asc", "desc"]).pipe(optional5, map34(optionToUndefined44));
100474
102084
  var readQueryCommand = exports_Command.make("query", { payload, text: text15, tag: tag7, limit: limit5, offset: offset3, snippetLength, sort: sort2, sortDirection }, ({ payload: payload2, text: text16, tag: tag8, limit: limit6, offset: offset4, snippetLength: snippetLength2, sort: sort3, sortDirection: sortDirection2 }) => gen2(function* () {
100475
102085
  const cfg = yield* AppConfig;
100476
102086
  yield* failInRemoteMode({
@@ -100593,11 +102203,11 @@ var queueConflictsCommand = exports_Command.make("conflicts", {
100593
102203
  }).pipe(catchAll2(writeFailure)));
100594
102204
 
100595
102205
  // src/commands/queue/inspect.ts
100596
- function optionToUndefined36(opt) {
102206
+ function optionToUndefined45(opt) {
100597
102207
  return isSome2(opt) ? opt.value : undefined;
100598
102208
  }
100599
- var txn = text9("txn").pipe(optional5, map34(optionToUndefined36));
100600
- var op = text9("op").pipe(optional5, map34(optionToUndefined36));
102209
+ var txn = text9("txn").pipe(optional5, map34(optionToUndefined45));
102210
+ var op = text9("op").pipe(optional5, map34(optionToUndefined45));
100601
102211
  var queueInspectCommand = exports_Command.make("inspect", { txn, op }, ({ txn: txn2, op: op2 }) => gen2(function* () {
100602
102212
  const cfg = yield* AppConfig;
100603
102213
  const queue = yield* Queue;
@@ -100723,13 +102333,13 @@ var queueStatsCommand = exports_Command.make("stats", { includeConflicts: boolea
100723
102333
  }).pipe(catchAll2(writeFailure)));
100724
102334
 
100725
102335
  // src/commands/queue/wait.ts
100726
- function optionToUndefined37(opt) {
102336
+ function optionToUndefined46(opt) {
100727
102337
  return isSome2(opt) ? opt.value : undefined;
100728
102338
  }
100729
102339
  var queueWaitCommand = exports_Command.make("wait", {
100730
102340
  txn: text9("txn"),
100731
- timeoutMs: integer7("timeout-ms").pipe(optional5, map34(optionToUndefined37)),
100732
- pollMs: integer7("poll-ms").pipe(optional5, map34(optionToUndefined37))
102341
+ timeoutMs: integer7("timeout-ms").pipe(optional5, map34(optionToUndefined46)),
102342
+ pollMs: integer7("poll-ms").pipe(optional5, map34(optionToUndefined46))
100733
102343
  }, ({ txn: txn2, timeoutMs: timeoutMs4, pollMs: pollMs3 }) => gen2(function* () {
100734
102344
  const cfg = yield* AppConfig;
100735
102345
  const hostApi = yield* HostApiClient;
@@ -100762,12 +102372,12 @@ var queueCommand = exports_Command.make("queue", {}).pipe(exports_Command.withSu
100762
102372
  ]));
100763
102373
 
100764
102374
  // src/commands/read/by-reference.ts
100765
- function optionToUndefined38(opt) {
102375
+ function optionToUndefined47(opt) {
100766
102376
  return isSome2(opt) ? opt.value : undefined;
100767
102377
  }
100768
102378
  var reference = text9("reference").pipe(repeated5);
100769
- var timeRange = text9("time").pipe(optional5, map34(optionToUndefined38));
100770
- var maxDepth2 = integer7("max-depth").pipe(optional5, map34(optionToUndefined38));
102379
+ var timeRange = text9("time").pipe(optional5, map34(optionToUndefined47));
102380
+ var maxDepth2 = integer7("max-depth").pipe(optional5, map34(optionToUndefined47));
100771
102381
  var limit6 = integer7("limit").pipe(withDefault5(40));
100772
102382
  var offset4 = integer7("offset").pipe(withDefault5(0));
100773
102383
  var readByReferenceCommand = exports_Command.make("by-reference", { reference, timeRange, maxDepth: maxDepth2, limit: limit6, offset: offset4 }, ({ reference: reference2, timeRange: timeRange2, maxDepth: maxDepth3, limit: limit7, offset: offset5 }) => gen2(function* () {
@@ -100808,10 +102418,10 @@ var readConnectionsCommand = exports_Command.make("connections", { id: text9("id
100808
102418
  }).pipe(catchAll2(writeFailure)));
100809
102419
 
100810
102420
  // src/commands/read/inspect.ts
100811
- function optionToUndefined39(opt) {
102421
+ function optionToUndefined48(opt) {
100812
102422
  return isSome2(opt) ? opt.value : undefined;
100813
102423
  }
100814
- var maxReferenceDepth = integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined39));
102424
+ var maxReferenceDepth = integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined48));
100815
102425
  var readInspectCommand = exports_Command.make("inspect", {
100816
102426
  id: text9("id"),
100817
102427
  expandReferences: boolean8("expand-references"),
@@ -100843,15 +102453,15 @@ var readInspectCommand = exports_Command.make("inspect", {
100843
102453
  }).pipe(catchAll2(writeFailure)));
100844
102454
 
100845
102455
  // src/commands/read/outline.ts
100846
- function optionToUndefined40(opt) {
102456
+ function optionToUndefined49(opt) {
100847
102457
  return isSome2(opt) ? opt.value : undefined;
100848
102458
  }
100849
- var depth = integer7("depth").pipe(optional5, map34(optionToUndefined40));
100850
- var offset5 = integer7("offset").pipe(optional5, map34(optionToUndefined40));
100851
- var nodes = integer7("nodes").pipe(optional5, map34(optionToUndefined40));
100852
- var format9 = choice5("format", ["md", "json"]).pipe(optional5, map34(optionToUndefined40));
100853
- var id3 = text9("id").pipe(optional5, map34(optionToUndefined40));
100854
- var ref = text9("ref").pipe(optional5, map34(optionToUndefined40));
102459
+ var depth = integer7("depth").pipe(optional5, map34(optionToUndefined49));
102460
+ var offset5 = integer7("offset").pipe(optional5, map34(optionToUndefined49));
102461
+ var nodes = integer7("nodes").pipe(optional5, map34(optionToUndefined49));
102462
+ var format9 = choice5("format", ["md", "json"]).pipe(optional5, map34(optionToUndefined49));
102463
+ var id3 = text9("id").pipe(optional5, map34(optionToUndefined49));
102464
+ var ref = text9("ref").pipe(optional5, map34(optionToUndefined49));
100855
102465
  var readOutlineCommand = exports_Command.make("outline", {
100856
102466
  id: id3,
100857
102467
  ref,
@@ -100862,7 +102472,7 @@ var readOutlineCommand = exports_Command.make("outline", {
100862
102472
  excludeProperties: boolean8("exclude-properties"),
100863
102473
  includeEmpty: boolean8("include-empty"),
100864
102474
  expandReferences: boolean8("expand-references"),
100865
- maxReferenceDepth: integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined40)),
102475
+ maxReferenceDepth: integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined49)),
100866
102476
  detail: boolean8("detail")
100867
102477
  }, ({
100868
102478
  id: id4,
@@ -100922,12 +102532,12 @@ var readOutlineCommand = exports_Command.make("outline", {
100922
102532
  }).pipe(catchAll2(writeFailure)));
100923
102533
 
100924
102534
  // src/commands/read/page-id.ts
100925
- function optionToUndefined41(opt) {
102535
+ function optionToUndefined50(opt) {
100926
102536
  return isSome2(opt) ? opt.value : undefined;
100927
102537
  }
100928
- var ref2 = text9("ref").pipe(optional5, map34(optionToUndefined41));
102538
+ var ref2 = text9("ref").pipe(optional5, map34(optionToUndefined50));
100929
102539
  var id4 = text9("id").pipe(repeated5);
100930
- var maxHops = integer7("max-hops").pipe(optional5, map34(optionToUndefined41));
102540
+ var maxHops = integer7("max-hops").pipe(optional5, map34(optionToUndefined50));
100931
102541
  var readPageIdCommand = exports_Command.make("page-id", { ref: ref2, id: id4, maxHops, detail: boolean8("detail") }, ({ ref: ref3, id: id5, maxHops: maxHops2, detail }) => gen2(function* () {
100932
102542
  const cfg = yield* AppConfig;
100933
102543
  yield* failInRemoteMode({
@@ -100980,11 +102590,11 @@ var readPageIdCommand = exports_Command.make("page-id", { ref: ref2, id: id4, ma
100980
102590
  }).pipe(catchAll2(writeFailure)));
100981
102591
 
100982
102592
  // src/commands/read/references.ts
100983
- function optionToUndefined42(opt) {
102593
+ function optionToUndefined51(opt) {
100984
102594
  return isSome2(opt) ? opt.value : undefined;
100985
102595
  }
100986
- var maxDepth3 = integer7("max-depth").pipe(optional5, map34(optionToUndefined42));
100987
- var inboundMaxDepth = integer7("inbound-max-depth").pipe(optional5, map34(optionToUndefined42));
102596
+ var maxDepth3 = integer7("max-depth").pipe(optional5, map34(optionToUndefined51));
102597
+ var inboundMaxDepth = integer7("inbound-max-depth").pipe(optional5, map34(optionToUndefined51));
100988
102598
  var readReferencesCommand = exports_Command.make("references", {
100989
102599
  id: text9("id"),
100990
102600
  includeDescendants: boolean8("include-descendants"),
@@ -101020,10 +102630,10 @@ var readReferencesCommand = exports_Command.make("references", {
101020
102630
 
101021
102631
  // src/commands/read/resolve-ref.ts
101022
102632
  var ids3 = text9("ids").pipe(repeated5);
101023
- function optionToUndefined43(opt) {
102633
+ function optionToUndefined52(opt) {
101024
102634
  return isSome2(opt) ? opt.value : undefined;
101025
102635
  }
101026
- var maxReferenceDepth2 = integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined43));
102636
+ var maxReferenceDepth2 = integer7("max-reference-depth").pipe(optional5, map34(optionToUndefined52));
101027
102637
  var readResolveRefCommand = exports_Command.make("resolve-ref", {
101028
102638
  ids: ids3,
101029
102639
  expandReferences: boolean8("expand-references"),
@@ -101058,13 +102668,13 @@ function normalizeRemIdInput2(raw4) {
101058
102668
  }
101059
102669
  var tag8 = text9("tag").pipe(repeated5);
101060
102670
  var writeRemCreateCommand = exports_Command.make("create", {
101061
- parent: text9("parent").pipe(optional5, map34(optionToUndefined34)),
101062
- ref: text9("ref").pipe(optional5, map34(optionToUndefined34)),
101063
- text: text9("text").pipe(optional5, map34(optionToUndefined34)),
102671
+ parent: text9("parent").pipe(optional5, map34(optionToUndefined43)),
102672
+ ref: text9("ref").pipe(optional5, map34(optionToUndefined43)),
102673
+ text: text9("text").pipe(optional5, map34(optionToUndefined43)),
101064
102674
  isDocument: boolean8("is-document"),
101065
102675
  tag: tag8,
101066
- position: integer7("position").pipe(optional5, map34(optionToUndefined34)),
101067
- clientTempId: text9("client-temp-id").pipe(optional5, map34(optionToUndefined34)),
102676
+ position: integer7("position").pipe(optional5, map34(optionToUndefined43)),
102677
+ clientTempId: text9("client-temp-id").pipe(optional5, map34(optionToUndefined43)),
101068
102678
  forceText: boolean8("force-text"),
101069
102679
  notify: writeCommonOptions.notify,
101070
102680
  ensureDaemon: writeCommonOptions.ensureDaemon,
@@ -101140,7 +102750,7 @@ var writeRemCreateCommand = exports_Command.make("create", {
101140
102750
  const tags2 = Array.isArray(tag9) ? tag9.map(normalizeRemIdInput2).filter(Boolean) : [];
101141
102751
  const remClientTempId = clientTempId ? String(clientTempId).trim() : makeTempId();
101142
102752
  const textValue = text16 !== undefined ? trimBoundaryBlankLines(text16) : undefined;
101143
- if (textValue && !forceText2 && looksLikeStructuredMarkdown(textValue)) {
102753
+ if (textValue && !forceText2 && looksLikeStructuredMarkdown2(textValue)) {
101144
102754
  return yield* fail8(new CliError({
101145
102755
  code: "INVALID_ARGS",
101146
102756
  message: "Input passed to --text looks like structured Markdown. Use rem children append --rem <parentRemId> --markdown ... instead, or pass --force-text to keep it literal.",
@@ -101247,16 +102857,17 @@ function buildActionEnvelope(params3) {
101247
102857
  return gen2(function* () {
101248
102858
  const payloadSvc = yield* Payload;
101249
102859
  const metaValue = params3.metaSpec ? yield* payloadSvc.readJson(params3.metaSpec) : undefined;
102860
+ const input = params3.input ?? {
102861
+ rem_id: params3.remId,
102862
+ ...params3.markdown !== undefined ? { markdown: params3.markdown } : {}
102863
+ };
101250
102864
  return {
101251
102865
  version: 1,
101252
102866
  kind: "actions",
101253
102867
  actions: [
101254
102868
  {
101255
102869
  action: params3.action,
101256
- input: {
101257
- rem_id: params3.remId,
101258
- ...params3.markdown !== undefined ? { markdown: params3.markdown } : {}
101259
- }
102870
+ input
101260
102871
  }
101261
102872
  ],
101262
102873
  ...params3.priority !== undefined ? { priority: params3.priority } : {},
@@ -101268,6 +102879,50 @@ function buildActionEnvelope(params3) {
101268
102879
  };
101269
102880
  });
101270
102881
  }
102882
+ function resolveCurrentSelectionRemId(params3) {
102883
+ return gen2(function* () {
102884
+ const resolved = yield* resolveCurrentSelectionRemIds(params3);
102885
+ if (resolved.rem_ids.length !== 1) {
102886
+ return yield* fail8(new CliError({
102887
+ code: "INVALID_ARGS",
102888
+ message: "Current selection must resolve to exactly one selected Rem",
102889
+ exitCode: 2,
102890
+ details: { total_count: resolved.rem_ids.length, selection: resolved.selection }
102891
+ }));
102892
+ }
102893
+ return {
102894
+ source: "selection",
102895
+ rem_id: resolved.rem_ids[0],
102896
+ selection: resolved.selection
102897
+ };
102898
+ });
102899
+ }
102900
+ function resolveCurrentSelectionRemIds(params3) {
102901
+ return gen2(function* () {
102902
+ const cfg = yield* AppConfig;
102903
+ const hostApi = yield* HostApiClient;
102904
+ const data = cfg.apiBaseUrl ? yield* hostApi.selectionCurrent({ baseUrl: cfg.apiBaseUrl, stateFile: params3.stateFile, staleMs: params3.staleMs }) : yield* collectSelectionCurrentUseCase({ stateFile: params3.stateFile, staleMs: params3.staleMs });
102905
+ const totalCountRaw = Number(data?.total_count ?? 0);
102906
+ const totalCount = Number.isFinite(totalCountRaw) && totalCountRaw >= 0 ? Math.floor(totalCountRaw) : 0;
102907
+ const truncated = data?.truncated === true;
102908
+ const listedIds = Array.isArray(data?.ids) ? data.ids.filter((value8) => typeof value8 === "string").map((value8) => value8.trim()).filter((value8) => value8.length > 0) : [];
102909
+ const currentId = typeof data?.current?.id === "string" && data.current.id.trim() ? data.current.id.trim() : "";
102910
+ const ids4 = listedIds.length > 0 ? listedIds : currentId ? [currentId] : [];
102911
+ if (truncated || totalCount < 1 || ids4.length === 0 || ids4.length !== totalCount) {
102912
+ return yield* fail8(new CliError({
102913
+ code: "INVALID_ARGS",
102914
+ message: "Current selection must resolve to one or more selected Rems",
102915
+ exitCode: 2,
102916
+ details: { total_count: totalCount, truncated, ids: ids4, selection: data }
102917
+ }));
102918
+ }
102919
+ return {
102920
+ source: "selection",
102921
+ rem_ids: ids4,
102922
+ selection: data
102923
+ };
102924
+ });
102925
+ }
101271
102926
  function readMarkdownArg(inputSpec) {
101272
102927
  return gen2(function* () {
101273
102928
  const raw4 = yield* readMarkdownTextFromInputSpec(inputSpec);
@@ -101320,6 +102975,39 @@ function submitActionEnvelope(params3) {
101320
102975
  });
101321
102976
  });
101322
102977
  }
102978
+ function loadTxnDetail(params3) {
102979
+ return gen2(function* () {
102980
+ const cfg = yield* AppConfig;
102981
+ const hostApi = yield* HostApiClient;
102982
+ const queue = yield* Queue;
102983
+ return cfg.apiBaseUrl ? yield* hostApi.queueTxn({ baseUrl: cfg.apiBaseUrl, txnId: params3.txnId }) : yield* queue.inspect({ dbPath: cfg.storeDb, txnId: params3.txnId });
102984
+ });
102985
+ }
102986
+ function parseResultJson(raw4) {
102987
+ const resultJson = raw4?.result_json;
102988
+ if (typeof resultJson === "string" && resultJson.trim()) {
102989
+ try {
102990
+ return JSON.parse(resultJson);
102991
+ } catch {}
102992
+ }
102993
+ return null;
102994
+ }
102995
+ function extractReplaceBackupSummary(txnDetail) {
102996
+ const ops = Array.isArray(txnDetail?.ops) ? txnDetail.ops : [];
102997
+ const replaceOp = ops.find((op2) => ["replace_children_with_markdown", "replace_selection_with_markdown"].includes(String(op2?.type ?? "").trim()));
102998
+ if (!replaceOp)
102999
+ return;
103000
+ const result = parseResultJson(replaceOp.result);
103001
+ if (!result || typeof result !== "object")
103002
+ return;
103003
+ return {
103004
+ policy: typeof result.backup_policy === "string" && result.backup_policy.trim() ? result.backup_policy.trim() : "none",
103005
+ deleted: result.backup_deleted !== false,
103006
+ rem_id: typeof result.backup_rem_id === "string" && result.backup_rem_id.trim() ? result.backup_rem_id.trim() : null,
103007
+ ...result.backup_hidden === true ? { hidden: true } : {},
103008
+ ...typeof result.backup_cleanup_state === "string" && result.backup_cleanup_state.trim() ? { cleanup_state: result.backup_cleanup_state.trim() } : {}
103009
+ };
103010
+ }
101323
103011
 
101324
103012
  // src/commands/write/rem/children/append.ts
101325
103013
  var writeRemChildrenAppendCommand = exports_Command.make("append", {
@@ -101484,9 +103172,17 @@ var writeRemChildrenPrependCommand = exports_Command.make("prepend", {
101484
103172
  }).pipe(catchAll2(writeFailure)));
101485
103173
 
101486
103174
  // src/commands/write/rem/children/replace.ts
103175
+ function optionToUndefined53(opt) {
103176
+ return isSome2(opt) ? opt.value : undefined;
103177
+ }
101487
103178
  var writeRemChildrenReplaceCommand = exports_Command.make("replace", {
101488
- rem: text9("rem"),
103179
+ rem: text9("rem").pipe(optional5, map34(optionToUndefined53)),
103180
+ selection: boolean8("selection"),
103181
+ stateFile: text9("state-file").pipe(optional5, map34(optionToUndefined53)),
103182
+ staleMs: integer7("stale-ms").pipe(optional5, map34(optionToUndefined53)),
101489
103183
  markdown: text9("markdown"),
103184
+ backup: choice5("backup", ["none", "visible"]).pipe(withDefault5("none")),
103185
+ assert: choice5("assert", ["single-root", "preserve-anchor", "no-literal-bullet"]).pipe(repeated5),
101490
103186
  notify: writeCommonOptions.notify,
101491
103187
  ensureDaemon: writeCommonOptions.ensureDaemon,
101492
103188
  wait: writeCommonOptions.wait,
@@ -101497,14 +103193,50 @@ var writeRemChildrenReplaceCommand = exports_Command.make("replace", {
101497
103193
  clientId: writeCommonOptions.clientId,
101498
103194
  idempotencyKey: writeCommonOptions.idempotencyKey,
101499
103195
  meta: writeCommonOptions.meta
101500
- }, ({ rem, markdown: markdown2, notify: notify3, ensureDaemon: ensureDaemon5, wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3, dryRun, priority: priority3, clientId: clientId3, idempotencyKey: idempotencyKey3, meta }) => gen2(function* () {
103196
+ }, ({
103197
+ rem,
103198
+ selection,
103199
+ stateFile: stateFile24,
103200
+ staleMs: staleMs11,
103201
+ markdown: markdown2,
103202
+ backup,
103203
+ assert: assert2,
103204
+ notify: notify3,
103205
+ ensureDaemon: ensureDaemon5,
103206
+ wait: wait3,
103207
+ timeoutMs: timeoutMs4,
103208
+ pollMs: pollMs3,
103209
+ dryRun,
103210
+ priority: priority3,
103211
+ clientId: clientId3,
103212
+ idempotencyKey: idempotencyKey3,
103213
+ meta
103214
+ }) => gen2(function* () {
101501
103215
  yield* ensureWaitArgs({ wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3, dryRun });
101502
- const remId = normalizeRemIdInput3(rem);
103216
+ const hasRem = typeof rem === "string" && rem.trim().length > 0;
103217
+ const targetCount = Number(hasRem) + Number(selection === true);
103218
+ if (targetCount !== 1) {
103219
+ return yield* fail8(new CliError({
103220
+ code: "INVALID_ARGS",
103221
+ message: "Provide exactly one target via --rem or --selection",
103222
+ exitCode: 2
103223
+ }));
103224
+ }
103225
+ const target2 = selection ? yield* resolveCurrentSelectionRemId({ stateFile: stateFile24, staleMs: staleMs11 }) : {
103226
+ source: "rem",
103227
+ rem_id: normalizeRemIdInput3(String(rem))
103228
+ };
103229
+ const remId = target2.rem_id;
101503
103230
  const markdownValue = yield* readMarkdownArg(markdown2);
101504
103231
  const body = yield* buildActionEnvelope({
101505
103232
  action: "rem.children.replace",
101506
103233
  remId,
101507
- markdown: markdownValue,
103234
+ input: {
103235
+ rem_id: remId,
103236
+ markdown: markdownValue,
103237
+ backup,
103238
+ ...assert2.length > 0 ? { assertions: assert2 } : {}
103239
+ },
101508
103240
  priority: priority3,
101509
103241
  clientId: clientId3,
101510
103242
  idempotencyKey: idempotencyKey3,
@@ -101515,24 +103247,32 @@ var writeRemChildrenReplaceCommand = exports_Command.make("replace", {
101515
103247
  if (dryRun) {
101516
103248
  const compiled = yield* dryRunEnvelope(body);
101517
103249
  yield* writeSuccess({
101518
- data: { dry_run: true, ...compiled },
103250
+ data: { dry_run: true, target: { source: target2.source, rem_id: remId }, ...compiled },
101519
103251
  md: `- dry_run: true
101520
103252
  - action: rem.children.replace
101521
103253
  - rem_id: ${remId}
103254
+ - target: ${target2.source}
101522
103255
  `
101523
103256
  });
101524
103257
  return;
101525
103258
  }
101526
103259
  const data = yield* submitActionEnvelope({ body, wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3 });
103260
+ const backupSummary = wait3 && data.status === "succeeded" && typeof data.txn_id === "string" ? extractReplaceBackupSummary(yield* loadTxnDetail({ txnId: data.txn_id })) : undefined;
101527
103261
  yield* writeSuccess({
101528
- data,
103262
+ data: backupSummary ? { ...data, backup: backupSummary } : data,
101529
103263
  ids: [data.txn_id, ...Array.isArray(data.op_ids) ? data.op_ids : []],
101530
103264
  md: [
101531
103265
  `- txn_id: ${data.txn_id}`,
101532
103266
  `- op_ids: ${Array.isArray(data.op_ids) ? data.op_ids.length : ""}`,
101533
103267
  `- notified: ${data.notified}`,
101534
103268
  `- sent: ${data.sent ?? ""}`,
101535
- ...data.status ? [`- status: ${data.status}`, `- elapsed_ms: ${data.elapsed_ms ?? ""}`] : []
103269
+ ...data.status ? [`- status: ${data.status}`, `- elapsed_ms: ${data.elapsed_ms ?? ""}`] : [],
103270
+ ...backupSummary ? [
103271
+ `- backup_policy: ${backupSummary.policy}`,
103272
+ `- backup_deleted: ${backupSummary.deleted ? "true" : "false"}`,
103273
+ ...backupSummary.hidden ? ["- backup_hidden: true"] : [],
103274
+ ...backupSummary.cleanup_state ? [`- backup_cleanup_state: ${backupSummary.cleanup_state}`] : []
103275
+ ] : []
101536
103276
  ].join(`
101537
103277
  `)
101538
103278
  });
@@ -101547,8 +103287,12 @@ var writeRemChildrenCommand = exports_Command.make("children", {}).pipe(exports_
101547
103287
  ]));
101548
103288
 
101549
103289
  // src/commands/write/rem/delete.ts
103290
+ function optionToUndefined54(opt) {
103291
+ return isSome2(opt) ? opt.value : undefined;
103292
+ }
101550
103293
  var writeRemDeleteCommand = exports_Command.make("delete", {
101551
103294
  rem: text9("rem"),
103295
+ maxDeleteSubtreeNodes: integer7("max-delete-subtree-nodes").pipe(optional5, map34(optionToUndefined54)),
101552
103296
  notify: writeCommonOptions.notify,
101553
103297
  ensureDaemon: writeCommonOptions.ensureDaemon,
101554
103298
  wait: writeCommonOptions.wait,
@@ -101559,7 +103303,27 @@ var writeRemDeleteCommand = exports_Command.make("delete", {
101559
103303
  clientId: writeCommonOptions.clientId,
101560
103304
  idempotencyKey: writeCommonOptions.idempotencyKey,
101561
103305
  meta: writeCommonOptions.meta
101562
- }, ({ rem, notify: notify3, ensureDaemon: ensureDaemon5, wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3, dryRun, priority: priority3, clientId: clientId3, idempotencyKey: idempotencyKey3, meta }) => gen2(function* () {
103306
+ }, ({
103307
+ rem,
103308
+ maxDeleteSubtreeNodes,
103309
+ notify: notify3,
103310
+ ensureDaemon: ensureDaemon5,
103311
+ wait: wait3,
103312
+ timeoutMs: timeoutMs4,
103313
+ pollMs: pollMs3,
103314
+ dryRun,
103315
+ priority: priority3,
103316
+ clientId: clientId3,
103317
+ idempotencyKey: idempotencyKey3,
103318
+ meta
103319
+ }) => gen2(function* () {
103320
+ if (maxDeleteSubtreeNodes !== undefined && maxDeleteSubtreeNodes <= 0) {
103321
+ return yield* fail8(new CliError({
103322
+ code: "INVALID_ARGS",
103323
+ message: "--max-delete-subtree-nodes must be a positive integer",
103324
+ exitCode: 2
103325
+ }));
103326
+ }
101563
103327
  if (!wait3 && (timeoutMs4 !== undefined || pollMs3 !== undefined)) {
101564
103328
  return yield* fail8(new CliError({
101565
103329
  code: "INVALID_ARGS",
@@ -101576,7 +103340,13 @@ var writeRemDeleteCommand = exports_Command.make("delete", {
101576
103340
  }
101577
103341
  const payloadSvc = yield* Payload;
101578
103342
  const op2 = yield* try_3({
101579
- try: () => normalizeOp({ type: "delete_rem", payload: { remId: rem } }, payloadSvc.normalizeKeys),
103343
+ try: () => normalizeOp({
103344
+ type: "delete_rem",
103345
+ payload: {
103346
+ remId: rem,
103347
+ ...maxDeleteSubtreeNodes !== undefined ? { maxDeleteSubtreeNodes } : {}
103348
+ }
103349
+ }, payloadSvc.normalizeKeys),
101580
103350
  catch: (e) => isCliError(e) ? e : new CliError({
101581
103351
  code: "INVALID_PAYLOAD",
101582
103352
  message: "Failed to generate op",
@@ -101630,9 +103400,9 @@ function normalizeRemIdInput4(raw4) {
101630
103400
  }
101631
103401
  var writeRemMoveCommand = exports_Command.make("move", {
101632
103402
  rem: text9("rem"),
101633
- parent: text9("parent").pipe(optional5, map34(optionToUndefined34)),
101634
- ref: text9("ref").pipe(optional5, map34(optionToUndefined34)),
101635
- position: integer7("position").pipe(optional5, map34(optionToUndefined34)),
103403
+ parent: text9("parent").pipe(optional5, map34(optionToUndefined43)),
103404
+ ref: text9("ref").pipe(optional5, map34(optionToUndefined43)),
103405
+ position: integer7("position").pipe(optional5, map34(optionToUndefined43)),
101636
103406
  notify: writeCommonOptions.notify,
101637
103407
  ensureDaemon: writeCommonOptions.ensureDaemon,
101638
103408
  wait: writeCommonOptions.wait,
@@ -101748,6 +103518,117 @@ var writeRemMoveCommand = exports_Command.make("move", {
101748
103518
  });
101749
103519
  }).pipe(catchAll2(writeFailure)));
101750
103520
 
103521
+ // src/commands/write/rem/replace.ts
103522
+ var writeRemReplaceCommand = exports_Command.make("replace", {
103523
+ rem: text9("rem").pipe(repeated5),
103524
+ selection: boolean8("selection"),
103525
+ stateFile: text9("state-file").pipe(optional5, map34(optionToUndefined43)),
103526
+ staleMs: integer7("stale-ms").pipe(optional5, map34(optionToUndefined43)),
103527
+ surface: choice5("surface", ["children", "self"]),
103528
+ markdown: text9("markdown"),
103529
+ assert: choice5("assert", ["single-root", "preserve-anchor", "no-literal-bullet"]).pipe(repeated5),
103530
+ notify: writeCommonOptions.notify,
103531
+ ensureDaemon: writeCommonOptions.ensureDaemon,
103532
+ wait: writeCommonOptions.wait,
103533
+ timeoutMs: writeCommonOptions.timeoutMs,
103534
+ pollMs: writeCommonOptions.pollMs,
103535
+ dryRun: writeCommonOptions.dryRun,
103536
+ priority: writeCommonOptions.priority,
103537
+ clientId: writeCommonOptions.clientId,
103538
+ idempotencyKey: writeCommonOptions.idempotencyKey,
103539
+ meta: writeCommonOptions.meta
103540
+ }, ({
103541
+ rem,
103542
+ selection,
103543
+ stateFile: stateFile24,
103544
+ staleMs: staleMs11,
103545
+ surface,
103546
+ markdown: markdown2,
103547
+ assert: assert2,
103548
+ notify: notify3,
103549
+ ensureDaemon: ensureDaemon5,
103550
+ wait: wait3,
103551
+ timeoutMs: timeoutMs4,
103552
+ pollMs: pollMs3,
103553
+ dryRun,
103554
+ priority: priority3,
103555
+ clientId: clientId3,
103556
+ idempotencyKey: idempotencyKey3,
103557
+ meta
103558
+ }) => gen2(function* () {
103559
+ yield* ensureWaitArgs({ wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3, dryRun });
103560
+ const explicitIds = rem.map(normalizeRemIdInput3).filter(Boolean);
103561
+ if (explicitIds.length === 0 && !selection || explicitIds.length > 0 && selection) {
103562
+ return yield* fail8(new CliError({
103563
+ code: "INVALID_ARGS",
103564
+ message: "Provide exactly one target selector via repeated --rem or --selection",
103565
+ exitCode: 2
103566
+ }));
103567
+ }
103568
+ const target2 = explicitIds.length > 0 ? {
103569
+ source: "explicit",
103570
+ rem_ids: Array.from(new Set(explicitIds))
103571
+ } : yield* resolveCurrentSelectionRemIds({ stateFile: stateFile24, staleMs: staleMs11 });
103572
+ if (surface === "children" && target2.rem_ids.length !== 1) {
103573
+ return yield* fail8(new CliError({
103574
+ code: "INVALID_ARGS",
103575
+ message: "rem replace --surface children requires exactly one target Rem",
103576
+ exitCode: 2,
103577
+ details: { surface, target: target2 }
103578
+ }));
103579
+ }
103580
+ const assertions = assert2;
103581
+ if (surface === "self" && assertions.includes("preserve-anchor")) {
103582
+ return yield* fail8(new CliError({
103583
+ code: "INVALID_ARGS",
103584
+ message: "rem replace --surface=self does not support --assert preserve-anchor",
103585
+ exitCode: 2
103586
+ }));
103587
+ }
103588
+ const markdownValue = yield* readMarkdownArg(markdown2);
103589
+ const body = yield* buildActionEnvelope({
103590
+ action: "rem.replace",
103591
+ remId: target2.rem_ids[0] ?? "",
103592
+ input: {
103593
+ surface,
103594
+ rem_ids: target2.rem_ids,
103595
+ markdown: markdownValue,
103596
+ ...assertions.length > 0 ? { assertions } : {}
103597
+ },
103598
+ priority: priority3,
103599
+ clientId: clientId3,
103600
+ idempotencyKey: idempotencyKey3,
103601
+ metaSpec: meta,
103602
+ notify: notify3,
103603
+ ensureDaemon: ensureDaemon5
103604
+ });
103605
+ if (dryRun) {
103606
+ const compiled = yield* dryRunEnvelope(body);
103607
+ yield* writeSuccess({
103608
+ data: { dry_run: true, target: { source: target2.source, rem_ids: target2.rem_ids }, ...compiled },
103609
+ md: `- dry_run: true
103610
+ - action: rem.replace
103611
+ - surface: ${surface}
103612
+ - targets: ${target2.rem_ids.length}
103613
+ `
103614
+ });
103615
+ return;
103616
+ }
103617
+ const data = yield* submitActionEnvelope({ body, wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3 });
103618
+ yield* writeSuccess({
103619
+ data,
103620
+ ids: [data.txn_id, ...Array.isArray(data.op_ids) ? data.op_ids : []],
103621
+ md: [
103622
+ `- txn_id: ${data.txn_id}`,
103623
+ `- op_ids: ${Array.isArray(data.op_ids) ? data.op_ids.length : ""}`,
103624
+ `- notified: ${data.notified}`,
103625
+ `- sent: ${data.sent ?? ""}`,
103626
+ ...data.status ? [`- status: ${data.status}`, `- elapsed_ms: ${data.elapsed_ms ?? ""}`] : []
103627
+ ].join(`
103628
+ `)
103629
+ });
103630
+ }).pipe(catchAll2(writeFailure)));
103631
+
101751
103632
  // src/commands/write/tag/index.ts
101752
103633
  function normalizeRemIdInput5(raw4) {
101753
103634
  const trimmed2 = raw4.trim();
@@ -101835,7 +103716,7 @@ var writeTagAddCommand = exports_Command.make("add", {
101835
103716
  var writeTagRemoveCommand = exports_Command.make("remove", {
101836
103717
  rem: text9("rem"),
101837
103718
  tag: text9("tag"),
101838
- removeProperties: boolean8("remove-properties").pipe(optional5, map34(optionToUndefined34)),
103719
+ removeProperties: boolean8("remove-properties").pipe(optional5, map34(optionToUndefined43)),
101839
103720
  notify: writeCommonOptions.notify,
101840
103721
  ensureDaemon: writeCommonOptions.ensureDaemon,
101841
103722
  wait: writeCommonOptions.wait,
@@ -101939,93 +103820,93 @@ function normalizeRemIdInput6(raw4) {
101939
103820
  return link3.remId;
101940
103821
  return trimmed2;
101941
103822
  }
101942
- function makeWriteRemTextCommand(name) {
101943
- return exports_Command.make(name, {
101944
- rem: text9("rem"),
101945
- text: text9("text"),
101946
- notify: writeCommonOptions.notify,
101947
- ensureDaemon: writeCommonOptions.ensureDaemon,
101948
- wait: writeCommonOptions.wait,
101949
- timeoutMs: writeCommonOptions.timeoutMs,
101950
- pollMs: writeCommonOptions.pollMs,
101951
- dryRun: writeCommonOptions.dryRun,
101952
- priority: writeCommonOptions.priority,
101953
- clientId: writeCommonOptions.clientId,
101954
- idempotencyKey: writeCommonOptions.idempotencyKey,
101955
- meta: writeCommonOptions.meta
101956
- }, ({ rem, text: text16, notify: notify3, ensureDaemon: ensureDaemon5, wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3, dryRun, priority: priority3, clientId: clientId3, idempotencyKey: idempotencyKey3, meta }) => gen2(function* () {
101957
- if (!wait3 && (timeoutMs4 !== undefined || pollMs3 !== undefined)) {
101958
- return yield* fail8(new CliError({
101959
- code: "INVALID_ARGS",
101960
- message: "Use --wait to enable --timeout-ms/--poll-ms",
101961
- exitCode: 2
101962
- }));
101963
- }
101964
- if (dryRun && wait3) {
101965
- return yield* fail8(new CliError({
101966
- code: "INVALID_ARGS",
101967
- message: "--wait is not compatible with --dry-run",
101968
- exitCode: 2
101969
- }));
101970
- }
101971
- const payloadSvc = yield* Payload;
101972
- const remId = normalizeRemIdInput6(rem);
101973
- const textValue = trimBoundaryBlankLines(text16);
101974
- const op2 = yield* try_3({
101975
- try: () => normalizeOp({ type: "update_text", payload: { remId, text: textValue } }, payloadSvc.normalizeKeys),
101976
- catch: (e) => isCliError(e) ? e : new CliError({
101977
- code: "INVALID_PAYLOAD",
101978
- message: "Failed to generate op",
101979
- exitCode: 2,
101980
- details: { error: String(e?.message || e) }
101981
- })
101982
- });
101983
- const metaValue = meta ? yield* payloadSvc.readJson(meta) : undefined;
101984
- if (dryRun) {
101985
- yield* writeSuccess({
101986
- data: { dry_run: true, ops: [op2], meta: metaValue ? payloadSvc.normalizeKeys(metaValue) : undefined },
101987
- md: `- dry_run: true
103823
+ var writeRemSetTextCommand = exports_Command.make("set-text", {
103824
+ rem: text9("rem"),
103825
+ text: text9("text"),
103826
+ notify: writeCommonOptions.notify,
103827
+ ensureDaemon: writeCommonOptions.ensureDaemon,
103828
+ wait: writeCommonOptions.wait,
103829
+ timeoutMs: writeCommonOptions.timeoutMs,
103830
+ pollMs: writeCommonOptions.pollMs,
103831
+ dryRun: writeCommonOptions.dryRun,
103832
+ priority: writeCommonOptions.priority,
103833
+ clientId: writeCommonOptions.clientId,
103834
+ idempotencyKey: writeCommonOptions.idempotencyKey,
103835
+ meta: writeCommonOptions.meta
103836
+ }, ({ rem, text: text16, notify: notify3, ensureDaemon: ensureDaemon5, wait: wait3, timeoutMs: timeoutMs4, pollMs: pollMs3, dryRun, priority: priority3, clientId: clientId3, idempotencyKey: idempotencyKey3, meta }) => gen2(function* () {
103837
+ if (!wait3 && (timeoutMs4 !== undefined || pollMs3 !== undefined)) {
103838
+ return yield* fail8(new CliError({
103839
+ code: "INVALID_ARGS",
103840
+ message: "Use --wait to enable --timeout-ms/--poll-ms",
103841
+ exitCode: 2
103842
+ }));
103843
+ }
103844
+ if (dryRun && wait3) {
103845
+ return yield* fail8(new CliError({
103846
+ code: "INVALID_ARGS",
103847
+ message: "--wait is not compatible with --dry-run",
103848
+ exitCode: 2
103849
+ }));
103850
+ }
103851
+ yield* failInRemoteMode({
103852
+ command: "rem set-text",
103853
+ reason: "this command enqueues writes to the local queue/store without a HostApiClient branch"
103854
+ });
103855
+ const payloadSvc = yield* Payload;
103856
+ const remId = normalizeRemIdInput6(rem);
103857
+ const textValue = trimBoundaryBlankLines(text16);
103858
+ const op2 = yield* try_3({
103859
+ try: () => normalizeOp({ type: "update_text", payload: { remId, text: textValue } }, payloadSvc.normalizeKeys),
103860
+ catch: (e) => isCliError(e) ? e : new CliError({
103861
+ code: "INVALID_PAYLOAD",
103862
+ message: "Failed to generate op",
103863
+ exitCode: 2,
103864
+ details: { error: String(e?.message || e) }
103865
+ })
103866
+ });
103867
+ const metaValue = meta ? yield* payloadSvc.readJson(meta) : undefined;
103868
+ if (dryRun) {
103869
+ yield* writeSuccess({
103870
+ data: { dry_run: true, ops: [op2], meta: metaValue ? payloadSvc.normalizeKeys(metaValue) : undefined },
103871
+ md: `- dry_run: true
101988
103872
  - op: update_text
101989
103873
  - rem_id: ${remId}
101990
103874
  `
101991
- });
101992
- return;
101993
- }
101994
- const data = yield* enqueueOps({
101995
- ops: [op2],
101996
- priority: priority3,
101997
- clientId: clientId3,
101998
- idempotencyKey: idempotencyKey3,
101999
- meta: metaValue,
102000
- notify: notify3,
102001
- ensureDaemon: ensureDaemon5
102002
103875
  });
102003
- const waited = wait3 ? yield* waitForTxn({ txnId: data.txn_id, timeoutMs: timeoutMs4, pollMs: pollMs3 }) : null;
102004
- const out = waited ? { ...data, ...waited } : data;
102005
- yield* writeSuccess({
102006
- data: out,
102007
- ids: [data.txn_id, ...data.op_ids],
102008
- md: [
102009
- `- txn_id: ${data.txn_id}`,
102010
- `- op_ids: ${data.op_ids.length}`,
102011
- `- notified: ${data.notified}`,
102012
- `- sent: ${data.sent ?? ""}`,
102013
- ...waited ? [`- status: ${waited.status}`, `- elapsed_ms: ${waited.elapsed_ms}`] : []
102014
- ].join(`
103876
+ return;
103877
+ }
103878
+ const data = yield* enqueueOps({
103879
+ ops: [op2],
103880
+ priority: priority3,
103881
+ clientId: clientId3,
103882
+ idempotencyKey: idempotencyKey3,
103883
+ meta: metaValue,
103884
+ notify: notify3,
103885
+ ensureDaemon: ensureDaemon5
103886
+ });
103887
+ const waited = wait3 ? yield* waitForTxn({ txnId: data.txn_id, timeoutMs: timeoutMs4, pollMs: pollMs3 }) : null;
103888
+ const out = waited ? { ...data, ...waited } : data;
103889
+ yield* writeSuccess({
103890
+ data: out,
103891
+ ids: [data.txn_id, ...data.op_ids],
103892
+ md: [
103893
+ `- txn_id: ${data.txn_id}`,
103894
+ `- op_ids: ${data.op_ids.length}`,
103895
+ `- notified: ${data.notified}`,
103896
+ `- sent: ${data.sent ?? ""}`,
103897
+ ...waited ? [`- status: ${waited.status}`, `- elapsed_ms: ${waited.elapsed_ms}`] : []
103898
+ ].join(`
102015
103899
  `)
102016
- });
102017
- }).pipe(catchAll2(writeFailure)));
102018
- }
102019
- var writeRemSetTextCommand = makeWriteRemTextCommand("set-text");
102020
- var writeRemTextCommand = makeWriteRemTextCommand("text");
103900
+ });
103901
+ }).pipe(catchAll2(writeFailure)));
102021
103902
 
102022
103903
  // src/commands/rem/index.ts
102023
103904
  var remCommand = exports_Command.make("rem", {}).pipe(exports_Command.withSubcommands([
103905
+ writeRemReplaceCommand,
102024
103906
  writeRemChildrenCommand,
102025
103907
  writeRemCreateCommand,
102026
103908
  writeRemMoveCommand,
102027
103909
  writeRemSetTextCommand,
102028
- writeRemTextCommand,
102029
103910
  writeRemTagCommand,
102030
103911
  writeRemDeleteCommand,
102031
103912
  readInspectCommand,
@@ -102043,7 +103924,7 @@ function resolveReplaceTarget(params3) {
102043
103924
  const _cfg = yield* AppConfig;
102044
103925
  yield* failInRemoteMode({
102045
103926
  command: "replace target resolution",
102046
- reason: "replace commands still depend on local selection/ref resolution semantics"
103927
+ reason: "replace markdown is an advanced/local-only block replace path that still depends on local selection/ref resolution semantics"
102047
103928
  });
102048
103929
  const refs = yield* RefResolver;
102049
103930
  const hasSelection = params3.selection === true;
@@ -102155,18 +104036,18 @@ function expandTargetIds(params3) {
102155
104036
  }
102156
104037
 
102157
104038
  // src/commands/write/replace/block.ts
102158
- function optionToUndefined44(opt) {
104039
+ function optionToUndefined55(opt) {
102159
104040
  return isSome2(opt) ? opt.value : undefined;
102160
104041
  }
102161
104042
  function readOptionalText4(name) {
102162
- return text9(name).pipe(optional5, map34(optionToUndefined44));
104043
+ return text9(name).pipe(optional5, map34(optionToUndefined55));
102163
104044
  }
102164
104045
  var selection = boolean8("selection");
102165
- var stateFile18 = readOptionalText4("state-file");
102166
- var staleMs11 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined44));
104046
+ var stateFile24 = readOptionalText4("state-file");
104047
+ var staleMs11 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined55));
102167
104048
  var ref3 = readOptionalText4("ref");
102168
104049
  var ids4 = text9("id").pipe(repeated5);
102169
- var scope5 = choice5("scope", ["roots", "subtree"]).pipe(optional5, map34(optionToUndefined44));
104050
+ var scope5 = choice5("scope", ["roots", "subtree"]).pipe(optional5, map34(optionToUndefined55));
102170
104051
  var requireComplete = boolean8("require-complete");
102171
104052
  var maxDepth4 = integer7("max-depth").pipe(withDefault5(10));
102172
104053
  var maxNodes2 = integer7("max-nodes").pipe(withDefault5(1000));
@@ -102174,19 +104055,19 @@ var allowDiscontiguous = boolean8("allow-discontiguous");
102174
104055
  var useCurrentSelection = boolean8("use-current-selection");
102175
104056
  var portalId = readOptionalText4("portal-id");
102176
104057
  var markdownInline = readOptionalText4("markdown");
102177
- var file8 = readOptionalText4("file");
104058
+ var file9 = readOptionalText4("file");
102178
104059
  var clientId3 = readOptionalText4("client-id");
102179
104060
  var idempotencyKey3 = readOptionalText4("idempotency-key");
102180
104061
  var metaSpec3 = readOptionalText4("meta");
102181
- var priority3 = integer7("priority").pipe(optional5, map34(optionToUndefined44));
104062
+ var priority3 = integer7("priority").pipe(optional5, map34(optionToUndefined55));
102182
104063
  var notify3 = boolean8("no-notify").pipe(map34((v) => !v));
102183
104064
  var ensureDaemon5 = boolean8("no-ensure-daemon").pipe(map34((v) => !v));
102184
104065
  var wait3 = boolean8("wait");
102185
- var timeoutMs4 = integer7("timeout-ms").pipe(optional5, map34(optionToUndefined44));
102186
- var pollMs3 = integer7("poll-ms").pipe(optional5, map34(optionToUndefined44));
104066
+ var timeoutMs4 = integer7("timeout-ms").pipe(optional5, map34(optionToUndefined55));
104067
+ var pollMs3 = integer7("poll-ms").pipe(optional5, map34(optionToUndefined55));
102187
104068
  var replaceMarkdownCommand = exports_Command.make("markdown", {
102188
104069
  selection,
102189
- stateFile: stateFile18,
104070
+ stateFile: stateFile24,
102190
104071
  staleMs: staleMs11,
102191
104072
  ref: ref3,
102192
104073
  id: ids4,
@@ -102197,7 +104078,7 @@ var replaceMarkdownCommand = exports_Command.make("markdown", {
102197
104078
  allowDiscontiguous,
102198
104079
  useCurrentSelection,
102199
104080
  portalId,
102200
- file: file8,
104081
+ file: file9,
102201
104082
  markdown: markdownInline,
102202
104083
  notify: notify3,
102203
104084
  ensureDaemon: ensureDaemon5,
@@ -102211,7 +104092,7 @@ var replaceMarkdownCommand = exports_Command.make("markdown", {
102211
104092
  meta: metaSpec3
102212
104093
  }, ({
102213
104094
  selection: selection2,
102214
- stateFile: stateFile19,
104095
+ stateFile: stateFile25,
102215
104096
  staleMs: staleMs12,
102216
104097
  ref: ref4,
102217
104098
  id: id5,
@@ -102222,7 +104103,7 @@ var replaceMarkdownCommand = exports_Command.make("markdown", {
102222
104103
  allowDiscontiguous: allowDiscontiguous2,
102223
104104
  useCurrentSelection: useCurrentSelection2,
102224
104105
  portalId: portalId2,
102225
- file: file9,
104106
+ file: file10,
102226
104107
  markdown: markdown2,
102227
104108
  notify: notify4,
102228
104109
  ensureDaemon: ensureDaemon6,
@@ -102235,6 +104116,10 @@ var replaceMarkdownCommand = exports_Command.make("markdown", {
102235
104116
  idempotencyKey: idempotencyKey4,
102236
104117
  meta
102237
104118
  }) => gen2(function* () {
104119
+ yield* failInRemoteMode({
104120
+ command: "replace markdown",
104121
+ reason: "replace markdown is an advanced/local-only block replace command that still depends on local selection/ref resolution semantics"
104122
+ });
102238
104123
  if (!wait4 && (timeoutMs5 !== undefined || pollMs4 !== undefined)) {
102239
104124
  return yield* fail8(new CliError({
102240
104125
  code: "INVALID_ARGS",
@@ -102251,18 +104136,18 @@ var replaceMarkdownCommand = exports_Command.make("markdown", {
102251
104136
  }
102252
104137
  const fileInput = yield* FileInput;
102253
104138
  const payloadSvc = yield* Payload;
102254
- const resolvedTarget = yield* resolveReplaceTarget({ selection: selection2, stateFile: stateFile19, staleMs: staleMs12, ref: ref4, ids: id5 });
102255
- if (file9 && markdown2) {
104139
+ const resolvedTarget = yield* resolveReplaceTarget({ selection: selection2, stateFile: stateFile25, staleMs: staleMs12, ref: ref4, ids: id5 });
104140
+ if (file10 && markdown2) {
102256
104141
  return yield* fail8(new CliError({
102257
104142
  code: "INVALID_ARGS",
102258
104143
  message: "Choose only one of --file or --markdown",
102259
104144
  exitCode: 2
102260
104145
  }));
102261
104146
  }
102262
- if (!file9 && !markdown2) {
104147
+ if (!file10 && !markdown2) {
102263
104148
  return yield* fail8(new CliError({ code: "INVALID_ARGS", message: "You must provide --file or --markdown", exitCode: 2 }));
102264
104149
  }
102265
- const mdRaw = typeof markdown2 === "string" ? markdown2 : yield* fileInput.readTextFromFileSpec({ spec: String(file9) });
104150
+ const mdRaw = typeof markdown2 === "string" ? markdown2 : yield* fileInput.readTextFromFileSpec({ spec: String(file10) });
102266
104151
  const md = trimBoundaryBlankLines(mdRaw);
102267
104152
  const scopeValue = scope6 ?? "roots";
102268
104153
  if (scopeValue !== "roots") {
@@ -102338,33 +104223,40 @@ var replaceMarkdownCommand = exports_Command.make("markdown", {
102338
104223
  });
102339
104224
  const waited = wait4 ? yield* waitForTxn({ txnId: data.txn_id, timeoutMs: timeoutMs5, pollMs: pollMs4 }) : null;
102340
104225
  const out = waited ? { ...data, ...waited } : data;
104226
+ const backup = waited?.status === "succeeded" ? yield* loadTxnDetail({ txnId: data.txn_id }).pipe(map17((detail) => extractReplaceBackupSummary(detail)), catchAll2(() => succeed8(undefined))) : undefined;
102341
104227
  yield* writeSuccess({
102342
- data: { ...out, target: resolvedTarget },
104228
+ data: backup ? { ...out, target: resolvedTarget, backup } : { ...out, target: resolvedTarget },
102343
104229
  ids: [data.txn_id, ...data.op_ids],
102344
104230
  md: [
102345
104231
  `- txn_id: ${data.txn_id}`,
102346
104232
  `- op_ids: ${data.op_ids.length}`,
102347
104233
  `- notified: ${data.notified}`,
102348
104234
  `- sent: ${data.sent ?? ""}`,
102349
- ...waited ? [`- status: ${waited.status}`, `- elapsed_ms: ${waited.elapsed_ms}`] : []
104235
+ ...waited ? [`- status: ${waited.status}`, `- elapsed_ms: ${waited.elapsed_ms}`] : [],
104236
+ ...backup ? [
104237
+ `- backup_policy: ${backup.policy}`,
104238
+ `- backup_deleted: ${backup.deleted ? "true" : "false"}`,
104239
+ ...backup.hidden ? ["- backup_hidden: true"] : [],
104240
+ ...backup.cleanup_state ? [`- backup_cleanup_state: ${backup.cleanup_state}`] : []
104241
+ ] : []
102350
104242
  ].join(`
102351
104243
  `)
102352
104244
  });
102353
- }).pipe(catchAll2(writeFailure)));
104245
+ }).pipe(catchAll2(writeFailure))).pipe(exports_Command.withDescription("advanced/local-only block replace command; canonical replace workflows should prefer rem replace"));
102354
104246
 
102355
104247
  // src/commands/write/replace/text.ts
102356
- function optionToUndefined45(opt) {
104248
+ function optionToUndefined56(opt) {
102357
104249
  return isSome2(opt) ? opt.value : undefined;
102358
104250
  }
102359
104251
  function readOptionalText5(name) {
102360
- return text9(name).pipe(optional5, map34(optionToUndefined45));
104252
+ return text9(name).pipe(optional5, map34(optionToUndefined56));
102361
104253
  }
102362
104254
  var selection2 = boolean8("selection");
102363
- var stateFile19 = readOptionalText5("state-file");
102364
- var staleMs12 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined45));
104255
+ var stateFile25 = readOptionalText5("state-file");
104256
+ var staleMs12 = integer7("stale-ms").pipe(optional5, map34(optionToUndefined56));
102365
104257
  var ref4 = readOptionalText5("ref");
102366
104258
  var ids5 = text9("id").pipe(repeated5);
102367
- var scope6 = choice5("scope", ["roots", "subtree"]).pipe(optional5, map34(optionToUndefined45));
104259
+ var scope6 = choice5("scope", ["roots", "subtree"]).pipe(optional5, map34(optionToUndefined56));
102368
104260
  var maxDepth5 = integer7("max-depth").pipe(withDefault5(10));
102369
104261
  var maxNodes3 = integer7("max-nodes").pipe(withDefault5(1000));
102370
104262
  var requireComplete2 = boolean8("require-complete");
@@ -102376,12 +104268,12 @@ var flags = readOptionalText5("flags");
102376
104268
  var clientId4 = readOptionalText5("client-id");
102377
104269
  var idempotencyKey4 = readOptionalText5("idempotency-key");
102378
104270
  var metaSpec4 = readOptionalText5("meta");
102379
- var priority4 = integer7("priority").pipe(optional5, map34(optionToUndefined45));
104271
+ var priority4 = integer7("priority").pipe(optional5, map34(optionToUndefined56));
102380
104272
  var notify4 = boolean8("no-notify").pipe(map34((v) => !v));
102381
104273
  var ensureDaemon6 = boolean8("no-ensure-daemon").pipe(map34((v) => !v));
102382
104274
  var wait4 = boolean8("wait");
102383
- var timeoutMs5 = integer7("timeout-ms").pipe(optional5, map34(optionToUndefined45));
102384
- var pollMs4 = integer7("poll-ms").pipe(optional5, map34(optionToUndefined45));
104275
+ var timeoutMs5 = integer7("timeout-ms").pipe(optional5, map34(optionToUndefined56));
104276
+ var pollMs4 = integer7("poll-ms").pipe(optional5, map34(optionToUndefined56));
102385
104277
  function tryMakeRegExp(pattern2, rawFlags) {
102386
104278
  const f = typeof rawFlags === "string" && rawFlags.trim() ? rawFlags.trim() : "g";
102387
104279
  const withGlobal = f.includes("g") ? f : `g${f}`;
@@ -102427,7 +104319,7 @@ function replaceRichText(value8, replacer) {
102427
104319
  }
102428
104320
  var replaceLiteralCommand = exports_Command.make("literal", {
102429
104321
  selection: selection2,
102430
- stateFile: stateFile19,
104322
+ stateFile: stateFile25,
102431
104323
  staleMs: staleMs12,
102432
104324
  ref: ref4,
102433
104325
  id: ids5,
@@ -102452,7 +104344,7 @@ var replaceLiteralCommand = exports_Command.make("literal", {
102452
104344
  meta: metaSpec4
102453
104345
  }, ({
102454
104346
  selection: selection3,
102455
- stateFile: stateFile20,
104347
+ stateFile: stateFile26,
102456
104348
  staleMs: staleMs13,
102457
104349
  ref: ref5,
102458
104350
  id: id5,
@@ -102493,7 +104385,7 @@ var replaceLiteralCommand = exports_Command.make("literal", {
102493
104385
  const cfg = yield* AppConfig;
102494
104386
  const payloadSvc = yield* Payload;
102495
104387
  const remdb = yield* RemDb;
102496
- const target2 = yield* resolveReplaceTarget({ selection: selection3, stateFile: stateFile20, staleMs: staleMs13, ref: ref5, ids: id5 });
104388
+ const target2 = yield* resolveReplaceTarget({ selection: selection3, stateFile: stateFile26, staleMs: staleMs13, ref: ref5, ids: id5 });
102497
104389
  const scopeValue = scope7 ?? "roots";
102498
104390
  if (target2.kind === "selection" && requireComplete3) {
102499
104391
  const sel = target2.snapshot.selection;
@@ -102629,11 +104521,11 @@ var writeReplaceCommand = exports_Command.make("replace", {}).pipe(exports_Comma
102629
104521
  var replaceCommand = writeReplaceCommand;
102630
104522
 
102631
104523
  // src/commands/read/search.ts
102632
- function optionToUndefined46(opt) {
104524
+ function optionToUndefined57(opt) {
102633
104525
  return isSome2(opt) ? opt.value : undefined;
102634
104526
  }
102635
- var timeRange2 = text9("time").pipe(optional5, map34(optionToUndefined46));
102636
- var parentId = text9("parent").pipe(optional5, map34(optionToUndefined46));
104527
+ var timeRange2 = text9("time").pipe(optional5, map34(optionToUndefined57));
104528
+ var parentId = text9("parent").pipe(optional5, map34(optionToUndefined57));
102637
104529
  var limit7 = integer7("limit").pipe(withDefault5(10));
102638
104530
  var offset6 = integer7("offset").pipe(withDefault5(0));
102639
104531
  var timeoutMs6 = integer7("timeout-ms").pipe(withDefault5(30000));
@@ -102691,10 +104583,10 @@ function normalizeRemIdInput7(raw4) {
102691
104583
  }
102692
104584
  var writeTableCreateCommand = exports_Command.make("create", {
102693
104585
  tableTag: text9("table-tag"),
102694
- parent: text9("parent").pipe(optional5, map34(optionToUndefined34)),
102695
- ref: text9("ref").pipe(optional5, map34(optionToUndefined34)),
102696
- position: integer7("position").pipe(optional5, map34(optionToUndefined34)),
102697
- clientTempId: text9("client-temp-id").pipe(optional5, map34(optionToUndefined34)),
104586
+ parent: text9("parent").pipe(optional5, map34(optionToUndefined43)),
104587
+ ref: text9("ref").pipe(optional5, map34(optionToUndefined43)),
104588
+ position: integer7("position").pipe(optional5, map34(optionToUndefined43)),
104589
+ clientTempId: text9("client-temp-id").pipe(optional5, map34(optionToUndefined43)),
102698
104590
  notify: writeCommonOptions.notify,
102699
104591
  ensureDaemon: writeCommonOptions.ensureDaemon,
102700
104592
  wait: writeCommonOptions.wait,
@@ -103105,8 +104997,8 @@ var writeTableOptionCommand = exports_Command.make("option", {}).pipe(exports_Co
103105
104997
  var writeTablePropertyAddCommand = exports_Command.make("add", {
103106
104998
  tableTag: text9("table-tag"),
103107
104999
  name: text9("name"),
103108
- type: text9("type").pipe(optional5, map34(optionToUndefined34)),
103109
- options: text9("options").pipe(optional5, map34(optionToUndefined34)),
105000
+ type: text9("type").pipe(optional5, map34(optionToUndefined43)),
105001
+ options: text9("options").pipe(optional5, map34(optionToUndefined43)),
103110
105002
  notify: writeCommonOptions.notify,
103111
105003
  ensureDaemon: writeCommonOptions.ensureDaemon,
103112
105004
  wait: writeCommonOptions.wait,
@@ -103242,10 +105134,10 @@ var writeTablePropertyCommand = exports_Command.make("property", {}).pipe(export
103242
105134
  // src/commands/write/table/record/add.ts
103243
105135
  var writeTableRecordAddCommand = exports_Command.make("add", {
103244
105136
  tableTag: text9("table-tag"),
103245
- parent: text9("parent").pipe(optional5, map34(optionToUndefined34)),
103246
- ref: text9("ref").pipe(optional5, map34(optionToUndefined34)),
103247
- text: text9("text").pipe(optional5, map34(optionToUndefined34)),
103248
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
105137
+ parent: text9("parent").pipe(optional5, map34(optionToUndefined43)),
105138
+ ref: text9("ref").pipe(optional5, map34(optionToUndefined43)),
105139
+ text: text9("text").pipe(optional5, map34(optionToUndefined43)),
105140
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
103249
105141
  notify: writeCommonOptions.notify,
103250
105142
  ensureDaemon: writeCommonOptions.ensureDaemon,
103251
105143
  wait: writeCommonOptions.wait,
@@ -103560,8 +105452,8 @@ function rowHasTag4(doc, tagId) {
103560
105452
  var writeTableRecordUpdateCommand = exports_Command.make("update", {
103561
105453
  tableTag: text9("table-tag"),
103562
105454
  row: text9("row"),
103563
- text: text9("text").pipe(optional5, map34(optionToUndefined34)),
103564
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
105455
+ text: text9("text").pipe(optional5, map34(optionToUndefined43)),
105456
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
103565
105457
  notify: writeCommonOptions.notify,
103566
105458
  ensureDaemon: writeCommonOptions.ensureDaemon,
103567
105459
  wait: writeCommonOptions.wait,
@@ -103782,10 +105674,10 @@ var tableCommand = exports_Command.make("table", {}).pipe(exports_Command.withSu
103782
105674
  var tagCommand = writeTagCommand;
103783
105675
 
103784
105676
  // src/commands/read/todos/list.ts
103785
- function optionToUndefined47(opt) {
105677
+ function optionToUndefined58(opt) {
103786
105678
  return isSome2(opt) ? opt.value : undefined;
103787
105679
  }
103788
- var status2 = choice5("status", ["unfinished", "finished", "all"]).pipe(optional5, map34(optionToUndefined47));
105680
+ var status2 = choice5("status", ["unfinished", "finished", "all"]).pipe(optional5, map34(optionToUndefined58));
103789
105681
  var sort3 = choice5("sort", [
103790
105682
  "dueAsc",
103791
105683
  "dueDesc",
@@ -103793,22 +105685,22 @@ var sort3 = choice5("sort", [
103793
105685
  "updatedAtDesc",
103794
105686
  "createdAtAsc",
103795
105687
  "createdAtDesc"
103796
- ]).pipe(optional5, map34(optionToUndefined47));
105688
+ ]).pipe(optional5, map34(optionToUndefined58));
103797
105689
  var tagId = text9("tag-id").pipe(repeated5);
103798
105690
  var tagTitle = text9("tag-title").pipe(repeated5);
103799
105691
  var preferTodoOnly = boolean8("prefer-todo-only");
103800
105692
  var preferTodoFirst = boolean8("prefer-todo-first");
103801
105693
  var includeDescendants = boolean8("no-descendants").pipe(map34((v) => !v));
103802
- var ancestor = text9("ancestor").pipe(optional5, map34(optionToUndefined47));
103803
- var dueBefore = text9("due-before").pipe(optional5, map34(optionToUndefined47));
103804
- var dueAfter = text9("due-after").pipe(optional5, map34(optionToUndefined47));
105694
+ var ancestor = text9("ancestor").pipe(optional5, map34(optionToUndefined58));
105695
+ var dueBefore = text9("due-before").pipe(optional5, map34(optionToUndefined58));
105696
+ var dueAfter = text9("due-after").pipe(optional5, map34(optionToUndefined58));
103805
105697
  var includeTagOnlyWhenNoStatus = boolean8("no-tag-only-when-no-status").pipe(map34((v) => !v));
103806
105698
  var statusAttrTitle = text9("status-attr-title").pipe(repeated5);
103807
105699
  var unfinishedOptionTitle = text9("unfinished-option-title").pipe(repeated5);
103808
105700
  var finishedOptionTitle = text9("finished-option-title").pipe(repeated5);
103809
105701
  var dueDateAttrTitle = text9("due-date-attr-title").pipe(repeated5);
103810
105702
  var alwaysIncludeTagOnlyTitle = text9("always-include-tag-only-title").pipe(repeated5);
103811
- var snippetLength2 = integer7("snippet-length").pipe(optional5, map34(optionToUndefined47));
105703
+ var snippetLength2 = integer7("snippet-length").pipe(optional5, map34(optionToUndefined58));
103812
105704
  var limit9 = integer7("limit").pipe(withDefault5(20));
103813
105705
  var offset8 = integer7("offset").pipe(withDefault5(0));
103814
105706
  function makeTodosListCommand() {
@@ -103889,8 +105781,8 @@ function makeTodosListCommand() {
103889
105781
  var todosListCommand = makeTodosListCommand();
103890
105782
 
103891
105783
  // src/commands/write/powerup/todo/todoAdd.ts
103892
- var status3 = choice5("status", ["unfinished", "finished", "clear"]).pipe(optional5, map34(optionToUndefined34));
103893
- var dispatchMode4 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined34));
105784
+ var status3 = choice5("status", ["unfinished", "finished", "clear"]).pipe(optional5, map34(optionToUndefined43));
105785
+ var dispatchMode4 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined43));
103894
105786
  function pickTodoSchema(schemas, tagId2) {
103895
105787
  const mapped = schemas.map((s) => ({
103896
105788
  tagId: String(s?.tagId ?? ""),
@@ -103909,10 +105801,10 @@ function pickTodoSchema(schemas, tagId2) {
103909
105801
  }
103910
105802
  var writePowerupTodoAddCommand = exports_Command.make("add", {
103911
105803
  rem: text9("rem"),
103912
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
105804
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
103913
105805
  status: status3,
103914
- due: text9("due").pipe(optional5, map34(optionToUndefined34)),
103915
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
105806
+ due: text9("due").pipe(optional5, map34(optionToUndefined43)),
105807
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
103916
105808
  notify: writeCommonOptions.notify,
103917
105809
  ensureDaemon: writeCommonOptions.ensureDaemon,
103918
105810
  wait: writeCommonOptions.wait,
@@ -104170,12 +106062,12 @@ function todoWriteEffect(params3) {
104170
106062
  }
104171
106063
 
104172
106064
  // src/commands/write/powerup/todo/todoDone.ts
104173
- var dispatchMode5 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined34));
106065
+ var dispatchMode5 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined43));
104174
106066
  var writePowerupTodoDoneCommand = exports_Command.make("done", {
104175
106067
  rem: text9("rem"),
104176
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
104177
- due: text9("due").pipe(optional5, map34(optionToUndefined34)),
104178
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
106068
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
106069
+ due: text9("due").pipe(optional5, map34(optionToUndefined43)),
106070
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
104179
106071
  notify: writeCommonOptions.notify,
104180
106072
  ensureDaemon: writeCommonOptions.ensureDaemon,
104181
106073
  wait: writeCommonOptions.wait,
@@ -104232,8 +106124,8 @@ function pickTodoTagId(schemas, tagId2) {
104232
106124
  }
104233
106125
  var writePowerupTodoRemoveCommand = exports_Command.make("remove", {
104234
106126
  rem: text9("rem"),
104235
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
104236
- removeProperties: boolean8("remove-properties").pipe(optional5, map34(optionToUndefined34)),
106127
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
106128
+ removeProperties: boolean8("remove-properties").pipe(optional5, map34(optionToUndefined43)),
104237
106129
  notify: writeCommonOptions.notify,
104238
106130
  ensureDaemon: writeCommonOptions.ensureDaemon,
104239
106131
  wait: writeCommonOptions.wait,
@@ -104360,12 +106252,12 @@ var writePowerupTodoRemoveCommand = exports_Command.make("remove", {
104360
106252
  }).pipe(catchAll2(writeFailure)));
104361
106253
 
104362
106254
  // src/commands/write/powerup/todo/todoUndone.ts
104363
- var dispatchMode6 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined34));
106255
+ var dispatchMode6 = choice5("dispatch-mode", ["serial", "conflict_parallel"]).pipe(optional5, map34(optionToUndefined43));
104364
106256
  var writePowerupTodoUndoneCommand = exports_Command.make("undone", {
104365
106257
  rem: text9("rem"),
104366
- tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined34)),
104367
- due: text9("due").pipe(optional5, map34(optionToUndefined34)),
104368
- values: text9("values").pipe(optional5, map34(optionToUndefined34)),
106258
+ tagId: text9("tag-id").pipe(optional5, map34(optionToUndefined43)),
106259
+ due: text9("due").pipe(optional5, map34(optionToUndefined43)),
106260
+ values: text9("values").pipe(optional5, map34(optionToUndefined43)),
104369
106261
  notify: writeCommonOptions.notify,
104370
106262
  ensureDaemon: writeCommonOptions.ensureDaemon,
104371
106263
  wait: writeCommonOptions.wait,
@@ -104422,15 +106314,15 @@ var todoCommand = exports_Command.make("todo", {}).pipe(exports_Command.withSubc
104422
106314
  ]));
104423
106315
 
104424
106316
  // src/commands/read/topic/summary.ts
104425
- function optionToUndefined48(opt) {
106317
+ function optionToUndefined59(opt) {
104426
106318
  return isSome2(opt) ? opt.value : undefined;
104427
106319
  }
104428
- var keywords = text9("keywords").pipe(optional5, map34(optionToUndefined48));
104429
- var query2 = text9("query").pipe(optional5, map34(optionToUndefined48));
104430
- var timeRange3 = text9("time").pipe(optional5, map34(optionToUndefined48));
104431
- var maxResults = integer7("max-results").pipe(optional5, map34(optionToUndefined48));
104432
- var maxNodesPerResult = integer7("max-nodes").pipe(optional5, map34(optionToUndefined48));
104433
- var groupBy2 = choice5("group-by", ["none", "parent", "date"]).pipe(optional5, map34(optionToUndefined48));
106320
+ var keywords = text9("keywords").pipe(optional5, map34(optionToUndefined59));
106321
+ var query2 = text9("query").pipe(optional5, map34(optionToUndefined59));
106322
+ var timeRange3 = text9("time").pipe(optional5, map34(optionToUndefined59));
106323
+ var maxResults = integer7("max-results").pipe(optional5, map34(optionToUndefined59));
106324
+ var maxNodesPerResult = integer7("max-nodes").pipe(optional5, map34(optionToUndefined59));
106325
+ var groupBy2 = choice5("group-by", ["none", "parent", "date"]).pipe(optional5, map34(optionToUndefined59));
104434
106326
  var topicSummaryCommand = exports_Command.make("summary", { keywords, query: query2, timeRange: timeRange3, maxResults, maxNodesPerResult, groupBy: groupBy2 }, ({ keywords: keywords2, query: query3, timeRange: timeRange4, maxResults: maxResults2, maxNodesPerResult: maxNodesPerResult2, groupBy: groupBy3 }) => gen2(function* () {
104435
106327
  const cfg = yield* AppConfig;
104436
106328
  yield* failInRemoteMode({
@@ -104486,8 +106378,8 @@ function looksLikeRef(raw4) {
104486
106378
  var writePortalCreateCommand = exports_Command.make("create", {
104487
106379
  parent: text9("parent"),
104488
106380
  target: text9("target"),
104489
- position: integer7("position").pipe(optional5, map34(optionToUndefined34)),
104490
- clientTempId: text9("client-temp-id").pipe(optional5, map34(optionToUndefined34)),
106381
+ position: integer7("position").pipe(optional5, map34(optionToUndefined43)),
106382
+ clientTempId: text9("client-temp-id").pipe(optional5, map34(optionToUndefined43)),
104491
106383
  notify: writeCommonOptions.notify,
104492
106384
  ensureDaemon: writeCommonOptions.ensureDaemon,
104493
106385
  wait: writeCommonOptions.wait,
@@ -104688,7 +106580,7 @@ var stackEnsureCommand = exports_Command.make("ensure", {
104688
106580
  }).pipe(catchAll2(writeFailure)));
104689
106581
 
104690
106582
  // src/commands/stack/status.ts
104691
- import path26 from "node:path";
106583
+ import path29 from "node:path";
104692
106584
  var stackStatusCommand = exports_Command.make("status", {}, () => gen2(function* () {
104693
106585
  const cfg = yield* AppConfig;
104694
106586
  const daemonFiles = yield* DaemonFiles;
@@ -104709,7 +106601,7 @@ var stackStatusCommand = exports_Command.make("status", {}, () => gen2(function*
104709
106601
  const apiBaseUrl = apiLocalBaseUrl(apiPidInfo?.port ?? cfg.apiPort ?? 3000, apiBasePath);
104710
106602
  const apiStatus = yield* api.status({ baseUrl: apiBaseUrl, timeoutMs: 2000 }).pipe(either3);
104711
106603
  const queueStats2 = yield* queue.stats({ dbPath: cfg.storeDb }).pipe(either3);
104712
- const stateFilePath = resolveUserFilePath(daemonPidInfo?.state_file ?? path26.join(path26.dirname(daemonPidFile), "ws.state.json"));
106604
+ const stateFilePath = resolveUserFilePath(daemonPidInfo?.state_file ?? path29.join(path29.dirname(daemonPidFile), "ws.state.json"));
104713
106605
  const data = {
104714
106606
  daemon: {
104715
106607
  running: daemonRunning,
@@ -104755,7 +106647,7 @@ var stackStatusCommand = exports_Command.make("status", {}, () => gen2(function*
104755
106647
  }).pipe(catchAll2(writeFailure)));
104756
106648
 
104757
106649
  // src/commands/stack/stop.ts
104758
- import path27 from "node:path";
106650
+ import path30 from "node:path";
104759
106651
  var stackStopCommand = exports_Command.make("stop", {}, () => gen2(function* () {
104760
106652
  const apiFiles = yield* ApiDaemonFiles;
104761
106653
  const daemonFiles = yield* DaemonFiles;
@@ -104792,7 +106684,7 @@ var stackStopCommand = exports_Command.make("stop", {}, () => gen2(function* ()
104792
106684
  }
104793
106685
  }
104794
106686
  yield* daemonFiles.deletePidFile(daemonPidFile).pipe(catchAll2(() => _void));
104795
- yield* supervisorState.deleteStateFile(resolveUserFilePath(daemonPidInfo?.state_file ?? path27.join(path27.dirname(daemonPidFile), "ws.state.json"))).pipe(catchAll2(() => _void));
106687
+ yield* supervisorState.deleteStateFile(resolveUserFilePath(daemonPidInfo?.state_file ?? path30.join(path30.dirname(daemonPidFile), "ws.state.json"))).pipe(catchAll2(() => _void));
104796
106688
  yield* writeSuccess({
104797
106689
  data: { stopped: true, api_stopped: apiStopped, daemon_stopped: daemonStopped },
104798
106690
  md: `- stopped: true
@@ -104806,23 +106698,23 @@ var stackStopCommand = exports_Command.make("stop", {}, () => gen2(function* ()
104806
106698
  var stackCommand = exports_Command.make("stack", {}).pipe(exports_Command.withSubcommands([stackEnsureCommand, stackStopCommand, stackStatusCommand]));
104807
106699
 
104808
106700
  // src/commands/index.ts
104809
- function optionToUndefined49(opt) {
106701
+ function optionToUndefined60(opt) {
104810
106702
  return isSome2(opt) ? opt.value : undefined;
104811
106703
  }
104812
- var remnoteDb = text9("remnote-db").pipe(optional5, map34(optionToUndefined49));
104813
- var storeDb = text9("store-db").pipe(optional5, map34(optionToUndefined49));
104814
- var daemonUrl = text9("daemon-url").pipe(optional5, map34(optionToUndefined49));
104815
- var wsPort = integer7("ws-port").pipe(optional5, map34(optionToUndefined49));
104816
- var repo = text9("repo").pipe(optional5, map34(optionToUndefined49));
104817
- var apiBaseUrl = text9("api-base-url").pipe(optional5, map34(optionToUndefined49));
104818
- var apiHost = text9("api-host").pipe(optional5, map34(optionToUndefined49));
104819
- var apiPort = integer7("api-port").pipe(optional5, map34(optionToUndefined49));
104820
- var apiBasePath = text9("api-base-path").pipe(optional5, map34(optionToUndefined49));
104821
- var configFile = text9("config-file").pipe(optional5, map34(optionToUndefined49));
106704
+ var remnoteDb = text9("remnote-db").pipe(optional5, map34(optionToUndefined60));
106705
+ var storeDb = text9("store-db").pipe(optional5, map34(optionToUndefined60));
106706
+ var daemonUrl = text9("daemon-url").pipe(optional5, map34(optionToUndefined60));
106707
+ var wsPort = integer7("ws-port").pipe(optional5, map34(optionToUndefined60));
106708
+ var repo = text9("repo").pipe(optional5, map34(optionToUndefined60));
106709
+ var apiBaseUrl = text9("api-base-url").pipe(optional5, map34(optionToUndefined60));
106710
+ var apiHost = text9("api-host").pipe(optional5, map34(optionToUndefined60));
106711
+ var apiPort = integer7("api-port").pipe(optional5, map34(optionToUndefined60));
106712
+ var apiBasePath = text9("api-base-path").pipe(optional5, map34(optionToUndefined60));
106713
+ var configFile = text9("config-file").pipe(optional5, map34(optionToUndefined60));
104822
106714
  var appConfigLive = effect(AppConfig, resolveConfig());
104823
106715
  var statusLineUpdaterLive = StatusLineUpdaterLive.pipe(provide3([appConfigLive, QueueLive, StatusLineFileLive, TmuxLive, WsBridgeStateLive]));
104824
106716
  var statusLineLive = StatusLineControllerLive.pipe(provide3(statusLineUpdaterLive), provide3(appConfigLive));
104825
- var servicesLive = mergeAll5(appConfigLive, OutputLive, FileInputLive, FsAccessLive, LogWriterFactoryLive, PayloadLive, DaemonFilesLive, ApiDaemonFilesLive, ProcessLive, ChildProcessLive, WsClientLive, HostApiClientLive.pipe(provide3(appConfigLive)), UserConfigFileLive, WorkspaceBindingsLive, QueueLive, RefResolverLive, RemDbLive, StatusLineFileLive, SubprocessLive, SupervisorStateLive, WsBridgeServerLive, WsBridgeStateFileLive, statusLineLive);
106717
+ var servicesLive = mergeAll5(appConfigLive, OutputLive, FileInputLive, FsAccessLive, LogWriterFactoryLive, PayloadLive, DaemonFilesLive, ApiDaemonFilesLive, ProcessLive, ChildProcessLive, WsClientLive, HostApiClientLive.pipe(provide3(appConfigLive)), PluginServerFilesLive, UserConfigFileLive, WorkspaceBindingsLive, QueueLive, RefResolverLive, RemDbLive, StatusLineFileLive, SubprocessLive, SupervisorStateLive, WsBridgeServerLive, WsBridgeStateFileLive, statusLineLive);
104826
106718
  var rootCommand = exports_Command.make("agent-remnote", {
104827
106719
  json: boolean8("json"),
104828
106720
  md: boolean8("md"),
@@ -104850,6 +106742,7 @@ var rootCommand = exports_Command.make("agent-remnote", {
104850
106742
  queryCommand,
104851
106743
  remCommand,
104852
106744
  dailyCommand,
106745
+ backupCommand,
104853
106746
  todoCommand,
104854
106747
  topicCommand,
104855
106748
  powerupCommand,