@crewx/doc 0.1.9-rc.139 → 0.1.9-rc.140

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/cli.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  export declare function main(inputArgs?: string[]): Promise<void>;
3
- //# sourceMappingURL=cli.d.ts.map
3
+
package/dist/cli.js CHANGED
@@ -1,76 +1,6 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || (function () {
20
- var ownKeys = function(o) {
21
- ownKeys = Object.getOwnPropertyNames || function (o) {
22
- var ar = [];
23
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
- return ar;
25
- };
26
- return ownKeys(o);
27
- };
28
- return function (mod) {
29
- if (mod && mod.__esModule) return mod;
30
- var result = {};
31
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
- __setModuleDefault(result, mod);
33
- return result;
34
- };
35
- })();
36
- Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.main = main;
38
- const fs = __importStar(require("fs"));
39
- const path = __importStar(require("path"));
40
- const engine_1 = require("./src/engine");
41
- const indexer_1 = require("./src/indexer");
42
- const okf_1 = require("./src/okf");
43
- const knowledge_core_1 = require("@crewx/knowledge-core");
44
- let PKG_VERSION = 'unknown';
45
- try {
46
- const _pkgPath = fs.existsSync(path.join(__dirname, 'package.json'))
47
- ? path.join(__dirname, 'package.json')
48
- : path.join(__dirname, '..', 'package.json');
49
- const _pkg = JSON.parse(fs.readFileSync(_pkgPath, 'utf-8'));
50
- if (_pkg?.version)
51
- PKG_VERSION = String(_pkg.version);
52
- }
53
- catch { }
54
- async function loadTracer() {
55
- try {
56
- return await Promise.resolve().then(() => __importStar(require('@crewx/shared/skill-tracer')));
57
- }
58
- catch {
59
- return null;
60
- }
61
- }
62
- function showDetailedUsage() {
63
- const skillMd = path.join(__dirname, '..', 'SKILL.md');
64
- if (fs.existsSync(skillMd)) {
65
- process.stdout.write(fs.readFileSync(skillMd, 'utf-8'));
66
- }
67
- else {
68
- console.log('No SKILL.md found. Use --help for usage.');
69
- }
70
- }
71
- function printUsage(noColor) {
72
- console.log(`
73
- @crewx/doc@${PKG_VERSION} - Document management and knowledge tools
2
+ "use strict";var L=exports&&exports.__createBinding||(Object.create?(function(c,e,n,s){if(s===void 0)s=n;var g=Object.getOwnPropertyDescriptor(e,n);if(!g||("get"in g?!e.__esModule:g.writable||g.configurable)){g={enumerable:true,get:function(){return e[n]}}}Object.defineProperty(c,s,g)}):(function(c,e,n,s){if(s===void 0)s=n;c[s]=e[n]}));var B=exports&&exports.__setModuleDefault||(Object.create?(function(c,e){Object.defineProperty(c,"default",{enumerable:true,value:e})}):function(c,e){c["default"]=e});var q=exports&&exports.__importStar||(function(){var c=function(e){c=Object.getOwnPropertyNames||function(n){var s=[];for(var g in n)if(Object.prototype.hasOwnProperty.call(n,g))s[s.length]=g;return s};return c(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null){for(var s=c(e),g=0;g<s.length;g++)if(s[g]!=="default")L(n,e,s[g])}B(n,e);return n}})();Object.defineProperty(exports,"__esModule",{value:true});exports.main=z;const h=q(require("fs"));const x=q(require("path"));const J=require("./src/engine");const _=require("./src/indexer");const N=require("./src/okf");const W=require("@crewx/knowledge-core");let M="unknown";try{const c=h.existsSync(x.join(__dirname,"package.json"))?x.join(__dirname,"package.json"):x.join(__dirname,"..","package.json");const e=JSON.parse(h.readFileSync(c,"utf-8"));if(e?.version)M=String(e.version)}catch{}async function V(){try{return await Promise.resolve().then(()=>q(require("@crewx/shared/skill-tracer")))}catch{return null}}function G(){const c=x.join(__dirname,"..","SKILL.md");if(h.existsSync(c)){process.stdout.write(h.readFileSync(c,"utf-8"))}else{console.log("No SKILL.md found. Use --help for usage.")}}function P(c){console.log(`
3
+ @crewx/doc@${M} - Document management and knowledge tools
74
4
 
75
5
  Usage:
76
6
  doc <command> [options]
@@ -103,444 +33,17 @@ Examples:
103
33
  doc index
104
34
 
105
35
  For detailed usage guide: doc usage
106
- `);
107
- }
108
- function headingIds(engine, filePath, maxDepth = 6) {
109
- try {
110
- const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
111
- const content = fs.readFileSync(resolvedPath, 'utf-8');
112
- return engine.extractHeadings(content, maxDepth).slice(0, 3).map(heading => heading.id);
113
- }
114
- catch {
115
- return [];
116
- }
117
- }
118
- function printDocActions(jsonMode, context) {
119
- if (jsonMode)
120
- return;
121
- const block = (0, knowledge_core_1.formatActions)((0, knowledge_core_1.generateNextActions)(context));
122
- if (block)
123
- console.log(block);
124
- }
125
- async function main(inputArgs) {
126
- const args = inputArgs ?? process.argv.slice(2);
127
- const command = args[0];
128
- const jsonMode = args.includes('--json');
129
- const positionalArgs = args.filter(arg => arg !== '--json');
130
- const forceColor = args.includes('--color');
131
- const noColor = !forceColor && (args.includes('--no-color') || !process.stdout.isTTY || !!process.env.NO_COLOR);
132
- const engine = new engine_1.DocEngine(noColor);
133
- if (command === '--version') {
134
- console.log(PKG_VERSION);
135
- return;
136
- }
137
- if (command === 'usage') {
138
- showDetailedUsage();
139
- return;
140
- }
141
- if (!command || command === '--help' || command === '-h' || command === 'help') {
142
- printUsage(noColor);
143
- return;
144
- }
145
- const docsDir = positionalArgs[1] || 'docs';
146
- if (command === 'index') {
147
- const entries = (0, indexer_1.indexDocs)(docsDir);
148
- const importantEntries = entries.filter(e => e.important);
149
- const normalEntries = entries.filter(e => !e.important);
150
- const sorted = [...importantEntries, ...normalEntries];
151
- if (jsonMode) {
152
- console.log(JSON.stringify({
153
- success: true,
154
- directory: docsDir,
155
- count: sorted.length,
156
- documents: sorted,
157
- }, null, 2));
158
- return;
159
- }
160
- console.log(`Indexed ${entries.length} documents from ${docsDir}/`);
161
- for (const entry of sorted) {
162
- const star = entry.important ? '⭐ ' : '';
163
- const tags = entry.tags.length > 0 ? ` [${entry.tags.join(', ')}]` : '';
164
- console.log(` ${star}${entry.id} (${entry.category})${tags} — ${entry.summary}`);
165
- }
166
- const allTags = [...new Set(entries.flatMap(e => e.tags))].slice(0, 3);
167
- const ctx = {
168
- commandId: 'doc.index',
169
- params: {},
170
- resultTags: allTags,
171
- resultIds: sorted.slice(0, 3).map(entry => entry.id),
172
- resultCount: entries.length,
173
- };
174
- printDocActions(jsonMode, ctx);
175
- return;
176
- }
177
- if (command === 'stats') {
178
- const entries = (0, indexer_1.indexDocs)(docsDir);
179
- const importantCount = entries.filter(e => e.important).length;
180
- const categoryCounts = {};
181
- for (const entry of entries) {
182
- categoryCounts[entry.category] = (categoryCounts[entry.category] ?? 0) + 1;
183
- }
184
- const sortedCategories = Object.entries(categoryCounts).sort(([, a], [, b]) => b - a);
185
- const tags = (0, indexer_1.collectTags)(entries);
186
- const sortedTags = Object.entries(tags).sort(([, a], [, b]) => b - a).slice(0, 10);
187
- if (jsonMode) {
188
- console.log(JSON.stringify({
189
- success: true,
190
- directory: docsDir,
191
- count: entries.length,
192
- important_count: importantCount,
193
- categories: Object.fromEntries(sortedCategories),
194
- tags: Object.fromEntries(sortedTags),
195
- }, null, 2));
196
- return;
197
- }
198
- const importantNote = importantCount > 0 ? `, ${importantCount} ⭐ important` : '';
199
- console.log(`Document Stats: ${docsDir}/ (${entries.length} docs${importantNote})`);
200
- console.log('\nCategories:');
201
- for (const [cat, count] of sortedCategories) {
202
- console.log(` ${cat}: ${count}`);
203
- }
204
- console.log('\nTags TOP 10:');
205
- if (sortedTags.length === 0) {
206
- console.log(' (none)');
207
- }
208
- else {
209
- for (const [tag, count] of sortedTags) {
210
- console.log(` ${tag}: ${count}`);
211
- }
212
- }
213
- const topTags = sortedTags.slice(0, 3).map(([t]) => t);
214
- const statsCtx = {
215
- commandId: 'doc.stats',
216
- params: {},
217
- resultTags: topTags,
218
- resultCount: entries.length,
219
- };
220
- printDocActions(jsonMode, statsCtx);
221
- return;
222
- }
223
- if (command === 'find') {
224
- const query = positionalArgs[1];
225
- if (!query) {
226
- const red = noColor ? '' : '\x1b[31m';
227
- const reset = noColor ? '' : '\x1b[0m';
228
- console.error(`${red}Error: Query required${reset}`);
229
- process.exit(1);
230
- }
231
- const dir = positionalArgs[2] || 'docs';
232
- const entries = (0, indexer_1.indexDocs)(dir);
233
- const results = (0, indexer_1.findDocs)(entries, query);
234
- if (jsonMode) {
235
- console.log(JSON.stringify({
236
- success: true,
237
- directory: dir,
238
- query,
239
- count: results.length,
240
- results,
241
- }, null, 2));
242
- return;
243
- }
244
- if (results.length === 0) {
245
- console.log('No results found.');
246
- }
247
- else {
248
- console.log(`Found ${results.length} results:`);
249
- for (const r of results) {
250
- console.log(` [${r._score}] ${r.id} — ${r.summary}`);
251
- }
252
- }
253
- const resultTags = [...new Set(results.flatMap(r => r.tags ?? []))].slice(0, 3);
254
- const resultIds = results.slice(0, 3).map(r => r.id);
255
- const findCtx = {
256
- commandId: 'doc.find',
257
- params: { query },
258
- resultTags,
259
- resultIds,
260
- resultCount: results.length,
261
- };
262
- printDocActions(jsonMode, findCtx);
263
- return;
264
- }
265
- if (command === 'graph') {
266
- const entries = (0, indexer_1.indexDocs)(docsDir);
267
- const graph = (0, indexer_1.buildDocGraph)(entries);
268
- if (jsonMode) {
269
- console.log(JSON.stringify({
270
- success: true,
271
- directory: docsDir,
272
- graph,
273
- }, null, 2));
274
- return;
275
- }
276
- console.log(`Graph: ${graph.stats.nodeCount} nodes, ${graph.stats.edgeCount} edges`);
277
- if (graph.edges.length > 0) {
278
- console.log('Edges:');
279
- for (const edge of graph.edges) {
280
- console.log(` ${edge.from} ↔ ${edge.to} (${edge.type}, w=${edge.weight})`);
281
- }
282
- }
283
- const graphTags = [...new Set(entries.flatMap(e => e.tags))].slice(0, 3);
284
- const graphCtx = {
285
- commandId: 'doc.graph',
286
- params: {},
287
- resultTags: graphTags,
288
- resultCount: graph.stats.nodeCount,
289
- };
290
- printDocActions(jsonMode, graphCtx);
291
- return;
292
- }
293
- if (command === 'tags') {
294
- const entries = (0, indexer_1.indexDocs)(docsDir);
295
- const tags = (0, indexer_1.collectTags)(entries);
296
- const sorted = Object.entries(tags).sort(([, a], [, b]) => b - a);
297
- console.log(`Tags (${sorted.length} unique):`);
298
- for (const [tag, count] of sorted) {
299
- console.log(` ${tag}: ${count}`);
300
- }
301
- const topTags = sorted.slice(0, 3).map(([t]) => t);
302
- const tagsCtx = {
303
- commandId: 'doc.tags',
304
- params: {},
305
- resultTags: topTags,
306
- resultCount: sorted.length,
307
- };
308
- printDocActions(jsonMode, tagsCtx);
309
- return;
310
- }
311
- if (command === 'properties') {
312
- const entries = (0, indexer_1.indexDocs)(docsDir);
313
- const props = (0, indexer_1.collectProperties)(entries);
314
- console.log('Frontmatter properties:');
315
- for (const [key, values] of Object.entries(props)) {
316
- console.log(` ${key}: ${values.join(', ')}`);
317
- }
318
- const propTags = [...new Set(entries.flatMap(e => e.tags))].slice(0, 3);
319
- const propCtx = {
320
- commandId: 'doc.index',
321
- params: {},
322
- resultTags: propTags,
323
- resultCount: entries.length,
324
- };
325
- printDocActions(jsonMode, propCtx);
326
- return;
327
- }
328
- if (command === 'create') {
329
- const dir = args[1];
330
- const title = args[2];
331
- if (!dir || !title) {
332
- const red = noColor ? '' : '\x1b[31m';
333
- const reset = noColor ? '' : '\x1b[0m';
334
- console.error(`${red}Error: dir and title are required${reset}`);
335
- console.error('Usage: doc create <dir> "<title>" [--tags=t1,t2] [--category=cat] [--author=agent] [--body="content"] [--important]');
336
- process.exit(1);
337
- }
338
- const tagsArg = args.find(a => a.startsWith('--tags='));
339
- const tags = tagsArg ? tagsArg.slice('--tags='.length).split(',').map(t => t.trim()).filter(Boolean) : [];
340
- const categoryArg = args.find(a => a.startsWith('--category='));
341
- const category = categoryArg ? categoryArg.slice('--category='.length) : 'general';
342
- const authorArg = args.find(a => a.startsWith('--author='));
343
- const author = authorArg ? authorArg.slice('--author='.length) : '';
344
- const bodyArg = args.find(a => a.startsWith('--body='));
345
- const body = bodyArg ? bodyArg.slice('--body='.length) : '';
346
- const important = args.includes('--important');
347
- const slug = title
348
- .trim()
349
- .replace(/[\s_]+/g, '-')
350
- .toLowerCase()
351
- .replace(/[^a-z0-9\uAC00-\uD7AF\u3130-\u318F-]/g, '')
352
- .replace(/-+/g, '-')
353
- .replace(/^-+|-+$/g, '');
354
- const createFilePath = path.join(dir, `${slug}.md`);
355
- if (fs.existsSync(createFilePath)) {
356
- const red = noColor ? '' : '\x1b[31m';
357
- const reset = noColor ? '' : '\x1b[0m';
358
- console.error(`${red}Error: File already exists: ${createFilePath}${reset}`);
359
- process.exit(1);
360
- }
361
- fs.mkdirSync(dir, { recursive: true });
362
- const today = new Date().toISOString().split('T')[0];
363
- const tagsYaml = tags.length > 0 ? `[${tags.join(', ')}]` : '[]';
364
- const authorLine = author ? `author: ${author}\n` : '';
365
- const importantLine = important ? `important: true\n` : '';
366
- let content = `---\ntype: document\nsummary: ${title}\ncategory: ${category}\ntags: ${tagsYaml}\ndate: ${today}\n${authorLine}${importantLine}---\n`;
367
- if (body) {
368
- content += `\n${body}\n`;
369
- }
370
- fs.writeFileSync(createFilePath, content, 'utf-8');
371
- const green = noColor ? '' : '\x1b[32m';
372
- const reset2 = noColor ? '' : '\x1b[0m';
373
- console.log(`${green}Created:${reset2} ${createFilePath}`);
374
- const createCtx = {
375
- commandId: 'doc.create',
376
- params: { dir, title },
377
- resultTags: tags,
378
- resultCount: 1,
379
- };
380
- printDocActions(jsonMode, createCtx);
381
- return;
382
- }
383
- if (command === 'okf') {
384
- const subcommand = args[1];
385
- const okfFile = args[2];
386
- const red = noColor ? '' : '\x1b[31m';
387
- const green = noColor ? '' : '\x1b[32m';
388
- const yellow = noColor ? '' : '\x1b[33m';
389
- const reset = noColor ? '' : '\x1b[0m';
390
- if (!subcommand || !['init', 'validate', 'normalize'].includes(subcommand)) {
391
- console.error(`${red}Error: okf subcommand required: init | validate | normalize${reset}`);
392
- console.error('Usage: doc okf <init|validate|normalize> <file> [--type=...] [--title=...] [--tags=...] [--dry-run]');
393
- process.exit(1);
394
- }
395
- if (!okfFile) {
396
- console.error(`${red}Error: File path required${reset}`);
397
- process.exit(1);
398
- }
399
- const typeArg = args.find(a => a.startsWith('--type='))?.slice('--type='.length);
400
- const titleArg = args.find(a => a.startsWith('--title='))?.slice('--title='.length);
401
- const descriptionArg = args.find(a => a.startsWith('--description='))?.slice('--description='.length);
402
- const tagsArg = args.find(a => a.startsWith('--tags='))?.slice('--tags='.length);
403
- const parsedTags = tagsArg ? tagsArg.split(',').map(t => t.trim()).filter(Boolean) : undefined;
404
- const dryRun = args.includes('--dry-run');
405
- const workspaceRoot = process.cwd();
406
- const absoluteOkfFile = path.isAbsolute(okfFile) ? okfFile : path.resolve(workspaceRoot, okfFile);
407
- if (subcommand === 'init') {
408
- if (fs.existsSync(absoluteOkfFile)) {
409
- console.error(`${red}Error: File already exists: ${okfFile}${reset}`);
410
- console.error('Use "doc okf normalize" to update an existing file.');
411
- process.exit(1);
412
- }
413
- const resolvedTitle = titleArg ?? path.basename(okfFile, path.extname(okfFile)).replace(/[-_]+/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
414
- const initialBody = `\n# ${resolvedTitle}\n`;
415
- const normalized = (0, okf_1.normalizeOkfDocument)(initialBody, {
416
- filePath: absoluteOkfFile,
417
- workspaceRoot,
418
- type: typeArg,
419
- title: titleArg,
420
- description: descriptionArg,
421
- tags: parsedTags,
422
- });
423
- fs.mkdirSync(path.dirname(absoluteOkfFile), { recursive: true });
424
- fs.writeFileSync(absoluteOkfFile, normalized, 'utf-8');
425
- console.log(`${green}Created:${reset} ${okfFile}`);
426
- return;
427
- }
428
- if (subcommand === 'validate') {
429
- if (!fs.existsSync(absoluteOkfFile)) {
430
- console.error(`${red}Error: File not found: ${okfFile}${reset}`);
431
- process.exit(1);
432
- }
433
- const content = fs.readFileSync(absoluteOkfFile, 'utf-8');
434
- const issues = (0, okf_1.validateOkfDocument)(content);
435
- if (issues.length === 0) {
436
- console.log(`${green}OK:${reset} ${okfFile} — OKF frontmatter is valid`);
437
- return;
438
- }
439
- const errors = issues.filter(i => i.level === 'error');
440
- const warnings = issues.filter(i => i.level === 'warning');
441
- for (const issue of warnings) {
442
- console.log(`${yellow}WARN [${issue.field}]:${reset} ${issue.message}`);
443
- }
444
- for (const issue of errors) {
445
- console.error(`${red}ERROR [${issue.field}]:${reset} ${issue.message}`);
446
- }
447
- if (errors.length > 0) {
448
- process.exit(1);
449
- }
450
- return;
451
- }
452
- if (subcommand === 'normalize') {
453
- let existingContent = '';
454
- if (fs.existsSync(absoluteOkfFile)) {
455
- existingContent = fs.readFileSync(absoluteOkfFile, 'utf-8');
456
- }
457
- const normalized = (0, okf_1.normalizeOkfDocument)(existingContent, {
458
- filePath: absoluteOkfFile,
459
- workspaceRoot,
460
- type: typeArg,
461
- title: titleArg,
462
- description: descriptionArg,
463
- tags: parsedTags,
464
- });
465
- if (normalized === existingContent) {
466
- console.log(`${green}No changes:${reset} ${okfFile} is already normalized`);
467
- return;
468
- }
469
- if (dryRun) {
470
- console.log(`${yellow}[dry-run]${reset} Would update: ${okfFile}`);
471
- process.stdout.write(normalized);
472
- return;
473
- }
474
- fs.mkdirSync(path.dirname(absoluteOkfFile), { recursive: true });
475
- fs.writeFileSync(absoluteOkfFile, normalized, 'utf-8');
476
- console.log(`${green}Normalized:${reset} ${okfFile}`);
477
- return;
478
- }
479
- }
480
- const filePath = args[1];
481
- if (!filePath) {
482
- const red = noColor ? '' : '\x1b[31m';
483
- const reset = noColor ? '' : '\x1b[0m';
484
- console.error(`${red}Error: File path required${reset}`);
485
- printUsage(noColor);
486
- process.exit(1);
487
- }
488
- switch (command) {
489
- case 'toc': {
490
- const depthArg = args.find(a => a.startsWith('--depth='));
491
- const maxDepth = depthArg ? parseInt(depthArg.split('=')[1] ?? '4', 10) : 4;
492
- engine.toc(filePath, { maxDepth });
493
- printDocActions(jsonMode, {
494
- commandId: 'doc.toc',
495
- params: { file: filePath },
496
- resultIds: headingIds(engine, filePath, maxDepth),
497
- });
498
- break;
499
- }
500
- case 'section': {
501
- const selector = args[2];
502
- if (!selector) {
503
- const red = noColor ? '' : '\x1b[31m';
504
- const reset = noColor ? '' : '\x1b[0m';
505
- console.error(`${red}Error: Heading selector required${reset}`);
506
- process.exit(1);
507
- }
508
- engine.section(filePath, selector);
509
- printDocActions(jsonMode, {
510
- commandId: 'doc.section',
511
- params: { file: filePath, heading: selector },
512
- });
513
- break;
514
- }
515
- case 'status': {
516
- engine.status(filePath);
517
- printDocActions(jsonMode, {
518
- commandId: 'doc.toc',
519
- params: { file: filePath },
520
- resultIds: headingIds(engine, filePath),
521
- });
522
- break;
523
- }
524
- case 'summary': {
525
- engine.summary(filePath);
526
- break;
527
- }
528
- default: {
529
- const red = noColor ? '' : '\x1b[31m';
530
- const reset = noColor ? '' : '\x1b[0m';
531
- console.error(`${red}Unknown command: ${command}${reset}`);
532
- printUsage(noColor);
533
- process.exit(1);
534
- }
535
- }
536
- }
537
- if (require.main === module) {
538
- loadTracer().then(tracer => {
539
- const opts = tracer ? { skillVersion: tracer.getOwnSkillVersion(__dirname) } : {};
540
- return tracer ? tracer.run('crewx/doc', main, opts) : main();
541
- }).catch((err) => {
542
- console.error(`Error: ${err.message}`);
543
- process.exit(1);
544
- });
545
- }
546
- //# sourceMappingURL=cli.js.map
36
+ `)}function K(c,e,n=6){try{const s=x.isAbsolute(e)?e:x.resolve(process.cwd(),e);const g=h.readFileSync(s,"utf-8");return c.extractHeadings(g,n).slice(0,3).map(E=>E.id)}catch{return[]}}function k(c,e){if(c)return;const n=(0,W.formatActions)((0,W.generateNextActions)(e));if(n)console.log(n)}async function z(c){const e=c??process.argv.slice(2);const n=e[0];const s=e.includes("--json");const g=e.filter(t=>t!=="--json");const E=e.includes("--color");const u=!E&&(e.includes("--no-color")||!process.stdout.isTTY||!!process.env.NO_COLOR);const F=new J.DocEngine(u);if(n==="--version"){console.log(M);return}if(n==="usage"){G();return}if(!n||n==="--help"||n==="-h"||n==="help"){P(u);return}const v=g[1]||"docs";if(n==="index"){const t=(0,_.indexDocs)(v);const o=t.filter(l=>l.important);const a=t.filter(l=>!l.important);const r=[...o,...a];if(s){console.log(JSON.stringify({success:true,directory:v,count:r.length,documents:r},null,2));return}console.log(`Indexed ${t.length} documents from ${v}/`);for(const l of r){const f=l.important?"\u2B50 ":"";const w=l.tags.length>0?` [${l.tags.join(", ")}]`:"";console.log(` ${f}${l.id} (${l.category})${w} \u2014 ${l.summary}`)}const d=[...new Set(t.flatMap(l=>l.tags))].slice(0,3);const i={commandId:"doc.index",params:{},resultTags:d,resultIds:r.slice(0,3).map(l=>l.id),resultCount:t.length};k(s,i);return}if(n==="stats"){const t=(0,_.indexDocs)(v);const o=t.filter(m=>m.important).length;const a={};for(const m of t){a[m.category]=(a[m.category]??0)+1}const r=Object.entries(a).sort(([,m],[,b])=>b-m);const d=(0,_.collectTags)(t);const i=Object.entries(d).sort(([,m],[,b])=>b-m).slice(0,10);if(s){console.log(JSON.stringify({success:true,directory:v,count:t.length,important_count:o,categories:Object.fromEntries(r),tags:Object.fromEntries(i)},null,2));return}const l=o>0?`, ${o} \u2B50 important`:"";console.log(`Document Stats: ${v}/ (${t.length} docs${l})`);console.log("\nCategories:");for(const[m,b]of r){console.log(` ${m}: ${b}`)}console.log("\nTags TOP 10:");if(i.length===0){console.log(" (none)")}else{for(const[m,b]of i){console.log(` ${m}: ${b}`)}}const f=i.slice(0,3).map(([m])=>m);const w={commandId:"doc.stats",params:{},resultTags:f,resultCount:t.length};k(s,w);return}if(n==="find"){const t=g[1];if(!t){const f=u?"":"\x1B[31m";const w=u?"":"\x1B[0m";console.error(`${f}Error: Query required${w}`);process.exit(1)}const o=g[2]||"docs";const a=(0,_.indexDocs)(o);const r=(0,_.findDocs)(a,t);if(s){console.log(JSON.stringify({success:true,directory:o,query:t,count:r.length,results:r},null,2));return}if(r.length===0){console.log("No results found.")}else{console.log(`Found ${r.length} results:`);for(const f of r){console.log(` [${f._score}] ${f.id} \u2014 ${f.summary}`)}}const d=[...new Set(r.flatMap(f=>f.tags??[]))].slice(0,3);const i=r.slice(0,3).map(f=>f.id);const l={commandId:"doc.find",params:{query:t},resultTags:d,resultIds:i,resultCount:r.length};k(s,l);return}if(n==="graph"){const t=(0,_.indexDocs)(v);const o=(0,_.buildDocGraph)(t);if(s){console.log(JSON.stringify({success:true,directory:v,graph:o},null,2));return}console.log(`Graph: ${o.stats.nodeCount} nodes, ${o.stats.edgeCount} edges`);if(o.edges.length>0){console.log("Edges:");for(const d of o.edges){console.log(` ${d.from} \u2194 ${d.to} (${d.type}, w=${d.weight})`)}}const a=[...new Set(t.flatMap(d=>d.tags))].slice(0,3);const r={commandId:"doc.graph",params:{},resultTags:a,resultCount:o.stats.nodeCount};k(s,r);return}if(n==="tags"){const t=(0,_.indexDocs)(v);const o=(0,_.collectTags)(t);const a=Object.entries(o).sort(([,i],[,l])=>l-i);console.log(`Tags (${a.length} unique):`);for(const[i,l]of a){console.log(` ${i}: ${l}`)}const r=a.slice(0,3).map(([i])=>i);const d={commandId:"doc.tags",params:{},resultTags:r,resultCount:a.length};k(s,d);return}if(n==="properties"){const t=(0,_.indexDocs)(v);const o=(0,_.collectProperties)(t);console.log("Frontmatter properties:");for(const[d,i]of Object.entries(o)){console.log(` ${d}: ${i.join(", ")}`)}const a=[...new Set(t.flatMap(d=>d.tags))].slice(0,3);const r={commandId:"doc.index",params:{},resultTags:a,resultCount:t.length};k(s,r);return}if(n==="create"){const t=e[1];const o=e[2];if(!t||!o){const y=u?"":"\x1B[31m";const A=u?"":"\x1B[0m";console.error(`${y}Error: dir and title are required${A}`);console.error('Usage: doc create <dir> "<title>" [--tags=t1,t2] [--category=cat] [--author=agent] [--body="content"] [--important]');process.exit(1)}const a=e.find(y=>y.startsWith("--tags="));const r=a?a.slice("--tags=".length).split(",").map(y=>y.trim()).filter(Boolean):[];const d=e.find(y=>y.startsWith("--category="));const i=d?d.slice("--category=".length):"general";const l=e.find(y=>y.startsWith("--author="));const f=l?l.slice("--author=".length):"";const w=e.find(y=>y.startsWith("--body="));const m=w?w.slice("--body=".length):"";const b=e.includes("--important");const I=o.trim().replace(/[\s_]+/g,"-").toLowerCase().replace(/[^a-z0-9\uAC00-\uD7AF\u3130-\u318F-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"");const j=x.join(t,`${I}.md`);if(h.existsSync(j)){const y=u?"":"\x1B[31m";const A=u?"":"\x1B[0m";console.error(`${y}Error: File already exists: ${j}${A}`);process.exit(1)}h.mkdirSync(t,{recursive:true});const $=new Date().toISOString().split("T")[0];const p=r.length>0?`[${r.join(", ")}]`:"[]";const S=f?`author: ${f}
37
+ `:"";const T=b?`important: true
38
+ `:"";let D=`---
39
+ type: document
40
+ summary: ${o}
41
+ category: ${i}
42
+ tags: ${p}
43
+ date: ${$}
44
+ ${S}${T}---
45
+ `;if(m){D+=`
46
+ ${m}
47
+ `}h.writeFileSync(j,D,"utf-8");const O=u?"":"\x1B[32m";const R=u?"":"\x1B[0m";console.log(`${O}Created:${R} ${j}`);const U={commandId:"doc.create",params:{dir:t,title:o},resultTags:r,resultCount:1};k(s,U);return}if(n==="okf"){const t=e[1];const o=e[2];const a=u?"":"\x1B[31m";const r=u?"":"\x1B[32m";const d=u?"":"\x1B[33m";const i=u?"":"\x1B[0m";if(!t||!["init","validate","normalize"].includes(t)){console.error(`${a}Error: okf subcommand required: init | validate | normalize${i}`);console.error("Usage: doc okf <init|validate|normalize> <file> [--type=...] [--title=...] [--tags=...] [--dry-run]");process.exit(1)}if(!o){console.error(`${a}Error: File path required${i}`);process.exit(1)}const l=e.find(p=>p.startsWith("--type="))?.slice("--type=".length);const f=e.find(p=>p.startsWith("--title="))?.slice("--title=".length);const w=e.find(p=>p.startsWith("--description="))?.slice("--description=".length);const m=e.find(p=>p.startsWith("--tags="))?.slice("--tags=".length);const b=m?m.split(",").map(p=>p.trim()).filter(Boolean):void 0;const I=e.includes("--dry-run");const j=process.cwd();const $=x.isAbsolute(o)?o:x.resolve(j,o);if(t==="init"){if(h.existsSync($)){console.error(`${a}Error: File already exists: ${o}${i}`);console.error('Use "doc okf normalize" to update an existing file.');process.exit(1)}const p=f??x.basename(o,x.extname(o)).replace(/[-_]+/g," ").replace(/\b\w/g,D=>D.toUpperCase());const S=`
48
+ # ${p}
49
+ `;const T=(0,N.normalizeOkfDocument)(S,{filePath:$,workspaceRoot:j,type:l,title:f,description:w,tags:b});h.mkdirSync(x.dirname($),{recursive:true});h.writeFileSync($,T,"utf-8");console.log(`${r}Created:${i} ${o}`);return}if(t==="validate"){if(!h.existsSync($)){console.error(`${a}Error: File not found: ${o}${i}`);process.exit(1)}const p=h.readFileSync($,"utf-8");const S=(0,N.validateOkfDocument)(p);if(S.length===0){console.log(`${r}OK:${i} ${o} \u2014 OKF frontmatter is valid`);return}const T=S.filter(O=>O.level==="error");const D=S.filter(O=>O.level==="warning");for(const O of D){console.log(`${d}WARN [${O.field}]:${i} ${O.message}`)}for(const O of T){console.error(`${a}ERROR [${O.field}]:${i} ${O.message}`)}if(T.length>0){process.exit(1)}return}if(t==="normalize"){let p="";if(h.existsSync($)){p=h.readFileSync($,"utf-8")}const S=(0,N.normalizeOkfDocument)(p,{filePath:$,workspaceRoot:j,type:l,title:f,description:w,tags:b});if(S===p){console.log(`${r}No changes:${i} ${o} is already normalized`);return}if(I){console.log(`${d}[dry-run]${i} Would update: ${o}`);process.stdout.write(S);return}h.mkdirSync(x.dirname($),{recursive:true});h.writeFileSync($,S,"utf-8");console.log(`${r}Normalized:${i} ${o}`);return}}const C=e[1];if(!C){const t=u?"":"\x1B[31m";const o=u?"":"\x1B[0m";console.error(`${t}Error: File path required${o}`);P(u);process.exit(1)}switch(n){case"toc":{const t=e.find(a=>a.startsWith("--depth="));const o=t?parseInt(t.split("=")[1]??"4",10):4;F.toc(C,{maxDepth:o});k(s,{commandId:"doc.toc",params:{file:C},resultIds:K(F,C,o)});break}case"section":{const t=e[2];if(!t){const o=u?"":"\x1B[31m";const a=u?"":"\x1B[0m";console.error(`${o}Error: Heading selector required${a}`);process.exit(1)}F.section(C,t);k(s,{commandId:"doc.section",params:{file:C,heading:t}});break}case"status":{F.status(C);k(s,{commandId:"doc.toc",params:{file:C},resultIds:K(F,C)});break}case"summary":{F.summary(C);break}default:{const t=u?"":"\x1B[31m";const o=u?"":"\x1B[0m";console.error(`${t}Unknown command: ${n}${o}`);P(u);process.exit(1)}}}if(require.main===module){V().then(c=>{const e=c?{skillVersion:c.getOwnSkillVersion(__dirname)}:{};return c?c.run("crewx/doc",z,e):z()}).catch(c=>{console.error(`Error: ${c.message}`);process.exit(1)})}
@@ -1,2 +1,2 @@
1
1
  export declare function buildAnnotationDigest(markdown: string): string;
2
- //# sourceMappingURL=annotation.d.ts.map
2
+
@@ -1,88 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.buildAnnotationDigest = buildAnnotationDigest;
37
- const yaml = __importStar(require("js-yaml"));
38
- function splitFrontmatter(markdown) {
39
- const re = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;
40
- const match = markdown.match(re);
41
- if (!match)
42
- return { data: null, body: markdown };
43
- try {
44
- const parsed = yaml.load(match[1]);
45
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
46
- return { data: parsed, body: match[2] };
47
- }
48
- }
49
- catch {
50
- }
51
- return { data: null, body: match[2] ?? markdown };
52
- }
53
- function isActiveHighlight(h) {
54
- if (!h || typeof h !== 'object')
55
- return false;
56
- const hl = h;
57
- const status = hl.status;
58
- return status !== 'orphaned' && status !== 'deleted' && status !== 'superseded';
59
- }
60
- function buildAnnotationDigest(markdown) {
61
- const { data } = splitFrontmatter(markdown);
62
- if (!data)
63
- return '';
64
- const crewx = data['crewx'];
65
- if (!crewx || typeof crewx !== 'object' || Array.isArray(crewx))
66
- return '';
67
- const highlights = crewx['highlights'];
68
- if (!Array.isArray(highlights) || highlights.length === 0)
69
- return '';
70
- const active = highlights.filter(isActiveHighlight);
71
- if (active.length === 0)
72
- return '';
73
- const lines = ['[annotation digest]'];
74
- for (const hl of active) {
75
- const parts = [];
76
- if (hl.intent)
77
- parts.push(`intent=${hl.intent}`);
78
- if (hl.context?.heading)
79
- parts.push(`heading="${hl.context.heading}"`);
80
- const meta = parts.length > 0 ? ` (${parts.join(', ')})` : '';
81
- if (hl.quote)
82
- lines.push(`• quote${meta}: ${hl.quote}`);
83
- if (hl.note)
84
- lines.push(` note: ${hl.note}`);
85
- }
86
- return lines.join('\n');
87
- }
88
- //# sourceMappingURL=annotation.js.map
1
+ "use strict";var s=exports&&exports.__createBinding||(Object.create?(function(r,e,t,n){if(n===void 0)n=t;var i=Object.getOwnPropertyDescriptor(e,t);if(!i||("get"in i?!e.__esModule:i.writable||i.configurable)){i={enumerable:true,get:function(){return e[t]}}}Object.defineProperty(r,n,i)}):(function(r,e,t,n){if(n===void 0)n=t;r[n]=e[t]}));var f=exports&&exports.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:true,value:e})}):function(r,e){r["default"]=e});var l=exports&&exports.__importStar||(function(){var r=function(e){r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i))n[n.length]=i;return n};return r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var n=r(e),i=0;i<n.length;i++)if(n[i]!=="default")s(t,e,n[i])}f(t,e);return t}})();Object.defineProperty(exports,"__esModule",{value:true});exports.buildAnnotationDigest=y;const h=l(require("js-yaml"));function d(r){const e=/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)([\s\S]*)$/;const t=r.match(e);if(!t)return{data:null,body:r};try{const n=h.load(t[1]);if(n&&typeof n==="object"&&!Array.isArray(n)){return{data:n,body:t[2]}}}catch{}return{data:null,body:t[2]??r}}function g(r){if(!r||typeof r!=="object")return false;const e=r;const t=e.status;return t!=="orphaned"&&t!=="deleted"&&t!=="superseded"}function y(r){const{data:e}=d(r);if(!e)return"";const t=e["crewx"];if(!t||typeof t!=="object"||Array.isArray(t))return"";const n=t["highlights"];if(!Array.isArray(n)||n.length===0)return"";const i=n.filter(g);if(i.length===0)return"";const o=["[annotation digest]"];for(const u of i){const a=[];if(u.intent)a.push(`intent=${u.intent}`);if(u.context?.heading)a.push(`heading="${u.context.heading}"`);const c=a.length>0?` (${a.join(", ")})`:"";if(u.quote)o.push(`\u2022 quote${c}: ${u.quote}`);if(u.note)o.push(` note: ${u.note}`)}return o.join("\n")}
@@ -14,4 +14,4 @@ export declare class DocEngine {
14
14
  private readFile;
15
15
  }
16
16
  export { buildAnnotationDigest } from './annotation';
17
- //# sourceMappingURL=engine.d.ts.map
17
+