@promptowl/contextnest-cli 0.1.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.
Files changed (3) hide show
  1. package/LICENSE +190 -0
  2. package/dist/index.js +548 -0
  3. package/package.json +29 -0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 PromptOwl, Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/dist/index.js ADDED
@@ -0,0 +1,548 @@
1
+ #!/usr/bin/env node
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/index.ts
10
+ import { Command } from "commander";
11
+ import chalk from "chalk";
12
+ import {
13
+ NestStorage,
14
+ validateDocument,
15
+ parseSelector,
16
+ evaluate,
17
+ Resolver,
18
+ PackLoader,
19
+ VersionManager,
20
+ CheckpointManager,
21
+ ContextInjector,
22
+ publishDocument,
23
+ generateContextYaml,
24
+ generateIndexMd,
25
+ verifyDocumentChain,
26
+ verifyCheckpointChain,
27
+ detectCycles,
28
+ serializeDocument,
29
+ parseUri
30
+ } from "@promptowl/contextnest-engine";
31
+ var program = new Command();
32
+ program.name("ctx").description("Context Nest CLI \u2014 manage structured, versioned context vaults").version("0.1.0");
33
+ function getVaultRoot() {
34
+ return process.env.CONTEXTNEST_VAULT_PATH || process.cwd();
35
+ }
36
+ function getStorage() {
37
+ return new NestStorage(getVaultRoot());
38
+ }
39
+ async function regenerateIndex(storage) {
40
+ const docs = await storage.discoverDocuments();
41
+ const config = await storage.readConfig();
42
+ const checkpointHistory = await storage.readCheckpointHistory();
43
+ const latestCheckpoint = checkpointHistory?.checkpoints?.at(-1) ?? null;
44
+ const published = docs.filter((d) => d.frontmatter.status === "published");
45
+ const contextYaml = generateContextYaml(published, config, latestCheckpoint);
46
+ await storage.writeContextYaml(contextYaml);
47
+ const folders = /* @__PURE__ */ new Map();
48
+ for (const doc of docs) {
49
+ const parts = doc.id.split("/");
50
+ const folder = parts.length > 1 ? parts.slice(0, -1).join("/") : ".";
51
+ if (!folders.has(folder)) folders.set(folder, []);
52
+ folders.get(folder).push(doc);
53
+ }
54
+ for (const [folder, folderDocs] of folders) {
55
+ if (folder === ".") continue;
56
+ const title = folder.split("/").pop().replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
57
+ const indexMd = generateIndexMd(folder, title, folderDocs);
58
+ await storage.writeIndexMd(folder, indexMd);
59
+ }
60
+ }
61
+ program.command("init").description("Initialize a new Context Nest vault").option("-l, --layout <mode>", "Layout mode: structured or obsidian", "structured").option("-n, --name <name>", "Vault name", "My Context Nest").action(async (opts) => {
62
+ const storage = getStorage();
63
+ await storage.init(opts.name, opts.layout);
64
+ console.log(chalk.green(`Initialized ${opts.layout} vault: ${getVaultRoot()}`));
65
+ });
66
+ program.command("add <path>").description("Create a new document with frontmatter template").option("-t, --type <type>", "Node type", "document").option("--title <title>", "Document title").option("--tags <tags>", "Comma-separated tags").option("--body <body>", "Markdown body content").action(async (path, opts) => {
67
+ const storage = getStorage();
68
+ const id = path.replace(/\.md$/, "");
69
+ const title = opts.title || id.split("/").pop().replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
70
+ const tagList = opts.tags ? opts.tags.split(",").map((t) => t.trim()).map((t) => t.startsWith("#") ? t : `#${t}`) : void 0;
71
+ const frontmatter = {
72
+ title,
73
+ type: opts.type,
74
+ status: "draft",
75
+ version: 1,
76
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
77
+ ...tagList ? { tags: tagList } : {}
78
+ };
79
+ const node = {
80
+ id,
81
+ filePath: "",
82
+ frontmatter,
83
+ body: opts.body ? `
84
+ ${opts.body}
85
+ ` : `
86
+ # ${title}
87
+
88
+ `,
89
+ rawContent: ""
90
+ };
91
+ const content = serializeDocument(node);
92
+ await storage.writeDocument(id, content);
93
+ const result = await publishDocument(storage, id, {
94
+ editedBy: "cli@contextnest.local",
95
+ note: "Created via CLI"
96
+ });
97
+ await regenerateIndex(storage);
98
+ console.log(chalk.green(`Created and published ${id}.md`));
99
+ console.log(` Version: ${result.node.frontmatter.version}`);
100
+ console.log(` Checkpoint: ${result.checkpointNumber}`);
101
+ });
102
+ program.command("validate [path]").description("Validate documents against the Context Nest specification").option("--json", "Output as JSON").action(async (path, opts) => {
103
+ const storage = getStorage();
104
+ let docs;
105
+ if (path) {
106
+ const id = path.replace(/\.md$/, "");
107
+ docs = [await storage.readDocument(id)];
108
+ } else {
109
+ docs = await storage.discoverDocuments();
110
+ }
111
+ let hasErrors = false;
112
+ const allErrors = [];
113
+ for (const doc of docs) {
114
+ const result = validateDocument(doc);
115
+ if (!result.valid) {
116
+ hasErrors = true;
117
+ allErrors.push({ path: doc.id, errors: result.errors });
118
+ if (!opts.json) {
119
+ console.log(chalk.red(`\u2717 ${doc.id}`));
120
+ for (const err of result.errors) {
121
+ console.log(` Rule ${err.rule}: ${err.message}${err.field ? ` (${err.field})` : ""}`);
122
+ }
123
+ }
124
+ } else if (!opts.json) {
125
+ console.log(chalk.green(`\u2713 ${doc.id}`));
126
+ }
127
+ }
128
+ const sourceNodes = docs.filter((d) => d.frontmatter.type === "source");
129
+ if (sourceNodes.length > 0) {
130
+ const cycle = detectCycles(sourceNodes);
131
+ if (cycle) {
132
+ hasErrors = true;
133
+ const err = { path: "sources", errors: [{ rule: 15, message: `Circular dependency: ${cycle.join(" \u2192 ")}` }] };
134
+ allErrors.push(err);
135
+ if (!opts.json) {
136
+ console.log(chalk.red(`\u2717 Circular dependency detected: ${cycle.join(" \u2192 ")}`));
137
+ }
138
+ }
139
+ }
140
+ if (opts.json) {
141
+ console.log(JSON.stringify({ valid: !hasErrors, errors: allErrors }, null, 2));
142
+ } else {
143
+ console.log(
144
+ hasErrors ? chalk.red(`
145
+ Validation failed with errors`) : chalk.green(`
146
+ All ${docs.length} documents valid`)
147
+ );
148
+ }
149
+ if (hasErrors) process.exit(1);
150
+ });
151
+ program.command("resolve <selector>").description("Execute a selector query and list matching documents").option("--json", "Output as JSON").action(async (selector, opts) => {
152
+ const storage = getStorage();
153
+ const docs = await storage.discoverDocuments();
154
+ const packs = await storage.readPacks();
155
+ const resolver = new Resolver({ documents: docs });
156
+ const packLoader = new PackLoader(packs);
157
+ const ast = parseSelector(selector);
158
+ const results = await evaluate(ast, {
159
+ resolver,
160
+ packLoader: (id) => packLoader.get(id)
161
+ });
162
+ if (opts.json) {
163
+ console.log(
164
+ JSON.stringify(
165
+ results.map((d) => ({
166
+ id: d.id,
167
+ title: d.frontmatter.title,
168
+ type: d.frontmatter.type || "document",
169
+ status: d.frontmatter.status || "draft",
170
+ tags: d.frontmatter.tags
171
+ })),
172
+ null,
173
+ 2
174
+ )
175
+ );
176
+ } else {
177
+ if (results.length === 0) {
178
+ console.log(chalk.yellow("No documents matched the selector."));
179
+ } else {
180
+ console.log(chalk.bold(`${results.length} document(s) matched:
181
+ `));
182
+ for (const doc of results) {
183
+ const type = doc.frontmatter.type || "document";
184
+ const status = doc.frontmatter.status || "draft";
185
+ const statusColor = status === "published" ? chalk.green : chalk.yellow;
186
+ console.log(` ${chalk.cyan(doc.id)} [${type}] ${statusColor(status)}`);
187
+ console.log(` ${doc.frontmatter.title}`);
188
+ }
189
+ }
190
+ }
191
+ });
192
+ program.command("publish <path>").description("Publish a document (bump version, create checkpoint)").option("-a, --author <email>", "Author email", "cli@contextnest.local").option("-m, --message <note>", "Version note").action(async (path, opts) => {
193
+ const storage = getStorage();
194
+ const id = path.replace(/\.md$/, "");
195
+ const result = await publishDocument(storage, id, {
196
+ editedBy: opts.author,
197
+ note: opts.message
198
+ });
199
+ await regenerateIndex(storage);
200
+ console.log(chalk.green(`Published ${id}`));
201
+ console.log(` Version: ${result.node.frontmatter.version}`);
202
+ console.log(` Checkpoint: ${result.checkpointNumber}`);
203
+ console.log(` Chain hash: ${result.versionEntry.chain_hash}`);
204
+ });
205
+ program.command("history <path>").description("Show version history for a document").option("--json", "Output as JSON").action(async (path, opts) => {
206
+ const storage = getStorage();
207
+ const id = path.replace(/\.md$/, "");
208
+ const vm = new VersionManager(storage);
209
+ const history = await vm.getHistory(id);
210
+ if (!history) {
211
+ console.log(chalk.yellow(`No version history for ${id}`));
212
+ return;
213
+ }
214
+ if (opts.json) {
215
+ console.log(JSON.stringify(history, null, 2));
216
+ } else {
217
+ console.log(chalk.bold(`Version history for ${id}:
218
+ `));
219
+ for (const entry of history.versions) {
220
+ const keyframe = entry.keyframe ? chalk.blue(" [keyframe]") : "";
221
+ const published = entry.published_at ? chalk.green(" published") : chalk.yellow(" draft");
222
+ console.log(` v${entry.version}${keyframe}${published}`);
223
+ console.log(` By: ${entry.edited_by} at ${entry.edited_at}`);
224
+ if (entry.note) console.log(` Note: ${entry.note}`);
225
+ }
226
+ }
227
+ });
228
+ program.command("reconstruct <path> <version>").description("Reconstruct a specific version of a document").action(async (path, version) => {
229
+ const storage = getStorage();
230
+ const id = path.replace(/\.md$/, "");
231
+ const vm = new VersionManager(storage);
232
+ const content = await vm.reconstructVersion(id, parseInt(version, 10));
233
+ console.log(content);
234
+ });
235
+ program.command("verify").description("Verify integrity of all hash chains").option("--json", "Output as JSON").action(async (opts) => {
236
+ const storage = getStorage();
237
+ const allHistories = await storage.findAllHistories();
238
+ const checkpointHistory = await storage.readCheckpointHistory();
239
+ let totalErrors = 0;
240
+ const allReportErrors = [];
241
+ for (const [docId, history] of allHistories) {
242
+ const report = verifyDocumentChain(docId, history, (version) => {
243
+ const fs = __require("fs");
244
+ const pathMod = __require("path");
245
+ const docName = pathMod.basename(docId);
246
+ const docDir = pathMod.dirname(docId);
247
+ const keyframePath = pathMod.join(
248
+ storage.root,
249
+ docDir,
250
+ ".versions",
251
+ docName,
252
+ `v${version}.md`
253
+ );
254
+ try {
255
+ return fs.readFileSync(keyframePath, "utf-8");
256
+ } catch {
257
+ return null;
258
+ }
259
+ });
260
+ if (!report.valid) {
261
+ totalErrors += report.errors.length;
262
+ allReportErrors.push(...report.errors);
263
+ if (!opts.json) {
264
+ console.log(chalk.red(`\u2717 ${docId}: ${report.errors.length} error(s)`));
265
+ for (const err of report.errors) {
266
+ console.log(` ${err.type} at version ${err.version}`);
267
+ }
268
+ }
269
+ } else if (!opts.json) {
270
+ console.log(chalk.green(`\u2713 ${docId}`));
271
+ }
272
+ }
273
+ if (checkpointHistory) {
274
+ const report = verifyCheckpointChain(
275
+ checkpointHistory.checkpoints,
276
+ allHistories
277
+ );
278
+ if (!report.valid) {
279
+ totalErrors += report.errors.length;
280
+ allReportErrors.push(...report.errors);
281
+ if (!opts.json) {
282
+ console.log(chalk.red(`\u2717 Checkpoint chain: ${report.errors.length} error(s)`));
283
+ for (const err of report.errors) {
284
+ console.log(` ${err.type} at checkpoint ${err.checkpoint}`);
285
+ }
286
+ }
287
+ } else if (!opts.json) {
288
+ console.log(chalk.green(`\u2713 Checkpoint chain`));
289
+ }
290
+ }
291
+ if (opts.json) {
292
+ console.log(JSON.stringify({ valid: totalErrors === 0, errors: allReportErrors }, null, 2));
293
+ } else {
294
+ console.log(
295
+ totalErrors === 0 ? chalk.green("\nAll integrity checks passed") : chalk.red(`
296
+ ${totalErrors} integrity error(s) found`)
297
+ );
298
+ }
299
+ if (totalErrors > 0) process.exit(1);
300
+ });
301
+ program.command("index").description("Regenerate context.yaml and INDEX.md files").action(async () => {
302
+ const storage = getStorage();
303
+ const docs = await storage.discoverDocuments();
304
+ const config = await storage.readConfig();
305
+ const checkpointHistory = await storage.readCheckpointHistory();
306
+ const latestCheckpoint = checkpointHistory?.checkpoints?.at(-1) ?? null;
307
+ const published = docs.filter((d) => d.frontmatter.status === "published");
308
+ const contextYaml = generateContextYaml(published, config, latestCheckpoint);
309
+ await storage.writeContextYaml(contextYaml);
310
+ console.log(chalk.green("Generated context.yaml"));
311
+ const folders = /* @__PURE__ */ new Map();
312
+ for (const doc of docs) {
313
+ const parts = doc.id.split("/");
314
+ const folder = parts.length > 1 ? parts.slice(0, -1).join("/") : ".";
315
+ if (!folders.has(folder)) folders.set(folder, []);
316
+ folders.get(folder).push(doc);
317
+ }
318
+ for (const [folder, folderDocs] of folders) {
319
+ if (folder === ".") continue;
320
+ const title = folder.split("/").pop().replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
321
+ const indexMd = generateIndexMd(folder, title, folderDocs);
322
+ await storage.writeIndexMd(folder, indexMd);
323
+ console.log(chalk.green(`Generated ${folder}/INDEX.md`));
324
+ }
325
+ });
326
+ program.command("inject <selector>").description("Resolve and return context for injection into an AI agent").option("--json", "Output as JSON").action(async (selector, opts) => {
327
+ const storage = getStorage();
328
+ const docs = await storage.discoverDocuments();
329
+ const packs = await storage.readPacks();
330
+ const checkpointHistory = await storage.readCheckpointHistory();
331
+ const currentCheckpoint = checkpointHistory?.checkpoints?.at(-1)?.checkpoint ?? 0;
332
+ const resolver = new Resolver({ documents: docs });
333
+ const packLoader = new PackLoader(packs);
334
+ const injector = new ContextInjector({ resolver, packLoader, currentCheckpoint });
335
+ const result = await injector.inject(selector);
336
+ if (opts.json) {
337
+ console.log(
338
+ JSON.stringify(
339
+ {
340
+ documents: result.documents.map((d) => ({
341
+ id: d.id,
342
+ title: d.frontmatter.title,
343
+ body: d.body
344
+ })),
345
+ sourceNodes: result.sourceNodes.map((d) => ({
346
+ id: d.id,
347
+ title: d.frontmatter.title,
348
+ source: d.frontmatter.source,
349
+ body: d.body
350
+ })),
351
+ traceCount: result.traces.length
352
+ },
353
+ null,
354
+ 2
355
+ )
356
+ );
357
+ } else {
358
+ console.log(chalk.bold("Documents:"));
359
+ for (const doc of result.documents) {
360
+ console.log(` ${chalk.cyan(doc.id)}: ${doc.frontmatter.title}`);
361
+ }
362
+ if (result.sourceNodes.length > 0) {
363
+ console.log(chalk.bold("\nSource Nodes (hydration order):"));
364
+ for (const doc of result.sourceNodes) {
365
+ console.log(` ${chalk.magenta(doc.id)}: ${doc.frontmatter.title}`);
366
+ console.log(` Transport: ${doc.frontmatter.source?.transport}, Server: ${doc.frontmatter.source?.server || "n/a"}`);
367
+ }
368
+ }
369
+ console.log(`
370
+ ${result.traces.length} trace entries recorded.`);
371
+ }
372
+ });
373
+ program.command("list").description("List all documents with optional filters").option("-t, --type <type>", "Filter by node type").option("-s, --status <status>", "Filter by status (draft/published)").option("--tag <tag>", "Filter by tag").option("--json", "Output as JSON").action(async (opts) => {
374
+ const storage = getStorage();
375
+ let docs = await storage.discoverDocuments();
376
+ if (opts.type) docs = docs.filter((d) => (d.frontmatter.type || "document") === opts.type);
377
+ if (opts.status) docs = docs.filter((d) => (d.frontmatter.status || "draft") === opts.status);
378
+ if (opts.tag) {
379
+ const normalizedTag = opts.tag.startsWith("#") ? opts.tag : `#${opts.tag}`;
380
+ docs = docs.filter((d) => d.frontmatter.tags?.includes(normalizedTag));
381
+ }
382
+ if (opts.json) {
383
+ console.log(
384
+ JSON.stringify(
385
+ docs.map((d) => ({
386
+ id: d.id,
387
+ title: d.frontmatter.title,
388
+ type: d.frontmatter.type || "document",
389
+ status: d.frontmatter.status || "draft",
390
+ tags: d.frontmatter.tags
391
+ })),
392
+ null,
393
+ 2
394
+ )
395
+ );
396
+ } else {
397
+ if (docs.length === 0) {
398
+ console.log(chalk.yellow("No documents found."));
399
+ } else {
400
+ console.log(chalk.bold(`${docs.length} document(s):
401
+ `));
402
+ for (const doc of docs) {
403
+ const type = doc.frontmatter.type || "document";
404
+ const status = doc.frontmatter.status || "draft";
405
+ const statusColor = status === "published" ? chalk.green : chalk.yellow;
406
+ console.log(` ${chalk.cyan(doc.id)} [${type}] ${statusColor(status)}`);
407
+ console.log(` ${doc.frontmatter.title}`);
408
+ }
409
+ }
410
+ }
411
+ });
412
+ program.command("update <path>").description("Update a document's frontmatter and/or body, then auto-publish").option("--title <title>", "New title").option("--tags <tags>", "New tags (comma-separated, replaces existing)").option("--body <body>", "New markdown body content").action(async (path, opts) => {
413
+ const storage = getStorage();
414
+ const id = path.replace(/\.md$/, "");
415
+ const doc = await storage.readDocument(id);
416
+ if (opts.title !== void 0) doc.frontmatter.title = opts.title;
417
+ if (opts.tags !== void 0) {
418
+ doc.frontmatter.tags = opts.tags.split(",").map((t) => t.trim()).map((t) => t.startsWith("#") ? t : `#${t}`);
419
+ }
420
+ doc.frontmatter.updated_at = (/* @__PURE__ */ new Date()).toISOString();
421
+ if (opts.body !== void 0) {
422
+ doc.body = `
423
+ ${opts.body}
424
+ `;
425
+ }
426
+ const validation = validateDocument(doc);
427
+ if (!validation.valid) {
428
+ console.log(chalk.red("Validation failed:"));
429
+ for (const err of validation.errors) {
430
+ console.log(` Rule ${err.rule}: ${err.message}${err.field ? ` (${err.field})` : ""}`);
431
+ }
432
+ process.exit(1);
433
+ }
434
+ const content = serializeDocument(doc);
435
+ await storage.writeDocument(id, content);
436
+ const result = await publishDocument(storage, id, {
437
+ editedBy: "cli@contextnest.local",
438
+ note: "Updated via CLI"
439
+ });
440
+ await regenerateIndex(storage);
441
+ console.log(chalk.green(`Updated and published ${id}`));
442
+ console.log(` Version: ${result.node.frontmatter.version}`);
443
+ console.log(` Checkpoint: ${result.checkpointNumber}`);
444
+ });
445
+ program.command("delete <path>").description("Delete a document and its version history").action(async (path) => {
446
+ const storage = getStorage();
447
+ const id = path.replace(/\.md$/, "");
448
+ const doc = await storage.readDocument(id);
449
+ await storage.deleteDocument(id);
450
+ await regenerateIndex(storage);
451
+ console.log(chalk.green(`Deleted ${id} (${doc.frontmatter.title})`));
452
+ });
453
+ program.command("search <query>").description("Full-text search across vault documents").option("--json", "Output as JSON").action(async (query, opts) => {
454
+ const storage = getStorage();
455
+ const docs = await storage.discoverDocuments();
456
+ const resolver = new Resolver({ documents: docs });
457
+ const uri = parseUri(`contextnest://search/${query.replace(/\s+/g, "+")}`);
458
+ const results = await resolver.resolve(uri);
459
+ if (opts.json) {
460
+ console.log(
461
+ JSON.stringify(
462
+ results.map((d) => ({
463
+ id: d.id,
464
+ title: d.frontmatter.title,
465
+ description: d.frontmatter.description,
466
+ type: d.frontmatter.type || "document"
467
+ })),
468
+ null,
469
+ 2
470
+ )
471
+ );
472
+ } else {
473
+ if (results.length === 0) {
474
+ console.log(chalk.yellow("No results found."));
475
+ } else {
476
+ console.log(chalk.bold(`${results.length} result(s):
477
+ `));
478
+ for (const doc of results) {
479
+ console.log(` ${chalk.cyan(doc.id)}: ${doc.frontmatter.title}`);
480
+ }
481
+ }
482
+ }
483
+ });
484
+ var packCmd = program.command("pack").description("Pack operations");
485
+ packCmd.command("list").description("List all context packs").option("--json", "Output as JSON").action(async (opts) => {
486
+ const storage = getStorage();
487
+ const packs = await storage.readPacks();
488
+ if (opts.json) {
489
+ console.log(JSON.stringify(packs, null, 2));
490
+ } else {
491
+ if (packs.length === 0) {
492
+ console.log(chalk.yellow("No packs found."));
493
+ } else {
494
+ for (const pack of packs) {
495
+ console.log(` ${chalk.cyan(`pack:${pack.id}`)} \u2014 ${pack.label}`);
496
+ if (pack.description) console.log(` ${pack.description}`);
497
+ }
498
+ }
499
+ }
500
+ });
501
+ packCmd.command("show <id>").description("Show pack details and resolved documents").action(async (id) => {
502
+ const storage = getStorage();
503
+ const packs = await storage.readPacks();
504
+ const packLoader = new PackLoader(packs);
505
+ const pack = packLoader.get(id);
506
+ if (!pack) {
507
+ console.log(chalk.red(`Pack "${id}" not found`));
508
+ process.exit(1);
509
+ }
510
+ console.log(chalk.bold(pack.label));
511
+ if (pack.description) console.log(pack.description);
512
+ if (pack.query) console.log(`
513
+ Query: ${chalk.cyan(pack.query)}`);
514
+ if (pack.includes?.length) console.log(`Includes: ${pack.includes.join(", ")}`);
515
+ if (pack.excludes?.length) console.log(`Excludes: ${pack.excludes.join(", ")}`);
516
+ if (pack.agent_instructions) {
517
+ console.log(chalk.bold("\nAgent Instructions:"));
518
+ console.log(pack.agent_instructions);
519
+ }
520
+ });
521
+ var cpCmd = program.command("checkpoint").description("Checkpoint operations");
522
+ cpCmd.command("list").description("List all checkpoints").option("--json", "Output as JSON").option("-n, --limit <n>", "Number of recent checkpoints to show", "10").action(async (opts) => {
523
+ const storage = getStorage();
524
+ const cm = new CheckpointManager(storage);
525
+ const history = await cm.loadCheckpointHistory();
526
+ if (!history || history.checkpoints.length === 0) {
527
+ console.log(chalk.yellow("No checkpoints found."));
528
+ return;
529
+ }
530
+ const limit = parseInt(opts.limit, 10);
531
+ const checkpoints = history.checkpoints.slice(-limit);
532
+ if (opts.json) {
533
+ console.log(JSON.stringify(checkpoints, null, 2));
534
+ } else {
535
+ for (const cp of checkpoints) {
536
+ console.log(` Checkpoint ${chalk.bold(String(cp.checkpoint))} \u2014 ${cp.at}`);
537
+ console.log(` Triggered by: ${cp.triggered_by}`);
538
+ console.log(` Documents: ${Object.keys(cp.document_versions).length}`);
539
+ }
540
+ }
541
+ });
542
+ cpCmd.command("rebuild").description("Rebuild checkpoint history from per-document histories").action(async () => {
543
+ const storage = getStorage();
544
+ const cm = new CheckpointManager(storage);
545
+ const history = await cm.rebuildCheckpointHistory();
546
+ console.log(chalk.green(`Rebuilt ${history.checkpoints.length} checkpoints`));
547
+ });
548
+ program.parse();
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@promptowl/contextnest-cli",
3
+ "version": "0.1.0",
4
+ "description": "Command-line tool for Context Nest vault operations",
5
+ "type": "module",
6
+ "bin": {
7
+ "ctx": "dist/index.js",
8
+ "contextnest": "dist/index.js"
9
+ },
10
+ "scripts": {
11
+ "build": "tsup",
12
+ "clean": "rm -rf dist",
13
+ "test": "vitest run",
14
+ "test:watch": "vitest"
15
+ },
16
+ "dependencies": {
17
+ "@promptowl/contextnest-engine": "workspace:*",
18
+ "commander": "^13.0.0",
19
+ "chalk": "^5.4.0",
20
+ "cli-table3": "^0.6.5"
21
+ },
22
+ "devDependencies": {
23
+ "typescript": "^5.7.0",
24
+ "tsup": "^8.0.0",
25
+ "vitest": "^3.0.0"
26
+ },
27
+ "files": ["dist"],
28
+ "license": "Apache-2.0"
29
+ }