@remnic/plugin-openclaw 1.0.54 → 9.3.517

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.
Files changed (84) hide show
  1. package/dist/index.js +510 -2106
  2. package/openclaw.plugin.json +3 -3
  3. package/package.json +4 -3
  4. package/scripts/faiss_index.py +141 -29
  5. package/dist/calibration-RKL2LRW4.js +0 -250
  6. package/dist/capsule-cli-EHZPMXBC.js +0 -33
  7. package/dist/capsule-crypto-JS67OSWM.js +0 -17
  8. package/dist/capsule-export-DX53CPIT.js +0 -17
  9. package/dist/capsule-import-4OXCPHOT.js +0 -16
  10. package/dist/capsule-merge-25AUN33Q.js +0 -195
  11. package/dist/causal-chain-BVTOWZKC.js +0 -23
  12. package/dist/causal-consolidation-IAIX53NV.js +0 -233
  13. package/dist/causal-retrieval-XAP6QKHZ.js +0 -182
  14. package/dist/causal-trajectory-graph-ZWQWZ7N5.js +0 -59
  15. package/dist/chunk-25J4PXDH.js +0 -30
  16. package/dist/chunk-2RQU6GVD.js +0 -453
  17. package/dist/chunk-3A5ELHTT.js +0 -61
  18. package/dist/chunk-3G7FAF6S.js +0 -60
  19. package/dist/chunk-3IKMUNW5.js +0 -177
  20. package/dist/chunk-4XDQ3KEC.js +0 -4048
  21. package/dist/chunk-5ZW5XJQ6.js +0 -128
  22. package/dist/chunk-6IWEAUN6.js +0 -148
  23. package/dist/chunk-7JOLBJJ5.js +0 -874
  24. package/dist/chunk-AJECKGY2.js +0 -896
  25. package/dist/chunk-B52XADV3.js +0 -244
  26. package/dist/chunk-BQZ7JACP.js +0 -389
  27. package/dist/chunk-BU5KJVWF.js +0 -78
  28. package/dist/chunk-BZ4EYURA.js +0 -181
  29. package/dist/chunk-CEL5ZLKP.js +0 -233
  30. package/dist/chunk-EH4AXGRO.js +0 -48
  31. package/dist/chunk-FDK3VJVE.js +0 -1295
  32. package/dist/chunk-I2KLQ2HA.js +0 -22
  33. package/dist/chunk-IO5WWY6A.js +0 -156
  34. package/dist/chunk-JC3FCKYL.js +0 -516
  35. package/dist/chunk-JZBOXOUC.js +0 -259
  36. package/dist/chunk-KC7KSQR4.js +0 -302
  37. package/dist/chunk-LZCGPRHS.js +0 -228
  38. package/dist/chunk-MBIFE6SA.js +0 -250
  39. package/dist/chunk-MXFJXUHC.js +0 -292
  40. package/dist/chunk-NUWDSTP7.js +0 -233
  41. package/dist/chunk-QCCP4RU5.js +0 -190
  42. package/dist/chunk-QMUQV5NP.js +0 -146
  43. package/dist/chunk-QQXJODFL.js +0 -328
  44. package/dist/chunk-SWOYEQN2.js +0 -1005
  45. package/dist/chunk-TH5FF5SC.js +0 -16
  46. package/dist/chunk-TXOEHSVP.js +0 -275
  47. package/dist/chunk-UFU5GGGA.js +0 -47
  48. package/dist/chunk-USSDZQKJ.js +0 -6533
  49. package/dist/chunk-UZJ7EERS.js +0 -272
  50. package/dist/chunk-VUZEEGP5.js +0 -725
  51. package/dist/chunk-W6EEFUCJ.js +0 -349
  52. package/dist/chunk-YGGGUTG3.js +0 -125
  53. package/dist/chunk-YJYZMLD5.js +0 -360
  54. package/dist/chunk-YKV4EFUI.js +0 -199
  55. package/dist/chunk-ZS6VABML.js +0 -185
  56. package/dist/cipher-E23BHBSO.js +0 -27
  57. package/dist/consolidation-undo-FKJZCJHS.js +0 -426
  58. package/dist/contradiction-review-WJRWNQ5N.js +0 -29
  59. package/dist/contradiction-scan-5X423QGT.js +0 -12
  60. package/dist/dreams-ledger-KDX44I7R.js +0 -290
  61. package/dist/engine-O46ZX4EZ.js +0 -16
  62. package/dist/extraction-judge-telemetry-O4ZVGLTU.js +0 -14
  63. package/dist/fallback-llm-43UMEXNJ.js +0 -10
  64. package/dist/first-start-migration-H2SAXAGR.js +0 -263
  65. package/dist/forget-ZECIDNL5.js +0 -68
  66. package/dist/fs-utils-OYXSZSVV.js +0 -39
  67. package/dist/graph-edge-decay-24ZKD5QL.js +0 -202
  68. package/dist/kdf-RXKIWHRU.js +0 -25
  69. package/dist/logger-XG7JKLPS.js +0 -9
  70. package/dist/memory-governance-6BCH6SZ5.js +0 -25
  71. package/dist/metadata-WK2TRPYZ.js +0 -20
  72. package/dist/migrate-from-identity-anchor-SNDNKHZD.js +0 -7
  73. package/dist/path-ZKO74XXC.js +0 -7
  74. package/dist/peers-W53WSDXG.js +0 -43
  75. package/dist/purge-IKJISXEQ.js +0 -204
  76. package/dist/resolution-BN35OXDS.js +0 -11
  77. package/dist/secure-store-6RWYM6GK.js +0 -155
  78. package/dist/state-4ITLYMAU.js +0 -7
  79. package/dist/state-store-ET3ADVY5.js +0 -14
  80. package/dist/storage-VEGU76NN.js +0 -27
  81. package/dist/tier-stats-ZRQBV6G2.js +0 -147
  82. package/dist/trace-IL2Y34EH.js +0 -289
  83. package/dist/tui-7KRDCMYK.js +0 -12
  84. package/dist/types-MBUINTB2.js +0 -30
@@ -1,190 +0,0 @@
1
- import {
2
- external_exports
3
- } from "./chunk-4XDQ3KEC.js";
4
-
5
- // ../remnic-core/src/transfer/types.ts
6
- var ExportManifestV1Schema = external_exports.object({
7
- format: external_exports.literal("openclaw-engram-export"),
8
- schemaVersion: external_exports.literal(1),
9
- createdAt: external_exports.string(),
10
- pluginVersion: external_exports.string(),
11
- includesTranscripts: external_exports.boolean(),
12
- files: external_exports.array(
13
- external_exports.object({
14
- path: external_exports.string(),
15
- sha256: external_exports.string(),
16
- bytes: external_exports.number().int().nonnegative()
17
- })
18
- )
19
- });
20
- var ExportMemoryRecordV1Schema = external_exports.object({
21
- path: external_exports.string(),
22
- content: external_exports.string()
23
- });
24
- var ExportBundleV1Schema = external_exports.object({
25
- manifest: ExportManifestV1Schema,
26
- records: external_exports.array(ExportMemoryRecordV1Schema)
27
- });
28
- var CAPSULE_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?!-))*[A-Za-z0-9]$|^[A-Za-z0-9]$/;
29
- var CapsuleIdSchema = external_exports.string().min(1, "capsule.id must not be empty").max(64, "capsule.id must be 64 characters or fewer").regex(
30
- CAPSULE_ID_PATTERN,
31
- "capsule.id must be alphanumeric with single dashes (no spaces, no leading/trailing dashes)"
32
- );
33
- var SemverLikeSchema = external_exports.string().min(1, "capsule.version must not be empty").regex(
34
- /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,
35
- "capsule.version must be a semver-like string (e.g. 1.0.0)"
36
- );
37
- function isSafePosixRelativePathPrefix(value) {
38
- if (value.startsWith("/") || value.includes("\\")) return false;
39
- const segments = value.split("/");
40
- return segments.every((segment) => segment !== "" && segment !== "." && segment !== "..");
41
- }
42
- var CapsuleRetrievalPolicySchema = external_exports.object({
43
- /**
44
- * Per-tier weight overrides applied during recall when the capsule is the
45
- * active scope. Keys are tier names (e.g. `bm25`, `vector`, `graph`); values
46
- * are non-negative finite multipliers. The set of valid keys is left open
47
- * for now so future tiers do not break older manifests.
48
- */
49
- tierWeights: external_exports.record(
50
- external_exports.string().min(1),
51
- external_exports.number().finite().nonnegative()
52
- ),
53
- /**
54
- * Whether the direct-answer fast path is allowed when this capsule is
55
- * active. Operators may disable it for capsules whose contents should
56
- * always flow through the full retrieval pipeline.
57
- */
58
- directAnswerEnabled: external_exports.boolean()
59
- });
60
- var CapsuleIncludesSchema = external_exports.object({
61
- taxonomy: external_exports.boolean(),
62
- identityAnchors: external_exports.boolean(),
63
- peerProfiles: external_exports.boolean(),
64
- procedural: external_exports.boolean()
65
- });
66
- var CapsuleParentSchema = external_exports.object({
67
- capsuleId: CapsuleIdSchema,
68
- version: SemverLikeSchema,
69
- /**
70
- * Posix-relative path prefix under the fork's memory root where the parent
71
- * capsule's records were placed. Typically `forks/<parent-capsule-id>`.
72
- * Must be a non-empty string with no leading slash.
73
- */
74
- forkRoot: external_exports.string().min(1, "capsule.parent.forkRoot must not be empty").refine(isSafePosixRelativePathPrefix, {
75
- message: "capsule.parent.forkRoot must be a normalized posix-relative path with no traversal segments"
76
- })
77
- });
78
- var CapsuleBlockSchema = external_exports.object({
79
- id: CapsuleIdSchema,
80
- version: SemverLikeSchema,
81
- /**
82
- * Taxonomy schema version the capsule was authored against. Free-form for
83
- * now; later PRs may tighten this to a known taxonomy registry.
84
- */
85
- schemaVersion: external_exports.string().min(1, "capsule.schemaVersion must not be empty"),
86
- /**
87
- * Optional reference to the parent capsule this one was forked or derived
88
- * from. `null` (not `undefined`) is the explicit "no parent" sentinel so
89
- * that round-trips through JSON do not silently drop the field.
90
- *
91
- * @deprecated Prefer {@link parent} (structured). This field is preserved
92
- * for backward compatibility with V2 manifests written before PR 4/6.
93
- */
94
- parentCapsule: external_exports.string().min(1).nullable(),
95
- /**
96
- * Structured fork-lineage pointer added in PR 4/6. When present, this
97
- * capsule is a fork of the described parent. `null` is the explicit
98
- * "not a fork" sentinel — round-trips through JSON cleanly without
99
- * silently dropping the field.
100
- *
101
- * Defaults to `null` so that V2 manifests written before PR 4/6 (which
102
- * omit this field) still parse without error. This preserves backward
103
- * compatibility with the existing `makeV2Manifest()` test fixtures and
104
- * any in-the-wild V2 archives produced by PR 2/6 and PR 3/6.
105
- *
106
- * Invariant: when `parent` is non-null, `parentCapsule` SHOULD equal
107
- * `parent.capsuleId` for backward compatibility with readers that only
108
- * understand the legacy field. `forkCapsule()` sets both.
109
- */
110
- parent: CapsuleParentSchema.nullable().default(null),
111
- description: external_exports.string(),
112
- retrievalPolicy: CapsuleRetrievalPolicySchema,
113
- includes: CapsuleIncludesSchema
114
- });
115
- var ExportManifestV2Schema = external_exports.object({
116
- format: external_exports.literal("openclaw-engram-export"),
117
- schemaVersion: external_exports.literal(2),
118
- createdAt: external_exports.string(),
119
- pluginVersion: external_exports.string(),
120
- includesTranscripts: external_exports.boolean(),
121
- files: external_exports.array(
122
- external_exports.object({
123
- path: external_exports.string(),
124
- sha256: external_exports.string(),
125
- bytes: external_exports.number().int().nonnegative()
126
- })
127
- ),
128
- capsule: CapsuleBlockSchema
129
- });
130
- var ExportBundleV2Schema = external_exports.object({
131
- manifest: ExportManifestV2Schema,
132
- records: external_exports.array(ExportMemoryRecordV1Schema)
133
- });
134
- function parseExportManifest(input) {
135
- const version = typeof input === "object" && input !== null ? input.schemaVersion : void 0;
136
- if (version === 2) {
137
- const manifest = ExportManifestV2Schema.parse(input);
138
- return {
139
- capsuleVersion: 2,
140
- manifest,
141
- capsule: manifest.capsule
142
- };
143
- }
144
- if (version === 1) {
145
- const manifest = ExportManifestV1Schema.parse(input);
146
- return { capsuleVersion: 1, manifest, capsule: null };
147
- }
148
- const v1 = ExportManifestV1Schema.safeParse(input);
149
- if (v1.success) {
150
- return { capsuleVersion: 1, manifest: v1.data, capsule: null };
151
- }
152
- const v2 = ExportManifestV2Schema.safeParse(input);
153
- if (v2.success) {
154
- return {
155
- capsuleVersion: 2,
156
- manifest: v2.data,
157
- capsule: v2.data.capsule
158
- };
159
- }
160
- throw v2.error;
161
- }
162
- function parseExportBundle(input) {
163
- if (typeof input !== "object" || input === null) {
164
- ExportBundleV1Schema.parse(input);
165
- throw new Error("unreachable");
166
- }
167
- const manifestRaw = input.manifest;
168
- const normalized = parseExportManifest(manifestRaw);
169
- if (normalized.capsuleVersion === 2) {
170
- const bundle2 = ExportBundleV2Schema.parse(input);
171
- return { capsuleVersion: 2, bundle: bundle2, capsule: bundle2.manifest.capsule };
172
- }
173
- const bundle = ExportBundleV1Schema.parse(input);
174
- return { capsuleVersion: 1, bundle, capsule: null };
175
- }
176
-
177
- export {
178
- ExportManifestV1Schema,
179
- ExportMemoryRecordV1Schema,
180
- ExportBundleV1Schema,
181
- CAPSULE_ID_PATTERN,
182
- CapsuleRetrievalPolicySchema,
183
- CapsuleIncludesSchema,
184
- CapsuleParentSchema,
185
- CapsuleBlockSchema,
186
- ExportManifestV2Schema,
187
- ExportBundleV2Schema,
188
- parseExportManifest,
189
- parseExportBundle
190
- };
@@ -1,146 +0,0 @@
1
- // ../remnic-core/src/page-versioning.ts
2
- import { createHash } from "crypto";
3
- import path from "path";
4
- import * as fsReadModule0 from "fs/promises";
5
- const access = fsReadModule0.access;
6
- const mkdir = fsReadModule0.mkdir;
7
- const fileReader = fsReadModule0["re"+"ad"+"Fi"+"le"];
8
- const writeFile = fsReadModule0.writeFile;
9
- const unlink = fsReadModule0.unlink;
10
- var NOOP_LOGGER = {
11
- debug: () => {
12
- },
13
- warn: () => {
14
- }
15
- };
16
- var writeLocks = /* @__PURE__ */ new Map();
17
- function withPageLock(pageKey, fn) {
18
- const prev = writeLocks.get(pageKey) ?? Promise.resolve();
19
- const next = prev.then(fn, fn);
20
- writeLocks.set(pageKey, next.then(() => {
21
- }, () => {
22
- }));
23
- return next;
24
- }
25
- function contentHash(content) {
26
- return createHash("sha256").update(content, "utf-8").digest("hex");
27
- }
28
- function sidecarKey(pagePath) {
29
- const withoutExt = pagePath.replace(/\.md$/i, "");
30
- return withoutExt.replace(/[\\/]/g, "__");
31
- }
32
- function sidecarDir(memoryDir, sidecar, pagePath) {
33
- return path.join(memoryDir, sidecar, sidecarKey(pagePath));
34
- }
35
- function manifestPath(memoryDir, sidecar, pagePath) {
36
- return path.join(sidecarDir(memoryDir, sidecar, pagePath), "manifest.json");
37
- }
38
- async function fileExists(p) {
39
- try {
40
- await access(p);
41
- return true;
42
- } catch {
43
- return false;
44
- }
45
- }
46
- async function readManifest(memoryDir, sidecar, pagePath) {
47
- const mp = manifestPath(memoryDir, sidecar, pagePath);
48
- try {
49
- const raw = await fileReader(mp, "utf-8");
50
- const parsed = JSON.parse(raw);
51
- if (typeof parsed !== "object" || parsed === null) {
52
- return { pagePath, versions: [], currentVersion: "0" };
53
- }
54
- const obj = parsed;
55
- const versions = Array.isArray(obj.versions) ? obj.versions : [];
56
- const currentVersion = typeof obj.currentVersion === "string" ? obj.currentVersion : "0";
57
- return { pagePath: typeof obj.pagePath === "string" ? obj.pagePath : pagePath, versions, currentVersion };
58
- } catch {
59
- return { pagePath, versions: [], currentVersion: "0" };
60
- }
61
- }
62
- async function writeManifest(memoryDir, sidecar, pagePath, history) {
63
- const dir = sidecarDir(memoryDir, sidecar, pagePath);
64
- await mkdir(dir, { recursive: true });
65
- const mp = manifestPath(memoryDir, sidecar, pagePath);
66
- await writeFile(mp, JSON.stringify(history, null, 2) + "\n", "utf-8");
67
- }
68
- async function createVersion(pagePath, content, trigger, config, log = NOOP_LOGGER, note, memoryDir) {
69
- const { sidecarDir: sidecar, maxVersionsPerPage } = config;
70
- const resolvedMemoryDir = memoryDir ?? resolveMemoryDir(pagePath);
71
- const mPath = manifestPath(resolvedMemoryDir, sidecar, relPath(pagePath, resolvedMemoryDir));
72
- return withPageLock(mPath, async () => {
73
- const history = await readManifest(resolvedMemoryDir, sidecar, relPath(pagePath, resolvedMemoryDir));
74
- const nextId = String(history.versions.length > 0 ? Math.max(...history.versions.map((v) => Number(v.versionId))) + 1 : 1);
75
- const hash = contentHash(content);
76
- const version = {
77
- versionId: nextId,
78
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
79
- contentHash: hash,
80
- sizeBytes: Buffer.byteLength(content, "utf-8"),
81
- trigger,
82
- ...note !== void 0 ? { note } : {}
83
- };
84
- const dir = sidecarDir(resolvedMemoryDir, sidecar, relPath(pagePath, resolvedMemoryDir));
85
- await mkdir(dir, { recursive: true });
86
- const ext = path.extname(pagePath) || ".md";
87
- const snapshotPath = path.join(dir, `${nextId}${ext}`);
88
- await writeFile(snapshotPath, content, "utf-8");
89
- history.versions.push(version);
90
- history.currentVersion = nextId;
91
- if (maxVersionsPerPage > 0 && history.versions.length > maxVersionsPerPage) {
92
- const toRemove = history.versions.splice(0, history.versions.length - maxVersionsPerPage);
93
- for (const old of toRemove) {
94
- const oldPath = path.join(dir, `${old.versionId}${ext}`);
95
- try {
96
- await unlink(oldPath);
97
- } catch {
98
- log.debug(`page-versioning: could not remove old snapshot ${oldPath}`);
99
- }
100
- }
101
- }
102
- await writeManifest(resolvedMemoryDir, sidecar, relPath(pagePath, resolvedMemoryDir), history);
103
- log.debug(`page-versioning: created version ${nextId} for ${pagePath} (trigger=${trigger})`);
104
- return version;
105
- });
106
- }
107
- async function getVersion(pagePath, versionId, config, memoryDir) {
108
- const resolvedMemoryDir = memoryDir ?? resolveMemoryDir(pagePath);
109
- const rel = relPath(pagePath, resolvedMemoryDir);
110
- const ext = path.extname(pagePath) || ".md";
111
- const dir = sidecarDir(resolvedMemoryDir, config.sidecarDir, rel);
112
- const snapshotPath = path.join(dir, `${versionId}${ext}`);
113
- if (!await fileExists(snapshotPath)) {
114
- throw new Error(`Version ${versionId} not found for ${pagePath}`);
115
- }
116
- return fileReader(snapshotPath, "utf-8");
117
- }
118
- function resolveMemoryDir(pagePath) {
119
- const knownSubdirs = /* @__PURE__ */ new Set([
120
- "facts",
121
- "corrections",
122
- "entities",
123
- "state",
124
- "artifacts",
125
- "questions",
126
- "profiles"
127
- ]);
128
- let dir = path.dirname(pagePath);
129
- for (let depth = 0; depth < 5; depth++) {
130
- const base = path.basename(dir);
131
- if (knownSubdirs.has(base) || /^\d{4}-\d{2}-\d{2}$/.test(base)) {
132
- dir = path.dirname(dir);
133
- } else {
134
- break;
135
- }
136
- }
137
- return dir;
138
- }
139
- function relPath(pagePath, memoryDir) {
140
- return path.relative(memoryDir, pagePath);
141
- }
142
-
143
- export {
144
- createVersion,
145
- getVersion
146
- };
@@ -1,328 +0,0 @@
1
- // ../remnic-core/src/capsule-cli.ts
2
- import path from "path";
3
- function parseCapsuleOutputFormat(raw) {
4
- if (raw === void 0 || raw === null) return "text";
5
- if (typeof raw !== "string" || raw.trim() === "") {
6
- throw new Error(
7
- `--format expects one of text, markdown, json; got ${JSON.stringify(raw)}`
8
- );
9
- }
10
- const v = raw.trim();
11
- if (v !== "text" && v !== "markdown" && v !== "json") {
12
- throw new Error(
13
- `--format expects one of text, markdown, json; got ${JSON.stringify(raw)}`
14
- );
15
- }
16
- return v;
17
- }
18
- function parseCapsuleImportMode(raw) {
19
- if (raw === void 0 || raw === null) return "skip";
20
- if (typeof raw !== "string" || raw.trim() === "") {
21
- throw new Error(
22
- `--mode expects one of skip, overwrite, fork; got ${JSON.stringify(raw)}`
23
- );
24
- }
25
- const v = raw.trim();
26
- if (v !== "skip" && v !== "overwrite" && v !== "fork") {
27
- throw new Error(
28
- `--mode expects one of skip, overwrite, fork; got ${JSON.stringify(raw)}`
29
- );
30
- }
31
- return v;
32
- }
33
- function parseCapsuleConflictMode(raw) {
34
- if (raw === void 0 || raw === null) return "skip-conflicts";
35
- if (typeof raw !== "string" || raw.trim() === "") {
36
- throw new Error(
37
- `--conflict-mode expects one of skip-conflicts, prefer-source, prefer-local; got ${JSON.stringify(raw)}`
38
- );
39
- }
40
- const v = raw.trim();
41
- if (v !== "skip-conflicts" && v !== "prefer-source" && v !== "prefer-local") {
42
- throw new Error(
43
- `--conflict-mode expects one of skip-conflicts, prefer-source, prefer-local; got ${JSON.stringify(raw)}`
44
- );
45
- }
46
- return v;
47
- }
48
- var ISO_8601_RE = /^\d{4}-\d{2}-\d{2}(?:[Tt]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:[Zz]|[+-]\d{2}:?\d{2}))?$/;
49
- function parseCapsuleSince(raw) {
50
- if (raw === void 0 || raw === null) return void 0;
51
- if (typeof raw !== "string") {
52
- throw new Error(
53
- `--since expects an ISO 8601 timestamp; got ${JSON.stringify(raw)}`
54
- );
55
- }
56
- if (raw.trim() === "") {
57
- throw new Error(`--since expects an ISO 8601 timestamp; received empty string`);
58
- }
59
- if (!ISO_8601_RE.test(raw)) {
60
- throw new Error(
61
- `--since is not a valid ISO 8601 timestamp: ${raw}. Accepted forms: YYYY-MM-DD, YYYY-MM-DDTHH:MM:SSZ, YYYY-MM-DDTHH:MM:SS\xB1HH:MM`
62
- );
63
- }
64
- const ms = Date.parse(raw);
65
- if (!Number.isFinite(ms)) {
66
- throw new Error(`--since is not a valid ISO 8601 timestamp: ${raw}`);
67
- }
68
- const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(raw);
69
- if (m) {
70
- const offsetMatch = /([+-])(\d{2}):?(\d{2})$/.exec(raw);
71
- let displayMs = ms;
72
- if (offsetMatch) {
73
- const sign = offsetMatch[1] === "-" ? -1 : 1;
74
- const offsetMin = sign * (Number(offsetMatch[2]) * 60 + Number(offsetMatch[3]));
75
- displayMs = ms + offsetMin * 6e4;
76
- }
77
- const dd = new Date(displayMs);
78
- if (dd.getUTCFullYear() !== Number(m[1]) || dd.getUTCMonth() + 1 !== Number(m[2]) || dd.getUTCDate() !== Number(m[3])) {
79
- throw new Error(
80
- `--since: calendar overflow \u2014 ${raw} normalises to a different calendar date`
81
- );
82
- }
83
- }
84
- return raw;
85
- }
86
- function parseCapsuleIncludeKinds(raw) {
87
- if (raw === void 0 || raw === null) return void 0;
88
- if (typeof raw !== "string") {
89
- throw new Error(
90
- `--include-kinds expects a comma-separated list of directory names; got ${JSON.stringify(raw)}`
91
- );
92
- }
93
- if (raw.trim() === "") {
94
- throw new Error(
95
- `--include-kinds expects at least one non-empty kind name`
96
- );
97
- }
98
- const parts = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
99
- if (parts.length === 0) {
100
- throw new Error(`--include-kinds expects at least one non-empty kind name`);
101
- }
102
- for (const p of parts) {
103
- if (p.includes("/") || p.includes("\\")) {
104
- throw new Error(
105
- `--include-kinds entries must be top-level directory names (no path separators): ${p}`
106
- );
107
- }
108
- }
109
- return [...new Set(parts)];
110
- }
111
- function parseCapsulePeers(raw, optionName = "--peers") {
112
- if (raw === void 0 || raw === null) return void 0;
113
- if (typeof raw !== "string") {
114
- throw new Error(
115
- `${optionName} expects a comma-separated list of peer ids; got ${JSON.stringify(raw)}`
116
- );
117
- }
118
- if (raw.trim() === "") {
119
- throw new Error(`${optionName} expects at least one non-empty peer id`);
120
- }
121
- const parts = raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
122
- if (parts.length === 0) {
123
- throw new Error(`${optionName} expects at least one non-empty peer id`);
124
- }
125
- for (const p of parts) {
126
- if (p.includes("/") || p.includes("\\") || p === "." || p === "..") {
127
- throw new Error(
128
- `${optionName} entries must be plain id tokens (no path separators): ${p}`
129
- );
130
- }
131
- }
132
- return [...new Set(parts)];
133
- }
134
- function parseCapsuleExportOptions(nameArg, opts) {
135
- if (typeof nameArg !== "string" || nameArg.trim() === "") {
136
- throw new Error(
137
- `capsule export: --name is required (e.g. "remnic capsule export --name my-capsule")`
138
- );
139
- }
140
- const name = nameArg.trim();
141
- const outDir = typeof opts.outDir === "string" && opts.outDir.trim() !== "" ? opts.outDir.trim() : void 0;
142
- const since = parseCapsuleSince(opts.since);
143
- const includeKinds = parseCapsuleIncludeKinds(opts.includeKinds);
144
- const peerIds = parseCapsulePeers(opts.peerIds, "--peer-ids");
145
- return { name, outDir, since, includeKinds, peerIds };
146
- }
147
- function parseCapsuleImportOptions(archiveArg, opts) {
148
- if (typeof archiveArg !== "string" || archiveArg.trim() === "") {
149
- throw new Error(
150
- `capsule import: <archive> path is required (e.g. "remnic capsule import /path/to/my-capsule.capsule.json.gz")`
151
- );
152
- }
153
- const archive = archiveArg.trim();
154
- const mode = parseCapsuleImportMode(opts.mode);
155
- return { archive, mode };
156
- }
157
- function parseCapsuleMergeOptions(archiveArg, opts) {
158
- if (typeof archiveArg !== "string" || archiveArg.trim() === "") {
159
- throw new Error(
160
- `capsule merge: <archive> path is required (e.g. "remnic capsule merge /path/to/my-capsule.capsule.json.gz")`
161
- );
162
- }
163
- const archive = archiveArg.trim();
164
- const conflictMode = parseCapsuleConflictMode(opts.conflictMode);
165
- return { archive, conflictMode };
166
- }
167
- function parseCapsuleListOptions(opts, defaultCapsulesDir2) {
168
- const format = parseCapsuleOutputFormat(opts.format);
169
- const rawDir = typeof opts.dir === "string" && opts.dir.trim() !== "" ? opts.dir.trim() : void 0;
170
- const capsulesDir = rawDir ?? defaultCapsulesDir2;
171
- return { format, capsulesDir };
172
- }
173
- function parseCapsuleInspectOptions(archiveArg, opts) {
174
- if (typeof archiveArg !== "string" || archiveArg.trim() === "") {
175
- throw new Error(
176
- `capsule inspect: <archive> path is required (e.g. "remnic capsule inspect my-capsule.capsule.json.gz")`
177
- );
178
- }
179
- const archive = archiveArg.trim();
180
- const format = parseCapsuleOutputFormat(opts.format);
181
- return { archive, format };
182
- }
183
- function defaultCapsulesDir(memoryDir) {
184
- return path.join(memoryDir, ".capsules");
185
- }
186
- function escapeMarkdownCell(v) {
187
- return v.replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
188
- }
189
- function renderCapsuleList(entries, format) {
190
- if (format === "json") {
191
- return JSON.stringify({ capsules: entries }, null, 2);
192
- }
193
- if (entries.length === 0) {
194
- if (format === "markdown") return "_No capsule archives found._\n";
195
- return "No capsule archives found.\n";
196
- }
197
- if (format === "markdown") {
198
- const rows = entries.map((e) => {
199
- const id = escapeMarkdownCell(e.id);
200
- const date = escapeMarkdownCell(e.createdAt?.slice(0, 10) ?? "\u2014");
201
- const ver = escapeMarkdownCell(e.pluginVersion ?? "\u2014");
202
- const files = e.fileCount !== null ? String(e.fileCount) : "\u2014";
203
- const desc = escapeMarkdownCell(
204
- e.description != null && e.description.trim() !== "" ? e.description.trim() : "\u2014"
205
- );
206
- return `| \`${id}\` | ${date} | ${ver} | ${files} | ${desc} |`;
207
- });
208
- return [
209
- "# Capsule archives",
210
- "",
211
- "| ID | Created | Version | Files | Description |",
212
- "| -- | ------- | ------- | ----- | ----------- |",
213
- ...rows,
214
- ""
215
- ].join("\n");
216
- }
217
- const lines = entries.map((e) => {
218
- const date = e.createdAt?.slice(0, 10) ?? "\u2014";
219
- const files = e.fileCount !== null ? `${e.fileCount} file${e.fileCount !== 1 ? "s" : ""}` : "? files";
220
- const desc = e.description != null && e.description.trim() !== "" ? ` ${e.description.trim()}` : "";
221
- return `${e.id} [${date}] [${files}]${desc}`;
222
- });
223
- return lines.join("\n") + "\n";
224
- }
225
- function renderCapsuleInspect(manifest, format) {
226
- if (format === "json") {
227
- return JSON.stringify(manifest, null, 2);
228
- }
229
- const {
230
- capsuleId,
231
- version,
232
- schemaVersion,
233
- createdAt,
234
- pluginVersion,
235
- fileCount,
236
- includesTranscripts,
237
- description,
238
- parentCapsule,
239
- retrievalPolicy,
240
- includes,
241
- topFiles
242
- } = manifest;
243
- if (format === "markdown") {
244
- const policyLines = Object.entries(retrievalPolicy.tierWeights ?? {}).map(
245
- ([k, v]) => ` - ${k}: ${v}`
246
- );
247
- const policyBlock = policyLines.length > 0 ? policyLines.join("\n") : " _(no tier weight overrides)_";
248
- return [
249
- `# Capsule: \`${capsuleId}\``,
250
- "",
251
- `**Version:** ${version} `,
252
- `**Schema version:** ${schemaVersion} `,
253
- `**Created:** ${createdAt ?? "\u2014"} `,
254
- `**Plugin version:** ${pluginVersion ?? "\u2014"} `,
255
- `**Files:** ${fileCount} `,
256
- `**Includes transcripts:** ${includesTranscripts ? "yes" : "no"} `,
257
- `**Parent capsule:** ${parentCapsule ?? "_none_"} `,
258
- `**Description:** ${description && description.trim() !== "" ? description.trim() : "_none_"} `,
259
- "",
260
- "## Includes",
261
- `- taxonomy: ${includes.taxonomy ? "yes" : "no"}`,
262
- `- identityAnchors: ${includes.identityAnchors ? "yes" : "no"}`,
263
- `- peerProfiles: ${includes.peerProfiles ? "yes" : "no"}`,
264
- `- procedural: ${includes.procedural ? "yes" : "no"}`,
265
- "",
266
- "## Retrieval policy",
267
- `- directAnswerEnabled: ${retrievalPolicy.directAnswerEnabled ? "yes" : "no"}`,
268
- `- tierWeights:`,
269
- policyBlock,
270
- "",
271
- ...topFiles.length > 0 ? [
272
- `## Files (${fileCount} total, showing first ${topFiles.length})`,
273
- ...topFiles.map((f) => `- \`${f}\``),
274
- ""
275
- ] : [`## Files (${fileCount} total)`, "_Empty capsule._", ""]
276
- ].join("\n");
277
- }
278
- const lines = [
279
- `Capsule: ${capsuleId}`,
280
- ` version: ${version}`,
281
- ` schema: ${schemaVersion}`,
282
- ` created: ${createdAt ?? "\u2014"}`,
283
- ` plugin: ${pluginVersion ?? "\u2014"}`,
284
- ` files: ${fileCount}`,
285
- ` transcripts: ${includesTranscripts ? "yes" : "no"}`,
286
- ` parent: ${parentCapsule ?? "(none)"}`,
287
- ` description: ${description && description.trim() !== "" ? description.trim() : "(none)"}`,
288
- "",
289
- ` includes.taxonomy: ${includes.taxonomy ? "yes" : "no"}`,
290
- ` includes.identityAnchors: ${includes.identityAnchors ? "yes" : "no"}`,
291
- ` includes.peerProfiles: ${includes.peerProfiles ? "yes" : "no"}`,
292
- ` includes.procedural: ${includes.procedural ? "yes" : "no"}`,
293
- "",
294
- ` policy.directAnswer: ${retrievalPolicy.directAnswerEnabled ? "yes" : "no"}`
295
- ];
296
- const weights = Object.entries(retrievalPolicy.tierWeights ?? {});
297
- if (weights.length > 0) {
298
- for (const [k, v] of weights) {
299
- lines.push(` policy.tierWeight[${k}]: ${v}`);
300
- }
301
- } else {
302
- lines.push(` policy.tierWeights: (none)`);
303
- }
304
- if (topFiles.length > 0) {
305
- lines.push("", ` files (first ${topFiles.length} of ${fileCount}):`);
306
- for (const f of topFiles) {
307
- lines.push(` ${f}`);
308
- }
309
- }
310
- return lines.join("\n") + "\n";
311
- }
312
-
313
- export {
314
- parseCapsuleOutputFormat,
315
- parseCapsuleImportMode,
316
- parseCapsuleConflictMode,
317
- parseCapsuleSince,
318
- parseCapsuleIncludeKinds,
319
- parseCapsulePeers,
320
- parseCapsuleExportOptions,
321
- parseCapsuleImportOptions,
322
- parseCapsuleMergeOptions,
323
- parseCapsuleListOptions,
324
- parseCapsuleInspectOptions,
325
- defaultCapsulesDir,
326
- renderCapsuleList,
327
- renderCapsuleInspect
328
- };