skillwiki 0.2.1-beta.2 → 0.2.1-beta.21

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.js CHANGED
@@ -2,43 +2,20 @@
2
2
  import {
3
3
  semverGt
4
4
  } from "./chunk-XM5IYZX7.js";
5
+ import {
6
+ git,
7
+ gitStrict
8
+ } from "./chunk-TPS5XD2J.js";
5
9
 
6
10
  // src/cli.ts
7
- import { readFileSync as readFileSync5 } from "fs";
11
+ import { readFileSync as readFileSync9 } from "fs";
12
+ import { join as join37 } from "path";
8
13
  import { Command } from "commander";
9
14
 
10
- // src/utils/output.ts
11
- function printJson(r) {
12
- process.stdout.write(JSON.stringify(r) + "\n");
13
- }
14
- function printHuman(r) {
15
- if (r.ok) {
16
- if (typeof r.data === "object" && r.data !== null && "humanHint" in r.data) {
17
- process.stdout.write(`${r.data.humanHint}
18
- `);
19
- } else {
20
- process.stdout.write(`OK
21
- ${formatData(r.data)}
22
- `);
23
- }
24
- } else {
25
- process.stdout.write(`ERR ${r.error}
26
- ${r.detail !== void 0 ? formatData(r.detail) + "\n" : ""}`);
27
- }
28
- }
29
- function formatData(d) {
30
- if (d == null) return "";
31
- if (typeof d === "string") return d;
32
- return JSON.stringify(d, null, 2);
33
- }
34
-
35
- // src/commands/hash.ts
36
- import { readFile } from "fs/promises";
37
- import { createHash } from "crypto";
38
-
39
15
  // ../shared/src/exit-codes.ts
40
16
  var ExitCode = {
41
17
  OK: 0,
18
+ INTERNAL_ERROR: 1,
42
19
  FILE_NOT_FOUND: 2,
43
20
  MISSING_CLOSING_DELIMITER: 3,
44
21
  SCHEME_REJECTED: 4,
@@ -73,7 +50,16 @@ var ExitCode = {
73
50
  RAW_DEDUP_DETECTED: 33,
74
51
  MIGRATION_APPLIED: 34,
75
52
  UNKNOWN_WIKI_PROFILE: 35,
76
- DEDUP_APPLIED: 36
53
+ DEDUP_APPLIED: 36,
54
+ PROJECT_NOT_FOUND: 37,
55
+ SYMLINK_FAILED: 38,
56
+ COMPOUND_PROMOTED: 39,
57
+ SKILL_VERSION_MISMATCH: 40,
58
+ INGEST_VALIDATION_FAILED: 41,
59
+ SYNC_PUSH_FAILED: 42,
60
+ SYNC_PULL_FAILED: 43,
61
+ BACKUP_SYNC_FAILED: 44,
62
+ BACKUP_RESTORE_CONFLICTS: 45
77
63
  };
78
64
 
79
65
  // ../shared/src/json-output.ts
@@ -97,7 +83,7 @@ var TypedKnowledgeSchema = z.object({
97
83
  aliases: z.array(z.string()).optional(),
98
84
  created: isoDate,
99
85
  updated: isoDate,
100
- type: z.enum(["entity", "concept", "comparison", "query", "summary"]),
86
+ type: z.enum(["entity", "concept", "comparison", "query"]),
101
87
  tags: z.array(z.string()),
102
88
  sources: z.array(z.string()).min(1),
103
89
  confidence: z.enum(["high", "medium", "low"]).optional(),
@@ -117,15 +103,13 @@ var RawSourceSchema = z.object({
117
103
  source_url: z.string().nullable(),
118
104
  ingested: isoDate,
119
105
  ingested_by: z.enum(["wiki-ingest", "proj-work", "manual"]).optional(),
120
- sha256: sha256Hex,
106
+ sha256: sha256Hex.optional(),
121
107
  project: wikilink.optional(),
122
108
  work_item: wikilink.optional(),
123
- kind: z.enum(["postmortem", "session-log", "meeting-notes", "other"]).optional()
109
+ kind: z.enum(["postmortem", "session-log", "meeting-notes", "other", "idea", "bug", "task", "note"]).optional()
124
110
  }).superRefine((v, ctx) => {
125
- const projectFields = [v.project, v.work_item, v.kind];
126
- const present = projectFields.filter((x) => x !== void 0).length;
127
- if (present !== 0 && present !== 3) {
128
- ctx.addIssue({ code: z.ZodIssueCode.custom, message: "project, work_item, kind must all be set together" });
111
+ if (v.work_item !== void 0 && (v.project === void 0 || v.kind === void 0)) {
112
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "project and kind are required when work_item is set" });
129
113
  }
130
114
  });
131
115
  var WorkItemSchema = z.object({
@@ -162,11 +146,29 @@ var CompoundSchema = z.object({
162
146
  promoted_to: wikilink.optional(),
163
147
  cssclasses: z.array(z.string()).optional()
164
148
  });
149
+ var MetaSchema = z.object({
150
+ title: z.string().min(1),
151
+ aliases: z.array(z.string()).optional(),
152
+ created: isoDate,
153
+ updated: isoDate,
154
+ type: z.literal("meta"),
155
+ tags: z.array(z.string()),
156
+ confidence: z.enum(["high", "medium", "low"]).optional(),
157
+ provenance: z.enum(["research", "project", "mixed"]).optional(),
158
+ provenance_projects: z.array(wikilink).min(2, "meta pages must reference \u22652 projects")
159
+ }).superRefine((v, ctx) => {
160
+ if (v.provenance && v.provenance !== "research" && (!v.provenance_projects || v.provenance_projects.length === 0)) {
161
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["provenance_projects"], message: "required when provenance != research" });
162
+ }
163
+ });
165
164
  function detectSchema(fm) {
166
165
  const COMPOUND_TYPES = /* @__PURE__ */ new Set(["lesson", "pattern", "antipattern", "gotcha"]);
167
166
  if (typeof fm.type === "string" && COMPOUND_TYPES.has(fm.type) && "project" in fm) return { schema: "compound" };
167
+ if (fm.type === "meta") return { schema: "meta" };
168
168
  if ("type" in fm && "sources" in fm) return { schema: "typed-knowledge" };
169
- if (typeof fm.sha256 === "string" && "ingested" in fm) return { schema: "raw" };
169
+ if ("ingested" in fm && ("source_url" in fm || "sha256" in fm)) return { schema: "raw" };
170
+ const RAW_KINDS = /* @__PURE__ */ new Set(["postmortem", "session-log", "meeting-notes", "other", "idea", "bug", "task", "note"]);
171
+ if ("ingested" in fm && typeof fm.kind === "string" && RAW_KINDS.has(fm.kind)) return { schema: "raw" };
170
172
  if ("kind" in fm && "status" in fm) return { schema: "work-item" };
171
173
  return { schema: null };
172
174
  }
@@ -210,6 +212,56 @@ function isBlockedHost(host) {
210
212
  return false;
211
213
  }
212
214
 
215
+ // src/utils/output.ts
216
+ function printJson(r) {
217
+ process.stdout.write(JSON.stringify(r) + "\n");
218
+ }
219
+ function printHuman(r) {
220
+ if (r.ok) {
221
+ if (typeof r.data === "object" && r.data !== null && "humanHint" in r.data) {
222
+ process.stdout.write(`${r.data.humanHint}
223
+ `);
224
+ } else {
225
+ process.stdout.write(`OK
226
+ ${formatData(r.data)}
227
+ `);
228
+ }
229
+ } else {
230
+ process.stdout.write(`ERR ${r.error}
231
+ ${r.detail !== void 0 ? formatData(r.detail) + "\n" : ""}`);
232
+ }
233
+ }
234
+ function formatData(d) {
235
+ if (d == null) return "";
236
+ if (typeof d === "string") return d;
237
+ return JSON.stringify(d, null, 2);
238
+ }
239
+
240
+ // src/utils/deprecation.ts
241
+ import { readFileSync } from "fs";
242
+ import { join } from "path";
243
+ function getDeprecatedWarnings(home) {
244
+ const manifestPath = join(home, ".claude", "skills", "wiki-manifest.json");
245
+ try {
246
+ const raw = readFileSync(manifestPath, "utf8");
247
+ const manifest = JSON.parse(raw);
248
+ if (!manifest.skills) return [];
249
+ const warnings = [];
250
+ for (const [dirName, meta] of Object.entries(manifest.skills)) {
251
+ if (meta.deprecated) {
252
+ warnings.push(`\u26A0 Skill "${meta.name || dirName}" is deprecated. See SKILL.md for migration notes.`);
253
+ }
254
+ }
255
+ return warnings;
256
+ } catch {
257
+ return [];
258
+ }
259
+ }
260
+
261
+ // src/commands/hash.ts
262
+ import { readFile } from "fs/promises";
263
+ import { createHash } from "crypto";
264
+
213
265
  // src/parsers/frontmatter.ts
214
266
  import yaml from "js-yaml";
215
267
  var FM_OPEN = /^---\r?\n/;
@@ -298,12 +350,22 @@ function sanitizeUrl(u) {
298
350
  }
299
351
 
300
352
  // src/commands/validate.ts
301
- import { readFile as readFile2 } from "fs/promises";
353
+ import { readFile as readFile2, writeFile } from "fs/promises";
354
+ import { join as join2, resolve, relative, sep } from "path";
355
+ var TYPE_TO_SECTION = {
356
+ entity: "Entities",
357
+ concept: "Concepts",
358
+ comparison: "Comparisons",
359
+ query: "Queries",
360
+ summary: "Summaries",
361
+ meta: "Meta"
362
+ };
302
363
  var SCHEMAS = {
303
364
  "typed-knowledge": TypedKnowledgeSchema,
304
365
  "raw": RawSourceSchema,
305
366
  "work-item": WorkItemSchema,
306
- "compound": CompoundSchema
367
+ "compound": CompoundSchema,
368
+ "meta": MetaSchema
307
369
  };
308
370
  async function runValidate(input) {
309
371
  let text;
@@ -321,36 +383,120 @@ async function runValidate(input) {
321
383
  }
322
384
  const det = detectSchema(fm.data);
323
385
  if (!det.schema) {
324
- return { exitCode: ExitCode.SCHEMA_NOT_DETECTED, result: ok({ schema: null, valid: false, errors: [], humanHint: "schema not detected" }) };
386
+ return { exitCode: ExitCode.SCHEMA_NOT_DETECTED, result: ok({ schema: null, valid: false, errors: [], index_updated: false, log_updated: false, humanHint: "schema not detected" }) };
325
387
  }
326
388
  const parsed = SCHEMAS[det.schema].safeParse(fm.data);
327
389
  if (!parsed.success) {
328
390
  const errors = parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message }));
329
391
  return {
330
392
  exitCode: ExitCode.INVALID_FRONTMATTER,
331
- result: ok({ schema: det.schema, valid: false, errors, humanHint: `INVALID (${det.schema})
393
+ result: ok({ schema: det.schema, valid: false, errors, index_updated: false, log_updated: false, humanHint: `INVALID (${det.schema})
332
394
  ${errors.map((e) => ` ${e.path}: ${e.message}`).join("\n")}` })
333
395
  };
334
396
  }
335
- return { exitCode: ExitCode.OK, result: ok({ schema: det.schema, valid: true, errors: [], humanHint: `VALID (${det.schema})` }) };
397
+ if (input.apply && !input.vault) {
398
+ return { exitCode: ExitCode.VAULT_PATH_INVALID, result: err("VAULT_PATH_INVALID", { reason: "--vault is required when --apply is set" }) };
399
+ }
400
+ let indexUpdated = false;
401
+ let logUpdated = false;
402
+ let applyHint = "";
403
+ if (input.apply && input.vault) {
404
+ const absFile = resolve(input.file);
405
+ const absVault = resolve(input.vault);
406
+ const relPath = relative(absVault, absFile).split(sep).join("/");
407
+ if (relPath.startsWith("..")) {
408
+ return { exitCode: ExitCode.VAULT_PATH_INVALID, result: err("VAULT_PATH_INVALID", { reason: `file ${input.file} is not inside vault ${input.vault}` }) };
409
+ }
410
+ const pageType = "type" in parsed.data && typeof parsed.data.type === "string" ? parsed.data.type : "";
411
+ const title = typeof parsed.data.title === "string" ? parsed.data.title : relPath.replace(/\.md$/, "");
412
+ if (det.schema === "typed-knowledge" || det.schema === "meta") {
413
+ indexUpdated = await addToIndex(input.vault, relPath, title, pageType);
414
+ }
415
+ logUpdated = await appendToLog(input.vault, relPath);
416
+ if (indexUpdated) applyHint += `
417
+ index: added [[${relPath.replace(/\.md$/, "")}]]`;
418
+ if (logUpdated) applyHint += "\n log: appended entry";
419
+ }
420
+ return { exitCode: ExitCode.OK, result: ok({
421
+ schema: det.schema,
422
+ valid: true,
423
+ errors: [],
424
+ index_updated: indexUpdated,
425
+ log_updated: logUpdated,
426
+ humanHint: `VALID (${det.schema})${applyHint}`
427
+ }) };
428
+ }
429
+ async function addToIndex(vault, relPath, title, pageType) {
430
+ const section = TYPE_TO_SECTION[pageType];
431
+ if (!section) return false;
432
+ const indexPath = join2(vault, "index.md");
433
+ let text;
434
+ try {
435
+ text = await readFile2(indexPath, "utf8");
436
+ } catch {
437
+ return false;
438
+ }
439
+ const ref = relPath.replace(/\.md$/, "");
440
+ if (text.includes(`[[${ref}]]`)) return false;
441
+ const entry = `- [[${ref}]] \u2014 ${title}`;
442
+ const lines = text.split("\n");
443
+ const sectionLine = `## ${section}`;
444
+ const sectionIdx = lines.findIndex((l) => l.trim() === sectionLine);
445
+ if (sectionIdx === -1) {
446
+ while (lines.length > 0 && lines[lines.length - 1].trim() === "") lines.pop();
447
+ lines.push("", sectionLine, entry);
448
+ } else {
449
+ let endIdx = sectionIdx + 1;
450
+ while (endIdx < lines.length) {
451
+ if (lines[endIdx].startsWith("## ")) break;
452
+ endIdx++;
453
+ }
454
+ let insertAt = endIdx;
455
+ while (insertAt > sectionIdx + 1 && lines[insertAt - 1].trim() === "") insertAt--;
456
+ lines.splice(insertAt, 0, entry);
457
+ }
458
+ try {
459
+ await writeFile(indexPath, lines.join("\n"), "utf8");
460
+ } catch {
461
+ return false;
462
+ }
463
+ return true;
464
+ }
465
+ async function appendToLog(vault, relPath) {
466
+ const logPath = join2(vault, "log.md");
467
+ let text;
468
+ try {
469
+ text = await readFile2(logPath, "utf8");
470
+ } catch {
471
+ return false;
472
+ }
473
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
474
+ const entry = `
475
+ ## [${today}] validate | added: ${relPath}`;
476
+ try {
477
+ await writeFile(logPath, text.trimEnd() + entry, "utf8");
478
+ } catch {
479
+ return false;
480
+ }
481
+ return true;
336
482
  }
337
483
 
338
484
  // src/commands/graph.ts
339
- import { writeFile, mkdir } from "fs/promises";
485
+ import { writeFile as writeFile2, mkdir } from "fs/promises";
340
486
  import { dirname } from "path";
341
487
 
342
488
  // src/utils/vault.ts
343
489
  import { readFile as readFile3, readdir, stat } from "fs/promises";
344
- import { join, relative, sep } from "path";
345
- var TYPED_DIRS = ["entities", "concepts", "comparisons", "queries"];
490
+ import { join as join3, relative as relative2, sep as sep2 } from "path";
491
+ var TYPED_DIRS = ["entities", "concepts", "comparisons", "queries", "meta"];
346
492
  async function scanVault(root) {
347
493
  try {
348
- await stat(join(root, "SCHEMA.md"));
494
+ await stat(join3(root, "SCHEMA.md"));
349
495
  } catch {
350
496
  return err("VAULT_PATH_INVALID", { root, reason: "SCHEMA.md missing" });
351
497
  }
352
498
  const all = await walk(root);
353
- const rels = all.map((p) => ({ absPath: p, relPath: relative(root, p).split(sep).join("/") }));
499
+ const rels = all.map((p) => ({ absPath: p, relPath: relative2(root, p).split(sep2).join("/") }));
354
500
  return ok({
355
501
  root,
356
502
  typedKnowledge: rels.filter((p) => TYPED_DIRS.some((d) => p.relPath.startsWith(d + "/"))),
@@ -363,7 +509,7 @@ async function walk(dir) {
363
509
  const entries = await readdir(dir, { withFileTypes: true });
364
510
  const out = [];
365
511
  for (const e of entries) {
366
- const p = join(dir, e.name);
512
+ const p = join3(dir, e.name);
367
513
  if (e.isDirectory()) out.push(...await walk(p));
368
514
  else if (e.isFile() && e.name.endsWith(".md")) out.push(p);
369
515
  }
@@ -374,7 +520,7 @@ async function readPage(p) {
374
520
  }
375
521
 
376
522
  // src/parsers/wikilinks.ts
377
- var FENCE = /`[^`]*`|```[\s\S]*?```/g;
523
+ var FENCE = /```[\s\S]*?```|`[^`\n]*`/g;
378
524
  function extractBodyWikilinks(body) {
379
525
  const stripped = body.replace(FENCE, "");
380
526
  const seen = /* @__PURE__ */ new Set();
@@ -412,7 +558,7 @@ async function runGraphBuild(input) {
412
558
  const edge_count = Object.values(adjacency).reduce((acc, arr) => acc + arr.length, 0);
413
559
  try {
414
560
  await mkdir(dirname(input.out), { recursive: true });
415
- await writeFile(input.out, JSON.stringify({ adjacency, adamicAdar }, null, 2));
561
+ await writeFile2(input.out, JSON.stringify({ adjacency, adamicAdar }, null, 2));
416
562
  } catch (e) {
417
563
  return { exitCode: ExitCode.WRITE_FAILED, result: err("WRITE_FAILED", { message: String(e) }) };
418
564
  }
@@ -499,12 +645,21 @@ async function runOverlap(input) {
499
645
  }
500
646
 
501
647
  // src/utils/wiki-path.ts
502
- import { join as join2 } from "path";
648
+ import { join as join4 } from "path";
503
649
 
504
650
  // src/utils/dotenv.ts
505
- import { readFile as readFile4, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
651
+ import { readFile as readFile4, writeFile as writeFile3, mkdir as mkdir2 } from "fs/promises";
506
652
  import { dirname as dirname2 } from "path";
507
- var CONFIG_KEYS = ["WIKI_PATH", "WIKI_LANG"];
653
+ var CONFIG_KEYS = [
654
+ "WIKI_PATH",
655
+ "WIKI_LANG",
656
+ "AUTO_COMMIT",
657
+ "BACKUP_ENDPOINT",
658
+ "BACKUP_BUCKET",
659
+ "BACKUP_REGION",
660
+ "BACKUP_ACCESS_KEY_ID",
661
+ "BACKUP_SECRET_ACCESS_KEY"
662
+ ];
508
663
  var _whitelist = new Set(CONFIG_KEYS);
509
664
  var PROFILE_PATH_RE = /^WIKI_([A-Z][A-Z0-9_]{0,31})_PATH$/;
510
665
  var PROFILE_LANG_RE = /^WIKI_([A-Z][A-Z0-9_]{0,31})_LANG$/;
@@ -543,7 +698,7 @@ async function parseDotenvFile(path) {
543
698
  async function writeDotenv(filePath, entries, originalContent) {
544
699
  const lines = originalContent !== void 0 ? updateLines(originalContent, entries) : freshLines(entries);
545
700
  await mkdir2(dirname2(filePath), { recursive: true });
546
- await writeFile2(filePath, lines.join("\n") + "\n", "utf8");
701
+ await writeFile3(filePath, lines.join("\n") + "\n", "utf8");
547
702
  }
548
703
  function freshLines(entries) {
549
704
  const out = [];
@@ -598,27 +753,27 @@ async function resolveInitTimePath(input) {
598
753
  return { path: input.envValue, source: "env", ...input.explain ? { chain } : {} };
599
754
  }
600
755
  if (input.explain) chain.push({ source: "env", matched: false });
601
- const sw = await parseDotenvFile(join2(input.home, ".skillwiki", ".env"));
756
+ const sw = await parseDotenvFile(join4(input.home, ".skillwiki", ".env"));
602
757
  if (sw.WIKI_PATH !== void 0) {
603
758
  if (input.explain) chain.push({ source: "skillwiki-dotenv", matched: true, value: sw.WIKI_PATH });
604
759
  return { path: sw.WIKI_PATH, source: "skillwiki-dotenv", ...input.explain ? { chain } : {} };
605
760
  }
606
761
  if (input.explain) chain.push({ source: "skillwiki-dotenv", matched: false });
607
- const hermes = await parseDotenvFile(join2(input.home, ".hermes", ".env"));
762
+ const hermes = await parseDotenvFile(join4(input.home, ".hermes", ".env"));
608
763
  if (hermes.WIKI_PATH !== void 0) {
609
764
  if (input.explain) chain.push({ source: "hermes-dotenv", matched: true, value: hermes.WIKI_PATH });
610
765
  return { path: hermes.WIKI_PATH, source: "hermes-dotenv", ...input.explain ? { chain } : {} };
611
766
  }
612
767
  if (input.explain) chain.push({ source: "hermes-dotenv", matched: false });
613
768
  if (input.cwd) {
614
- const projCfg = await parseDotenvFile(join2(input.cwd, ".skillwiki", ".env"));
769
+ const projCfg = await parseDotenvFile(join4(input.cwd, ".skillwiki", ".env"));
615
770
  if (projCfg.WIKI_PATH !== void 0) {
616
771
  if (input.explain) chain.push({ source: "project-dotenv", matched: true, value: projCfg.WIKI_PATH });
617
772
  return { path: projCfg.WIKI_PATH, source: "project-dotenv", ...input.explain ? { chain } : {} };
618
773
  }
619
774
  }
620
775
  if (input.explain) chain.push({ source: "project-dotenv", matched: false });
621
- const fallback = join2(input.home, "wiki");
776
+ const fallback = join4(input.home, "wiki");
622
777
  if (input.explain) chain.push({ source: "default", matched: true, value: fallback });
623
778
  return { path: fallback, source: "default", ...input.explain ? { chain } : {} };
624
779
  }
@@ -629,7 +784,7 @@ async function resolveRuntimePath(input) {
629
784
  return ok({ path: input.flag, source: "flag", ...input.explain ? { chain } : {} });
630
785
  }
631
786
  if (input.explain) chain.push({ source: "flag", matched: false });
632
- const swGlobal = await parseDotenvFile(join2(input.home, ".skillwiki", ".env"));
787
+ const swGlobal = await parseDotenvFile(join4(input.home, ".skillwiki", ".env"));
633
788
  const wikiName = input.wiki;
634
789
  if (wikiName !== void 0 && wikiName.length > 0) {
635
790
  if (wikiName.toLowerCase() === "default") {
@@ -673,7 +828,7 @@ async function resolveRuntimePath(input) {
673
828
  }
674
829
  if (input.explain) chain.push({ source: "env", matched: false });
675
830
  if (input.cwd) {
676
- const projCfg = await parseDotenvFile(join2(input.cwd, ".skillwiki", ".env"));
831
+ const projCfg = await parseDotenvFile(join4(input.cwd, ".skillwiki", ".env"));
677
832
  if (projCfg.WIKI_PATH !== void 0) {
678
833
  if (input.explain) chain.push({ source: "project-dotenv", matched: true, value: projCfg.WIKI_PATH });
679
834
  return ok({ path: projCfg.WIKI_PATH, source: "project-dotenv", ...input.explain ? { chain } : {} });
@@ -788,7 +943,7 @@ function simulateRemoval(adj, removed) {
788
943
 
789
944
  // src/commands/audit.ts
790
945
  import { readFile as readFile5, stat as stat2 } from "fs/promises";
791
- import { dirname as dirname3, resolve, join as join3 } from "path";
946
+ import { dirname as dirname3, resolve as resolve2, join as join5 } from "path";
792
947
 
793
948
  // src/parsers/citations.ts
794
949
  var FENCE2 = /```[\s\S]*?```/g;
@@ -895,12 +1050,12 @@ async function runAudit(input) {
895
1050
  if (!fm.ok) return { exitCode: ExitCode.INVALID_FRONTMATTER, result: fm };
896
1051
  const split = splitFrontmatter(text);
897
1052
  const body = split.ok ? split.data.body : text;
898
- const vault = await findVaultRoot(dirname3(resolve(input.file)));
1053
+ const vault = await findVaultRoot(dirname3(resolve2(input.file)));
899
1054
  if (!vault) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: err("VAULT_PATH_INVALID") };
900
1055
  const markers = extractCitationMarkers(body);
901
1056
  const resolved = await Promise.all(markers.map(async (m) => {
902
1057
  try {
903
- await stat2(join3(vault, m.target));
1058
+ await stat2(join5(vault, m.target));
904
1059
  return { ...m, resolved: true };
905
1060
  } catch {
906
1061
  return { ...m, resolved: false };
@@ -911,7 +1066,7 @@ async function runAudit(input) {
911
1066
  const unused_sources = sources.filter((s) => !referenced.has(s));
912
1067
  const missing_from_sources = [...referenced].filter((t) => !sources.includes(t));
913
1068
  const broken = resolved.filter((m) => !m.resolved);
914
- const footerMatch = body.match(/\n## Sources\n([\s\S]*)$/);
1069
+ const footerMatch = body.match(/\r?\n## Sources\r?\n([\s\S]*)$/);
915
1070
  let footer_consistency;
916
1071
  if (footerMatch) {
917
1072
  const footerTargets = /* @__PURE__ */ new Set();
@@ -945,7 +1100,7 @@ async function findVaultRoot(start) {
945
1100
  let cur = start;
946
1101
  for (let i = 0; i < 20; i++) {
947
1102
  try {
948
- await stat2(join3(cur, "SCHEMA.md"));
1103
+ await stat2(join5(cur, "SCHEMA.md"));
949
1104
  return cur;
950
1105
  } catch {
951
1106
  }
@@ -955,13 +1110,53 @@ async function findVaultRoot(start) {
955
1110
  }
956
1111
  return null;
957
1112
  }
1113
+ function stripWikilink(s) {
1114
+ return s.replace(/^\[\[/, "").replace(/(?:\|[^\[\]]*)?\]\]$/, "").trim();
1115
+ }
1116
+ async function validateCompoundReferences(vault) {
1117
+ const scan = await scanVault(vault);
1118
+ if (!scan.ok) return scan;
1119
+ const slugToPage = /* @__PURE__ */ new Map();
1120
+ const pathToPage = /* @__PURE__ */ new Map();
1121
+ for (const p of scan.data.workItems) {
1122
+ slugToPage.set(p.relPath.replace(/\.md$/, "").split("/").pop().toLowerCase(), p);
1123
+ pathToPage.set(p.relPath, p);
1124
+ }
1125
+ const findings = [];
1126
+ for (const cp of scan.data.compound) {
1127
+ const text = await readPage(cp);
1128
+ const fm = extractFrontmatter(text);
1129
+ if (!fm.ok) continue;
1130
+ const projectRaw = fm.data.project;
1131
+ const workItems = fm.data.work_items;
1132
+ if (!projectRaw || !workItems?.length) continue;
1133
+ const projSlug = stripWikilink(String(projectRaw));
1134
+ for (const wi of workItems) {
1135
+ const target = stripWikilink(wi);
1136
+ const withExt = target.endsWith(".md") ? target : target + ".md";
1137
+ const resolved = pathToPage.get(withExt) ?? slugToPage.get(target.split("/").pop().replace(/\.md$/, "").toLowerCase());
1138
+ if (!resolved) {
1139
+ findings.push({ compound: cp.relPath, work_item: wi, kind: "missing", detail: `no work item found for [[${target}]]` });
1140
+ continue;
1141
+ }
1142
+ const wiFm = extractFrontmatter(await readPage(resolved));
1143
+ if (wiFm.ok && wiFm.data.project) {
1144
+ const wiProj = stripWikilink(String(wiFm.data.project));
1145
+ if (wiProj !== projSlug) {
1146
+ findings.push({ compound: cp.relPath, work_item: wi, kind: "cross_project", detail: `compound project [[${projSlug}]] != work_item project [[${wiProj}]]` });
1147
+ }
1148
+ }
1149
+ }
1150
+ }
1151
+ return ok(findings);
1152
+ }
958
1153
 
959
1154
  // src/commands/install.ts
960
- import { readdir as readdir2, stat as stat4 } from "fs/promises";
961
- import { join as join4 } from "path";
1155
+ import { readdir as readdir2, stat as stat4, symlink, unlink, mkdir as mkdir4, readFile as readFile6 } from "fs/promises";
1156
+ import { join as join6, resolve as resolve3, dirname as dirname5 } from "path";
962
1157
 
963
1158
  // src/utils/install-fs.ts
964
- import { copyFile, mkdir as mkdir3, rename, writeFile as writeFile3, stat as stat3 } from "fs/promises";
1159
+ import { copyFile, mkdir as mkdir3, rename, writeFile as writeFile4, stat as stat3 } from "fs/promises";
965
1160
  import { dirname as dirname4 } from "path";
966
1161
  async function atomicCopyWithBackup(src, dst) {
967
1162
  await mkdir3(dirname4(dst), { recursive: true });
@@ -984,10 +1179,36 @@ async function atomicCopyWithBackup(src, dst) {
984
1179
  async function writeManifest(path, m) {
985
1180
  await mkdir3(dirname4(path), { recursive: true });
986
1181
  const enriched = { installed_at: (/* @__PURE__ */ new Date()).toISOString(), ...m };
987
- await writeFile3(path, JSON.stringify(enriched, null, 2));
1182
+ await writeFile4(path, JSON.stringify(enriched, null, 2));
988
1183
  }
989
1184
 
990
1185
  // src/commands/install.ts
1186
+ function parseSkillMeta(content) {
1187
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
1188
+ const meta = { name: "" };
1189
+ if (!fmMatch) return meta;
1190
+ const fm = fmMatch[1];
1191
+ const nameMatch = fm.match(/^name:\s*(.+)$/m);
1192
+ if (nameMatch) meta.name = nameMatch[1].trim();
1193
+ const versionMatch = fm.match(/^version:\s*(.+)$/m);
1194
+ if (versionMatch) meta.version = versionMatch[1].trim();
1195
+ const depMatch = fm.match(/^deprecated:\s*(.+)$/m);
1196
+ if (depMatch && /^(true|yes)$/i.test(depMatch[1].trim())) meta.deprecated = true;
1197
+ return meta;
1198
+ }
1199
+ async function createSymlink(src, dst) {
1200
+ await mkdir4(dirname5(dst), { recursive: true });
1201
+ try {
1202
+ await unlink(dst);
1203
+ } catch {
1204
+ }
1205
+ try {
1206
+ await symlink(resolve3(src), dst);
1207
+ } catch (e) {
1208
+ return err("SYMLINK_FAILED", { message: String(e) });
1209
+ }
1210
+ return ok({ linked: true });
1211
+ }
991
1212
  async function runInstall(input) {
992
1213
  let entries;
993
1214
  try {
@@ -1000,45 +1221,85 @@ async function runInstall(input) {
1000
1221
  }
1001
1222
  const installed = [];
1002
1223
  const backed_up = [];
1224
+ const version_warnings = [];
1225
+ const skillMetas = {};
1003
1226
  for (const name of entries) {
1004
- const src = join4(input.skillsRoot, name, "SKILL.md");
1005
- const dst = join4(input.target, name, "SKILL.md");
1227
+ const src = join6(input.skillsRoot, name, "SKILL.md");
1228
+ const dst = join6(input.target, name, "SKILL.md");
1006
1229
  try {
1007
1230
  await stat4(src);
1008
1231
  } catch {
1009
1232
  return { exitCode: ExitCode.PREFLIGHT_FAILED, result: err("PREFLIGHT_FAILED", { missing: src }) };
1010
1233
  }
1234
+ try {
1235
+ const content = await readFile6(src, "utf8");
1236
+ const meta = parseSkillMeta(content);
1237
+ meta.name = meta.name || name;
1238
+ skillMetas[name] = meta;
1239
+ if (meta.deprecated) {
1240
+ version_warnings.push(`${name}: DEPRECATED \u2014 will be removed in a future release`);
1241
+ }
1242
+ if (!input.dryRun) {
1243
+ try {
1244
+ const existingContent = await readFile6(dst, "utf8");
1245
+ const existingMeta = parseSkillMeta(existingContent);
1246
+ if (existingMeta.version && meta.version && existingMeta.version !== meta.version) {
1247
+ version_warnings.push(`${name}: version changed ${existingMeta.version} \u2192 ${meta.version}`);
1248
+ }
1249
+ } catch {
1250
+ }
1251
+ }
1252
+ } catch {
1253
+ }
1011
1254
  if (input.dryRun) {
1012
1255
  installed.push(dst);
1013
1256
  continue;
1014
1257
  }
1015
- const r = await atomicCopyWithBackup(src, dst);
1016
- if (!r.ok) return { exitCode: ExitCode.ATOMIC_COPY_FAILED, result: r };
1017
- installed.push(dst);
1018
- if (r.data.backupPath) backed_up.push(r.data.backupPath);
1258
+ if (input.symlink) {
1259
+ const r = await createSymlink(src, dst);
1260
+ if (!r.ok) return { exitCode: ExitCode.SYMLINK_FAILED, result: r };
1261
+ installed.push(dst);
1262
+ } else {
1263
+ const r = await atomicCopyWithBackup(src, dst);
1264
+ if (!r.ok) return { exitCode: ExitCode.ATOMIC_COPY_FAILED, result: r };
1265
+ installed.push(dst);
1266
+ if (r.data.backupPath) backed_up.push(r.data.backupPath);
1267
+ }
1019
1268
  }
1020
- const binSrc = join4(input.skillsRoot, "bin", "skillwiki");
1269
+ const binSrc = join6(input.skillsRoot, "bin", "skillwiki");
1021
1270
  try {
1022
1271
  await stat4(binSrc);
1023
- const binDst = join4(input.target, "bin", "skillwiki");
1272
+ const binDst = join6(input.target, "bin", "skillwiki");
1024
1273
  if (!input.dryRun) {
1025
- const r = await atomicCopyWithBackup(binSrc, binDst);
1026
- if (!r.ok) return { exitCode: ExitCode.ATOMIC_COPY_FAILED, result: r };
1027
- installed.push(binDst);
1028
- if (r.data.backupPath) backed_up.push(r.data.backupPath);
1274
+ if (input.symlink) {
1275
+ const r = await createSymlink(binSrc, binDst);
1276
+ if (!r.ok) return { exitCode: ExitCode.SYMLINK_FAILED, result: r };
1277
+ installed.push(binDst);
1278
+ } else {
1279
+ const r = await atomicCopyWithBackup(binSrc, binDst);
1280
+ if (!r.ok) return { exitCode: ExitCode.ATOMIC_COPY_FAILED, result: r };
1281
+ installed.push(binDst);
1282
+ if (r.data.backupPath) backed_up.push(r.data.backupPath);
1283
+ }
1029
1284
  } else {
1030
1285
  installed.push(binDst);
1031
1286
  }
1032
1287
  } catch {
1033
1288
  }
1034
- const manifest_path = join4(input.target, "wiki-manifest.json");
1035
- if (!input.dryRun) await writeManifest(manifest_path, { installed, backed_up });
1289
+ const manifest_path = join6(input.target, "wiki-manifest.json");
1290
+ if (!input.dryRun) await writeManifest(manifest_path, { installed, backed_up, symlink: input.symlink || void 0, skills: skillMetas });
1291
+ const mode = input.symlink ? "symlink (dev mode)" : "copy";
1036
1292
  const hintLines = [
1037
- `installed: ${installed.length}`,
1293
+ `installed: ${installed.length} (${mode})`,
1038
1294
  input.dryRun ? "(dry run)" : `backed up: ${backed_up.length}`,
1039
1295
  `manifest: ${manifest_path}`
1040
1296
  ];
1041
- return { exitCode: ExitCode.OK, result: ok({ installed, backed_up, manifest_path, humanHint: hintLines.join("\n") }) };
1297
+ if (version_warnings.length > 0) {
1298
+ hintLines.push(`version warnings: ${version_warnings.length}`);
1299
+ for (const w of version_warnings) hintLines.push(` ${w}`);
1300
+ }
1301
+ const exitCode = version_warnings.length > 0 ? ExitCode.SKILL_VERSION_MISMATCH : ExitCode.OK;
1302
+ return { exitCode, result: ok({ installed, backed_up, manifest_path, version_warnings, humanHint: hintLines.join("\n") }) };
1042
1303
  }
1043
1304
 
1044
1305
  // src/commands/path.ts
@@ -1067,7 +1328,7 @@ async function runPath(input) {
1067
1328
  }
1068
1329
 
1069
1330
  // src/utils/lang.ts
1070
- import { join as join5 } from "path";
1331
+ import { join as join7 } from "path";
1071
1332
  var ALIASES = {
1072
1333
  english: "en",
1073
1334
  en: "en",
@@ -1090,7 +1351,7 @@ async function resolveLang(input) {
1090
1351
  if (input.envValue !== void 0 && input.envValue.length > 0) {
1091
1352
  return { value: input.envValue, source: "env", canonical: normalizeLang(input.envValue) };
1092
1353
  }
1093
- const dotenv = await parseDotenvFile(join5(input.home, ".skillwiki", ".env"));
1354
+ const dotenv = await parseDotenvFile(join7(input.home, ".skillwiki", ".env"));
1094
1355
  if (dotenv.WIKI_LANG !== void 0) {
1095
1356
  return { value: dotenv.WIKI_LANG, source: "skillwiki-dotenv", canonical: normalizeLang(dotenv.WIKI_LANG) };
1096
1357
  }
@@ -1098,7 +1359,7 @@ async function resolveLang(input) {
1098
1359
  }
1099
1360
 
1100
1361
  // src/commands/lang.ts
1101
- import { join as join6 } from "path";
1362
+ import { join as join8 } from "path";
1102
1363
  async function runLang(input) {
1103
1364
  const resolved = await resolveLang({ flag: input.flag, envValue: input.envValue, home: input.home });
1104
1365
  let chain;
@@ -1107,7 +1368,7 @@ async function runLang(input) {
1107
1368
  { source: "flag", matched: input.flag !== void 0 && input.flag.length > 0, value: input.flag },
1108
1369
  { source: "env", matched: input.envValue !== void 0 && input.envValue.length > 0, value: input.envValue }
1109
1370
  ];
1110
- const sw = await parseDotenvFile(join6(input.home, ".skillwiki", ".env"));
1371
+ const sw = await parseDotenvFile(join8(input.home, ".skillwiki", ".env"));
1111
1372
  chain.push({ source: "skillwiki-dotenv", matched: sw.WIKI_LANG !== void 0, value: sw.WIKI_LANG });
1112
1373
  chain.push({ source: "default", matched: resolved.source === "default", value: "en" });
1113
1374
  }
@@ -1124,8 +1385,8 @@ async function runLang(input) {
1124
1385
  }
1125
1386
 
1126
1387
  // src/commands/init.ts
1127
- import { mkdir as mkdir4, readFile as readFile6, readdir as readdir3, writeFile as writeFile4 } from "fs/promises";
1128
- import { join as join7 } from "path";
1388
+ import { mkdir as mkdir5, readFile as readFile7, readdir as readdir3, writeFile as writeFile5 } from "fs/promises";
1389
+ import { join as join10 } from "path";
1129
1390
 
1130
1391
  // src/parsers/taxonomy.ts
1131
1392
  import yaml2 from "js-yaml";
@@ -1152,6 +1413,48 @@ function extractTaxonomy(schemaText) {
1152
1413
  return ok(tax);
1153
1414
  }
1154
1415
 
1416
+ // src/utils/last-op.ts
1417
+ import { readFileSync as readFileSync2, writeFileSync, mkdirSync, unlinkSync, existsSync } from "fs";
1418
+ import { join as join9 } from "path";
1419
+ var LAST_OP_DIR = ".skillwiki";
1420
+ var LAST_OP_FILE = "last-op.json";
1421
+ function lastOpPath(vault) {
1422
+ return join9(vault, LAST_OP_DIR, LAST_OP_FILE);
1423
+ }
1424
+ function readLastOp(vault) {
1425
+ const p = lastOpPath(vault);
1426
+ if (!existsSync(p)) return [];
1427
+ try {
1428
+ const raw = readFileSync2(p, "utf8");
1429
+ const parsed = JSON.parse(raw);
1430
+ if (!Array.isArray(parsed)) {
1431
+ unlinkSync(p);
1432
+ return [];
1433
+ }
1434
+ return parsed;
1435
+ } catch {
1436
+ try {
1437
+ unlinkSync(p);
1438
+ } catch {
1439
+ }
1440
+ return [];
1441
+ }
1442
+ }
1443
+ function appendLastOp(vault, entry) {
1444
+ const existing = readLastOp(vault);
1445
+ existing.push(entry);
1446
+ const dir = join9(vault, LAST_OP_DIR);
1447
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1448
+ writeFileSync(lastOpPath(vault), JSON.stringify(existing, null, 2), "utf8");
1449
+ }
1450
+ function clearLastOp(vault) {
1451
+ const p = lastOpPath(vault);
1452
+ try {
1453
+ unlinkSync(p);
1454
+ } catch {
1455
+ }
1456
+ }
1457
+
1155
1458
  // src/commands/init.ts
1156
1459
  var DEFAULT_TAXONOMY = [
1157
1460
  "research",
@@ -1176,9 +1479,12 @@ var VAULT_DIRS = [
1176
1479
  "queries",
1177
1480
  "meta",
1178
1481
  "projects",
1179
- ".obsidian"
1482
+ ".obsidian",
1483
+ "_Templates"
1180
1484
  ];
1181
1485
  var ATTACHMENT_FOLDER = "raw/assets";
1486
+ var NEW_FILE_FOLDER = "raw/transcripts";
1487
+ var TEMPLATE_FOLDER = "_Templates";
1182
1488
  function extractDomainFromSchema(text) {
1183
1489
  const m = text.match(/^##\s+Domain\s*\n([\s\S]*?)(?=\n\n|\n##|\s*$)/m);
1184
1490
  if (!m) return "";
@@ -1191,13 +1497,13 @@ async function discoverTagsFromPages(target, knownSlugs) {
1191
1497
  for (const dir of ["entities", "concepts", "comparisons", "queries"]) {
1192
1498
  let entries;
1193
1499
  try {
1194
- entries = (await readdir3(join7(target, dir), { withFileTypes: true })).filter((e) => e.isFile() && e.name.endsWith(".md")).map((e) => e.name);
1500
+ entries = (await readdir3(join10(target, dir), { withFileTypes: true })).filter((e) => e.isFile() && e.name.endsWith(".md")).map((e) => e.name);
1195
1501
  } catch {
1196
1502
  continue;
1197
1503
  }
1198
1504
  for (const file of entries) {
1199
1505
  try {
1200
- const text = await readFile6(join7(target, dir, file), "utf8");
1506
+ const text = await readFile7(join10(target, dir, file), "utf8");
1201
1507
  const fm = extractFrontmatter(text);
1202
1508
  if (!fm.ok || !fm.data.tags || !Array.isArray(fm.data.tags)) continue;
1203
1509
  for (const t of fm.data.tags) {
@@ -1216,7 +1522,7 @@ async function runInit(input) {
1216
1522
  const canonicalLang = langRes.canonical;
1217
1523
  let oldSchemaText;
1218
1524
  try {
1219
- oldSchemaText = await readFile6(join7(target, "SCHEMA.md"), "utf8");
1525
+ oldSchemaText = await readFile7(join10(target, "SCHEMA.md"), "utf8");
1220
1526
  } catch {
1221
1527
  }
1222
1528
  if (oldSchemaText && !input.force) {
@@ -1225,21 +1531,23 @@ async function runInit(input) {
1225
1531
  result: err("INIT_TARGET_NOT_EMPTY", { target })
1226
1532
  };
1227
1533
  }
1228
- const envPath = join7(input.home, ".skillwiki", ".env");
1534
+ const envPath = join10(input.home, ".skillwiki", ".env");
1229
1535
  let existingEnvRaw = "";
1230
1536
  try {
1231
- existingEnvRaw = await readFile6(envPath, "utf8");
1537
+ existingEnvRaw = await readFile7(envPath, "utf8");
1232
1538
  } catch {
1233
1539
  }
1234
1540
  const existingEnv = parseDotenvText(existingEnvRaw);
1235
1541
  const swDotenvHadPath = existingEnv.WIKI_PATH !== void 0;
1236
- if (!input.profile && existingEnv.WIKI_PATH !== void 0 && existingEnv.WIKI_PATH !== target && !input.force) {
1542
+ const explicitTarget = !!input.flag;
1543
+ const skipConflictCheck = explicitTarget || !!input.noEnv;
1544
+ if (!input.profile && !skipConflictCheck && existingEnv.WIKI_PATH !== void 0 && existingEnv.WIKI_PATH !== target && !input.force) {
1237
1545
  return {
1238
1546
  exitCode: ExitCode.ENV_WRITE_CONFLICT,
1239
1547
  result: err("ENV_WRITE_CONFLICT", { key: "WIKI_PATH", existing: existingEnv.WIKI_PATH, attempted: target })
1240
1548
  };
1241
1549
  }
1242
- if (!input.profile && existingEnv.WIKI_LANG !== void 0 && existingEnv.WIKI_LANG !== canonicalLang && !input.force) {
1550
+ if (!input.profile && !skipConflictCheck && existingEnv.WIKI_LANG !== void 0 && existingEnv.WIKI_LANG !== canonicalLang && !input.force) {
1243
1551
  return {
1244
1552
  exitCode: ExitCode.ENV_WRITE_CONFLICT,
1245
1553
  result: err("ENV_WRITE_CONFLICT", { key: "WIKI_LANG", existing: existingEnv.WIKI_LANG, attempted: canonicalLang })
@@ -1247,9 +1555,9 @@ async function runInit(input) {
1247
1555
  }
1248
1556
  const created = [];
1249
1557
  try {
1250
- await mkdir4(target, { recursive: true });
1558
+ await mkdir5(target, { recursive: true });
1251
1559
  for (const d of VAULT_DIRS) {
1252
- await mkdir4(join7(target, d), { recursive: true });
1560
+ await mkdir5(join10(target, d), { recursive: true });
1253
1561
  created.push(d + "/");
1254
1562
  }
1255
1563
  } catch (e) {
@@ -1278,9 +1586,9 @@ async function runInit(input) {
1278
1586
  const discovered_tags = discovered.length;
1279
1587
  const fullTaxonomyYaml = discovered.length > 0 ? taxonomy.map((t) => ` - ${t}`).join("\n") + "\n # --- Discovered from existing pages ---\n" + discovered.map((t) => ` - ${t}`).join("\n") : taxonomy.map((t) => ` - ${t}`).join("\n");
1280
1588
  try {
1281
- const schemaTpl = await readFile6(join7(input.templates, "SCHEMA.md"), "utf8");
1589
+ const schemaTpl = await readFile7(join10(input.templates, "SCHEMA.md"), "utf8");
1282
1590
  const schema = schemaTpl.replace("{{DOMAIN}}", domain).replace("{{WIKI_LANG}}", canonicalLang).replace("{{TAXONOMY_YAML}}", fullTaxonomyYaml);
1283
- await writeFile4(join7(target, "SCHEMA.md"), schema, "utf8");
1591
+ await writeFile5(join10(target, "SCHEMA.md"), schema, "utf8");
1284
1592
  created.push("SCHEMA.md");
1285
1593
  } catch (e) {
1286
1594
  return { exitCode: ExitCode.WRITE_FAILED, result: err("WRITE_FAILED", { file: "SCHEMA.md", message: String(e) }) };
@@ -1288,7 +1596,7 @@ async function runInit(input) {
1288
1596
  const preserved = [];
1289
1597
  async function writeOrPreserve(fileName, render) {
1290
1598
  try {
1291
- const existing = await readFile6(join7(target, fileName), "utf8");
1599
+ const existing = await readFile7(join10(target, fileName), "utf8");
1292
1600
  if (existing.split("\n").length > 10) {
1293
1601
  preserved.push(fileName);
1294
1602
  return void 0;
@@ -1296,7 +1604,7 @@ async function runInit(input) {
1296
1604
  } catch {
1297
1605
  }
1298
1606
  try {
1299
- await writeFile4(join7(target, fileName), await render(), "utf8");
1607
+ await writeFile5(join10(target, fileName), await render(), "utf8");
1300
1608
  created.push(fileName);
1301
1609
  return void 0;
1302
1610
  } catch (e) {
@@ -1304,20 +1612,37 @@ async function runInit(input) {
1304
1612
  }
1305
1613
  }
1306
1614
  const err1 = await writeOrPreserve("index.md", async () => {
1307
- const tpl = await readFile6(join7(input.templates, "index.md"), "utf8");
1615
+ const tpl = await readFile7(join10(input.templates, "index.md"), "utf8");
1308
1616
  return tpl.replace("{{INIT_DATE}}", today);
1309
1617
  });
1310
1618
  if (err1) return err1;
1311
1619
  const errObsidian = await writeOrPreserve(".obsidian/app.json", async () => {
1312
- return JSON.stringify({ attachmentFolderPath: ATTACHMENT_FOLDER }, null, 2) + "\n";
1620
+ return JSON.stringify({ attachmentFolderPath: ATTACHMENT_FOLDER, newFileLocation: "folder", newFileFolderPath: NEW_FILE_FOLDER }, null, 2) + "\n";
1313
1621
  });
1314
1622
  if (errObsidian) return errObsidian;
1623
+ const errTemplatesJson = await writeOrPreserve(".obsidian/templates.json", async () => {
1624
+ return JSON.stringify({ folder: TEMPLATE_FOLDER }, null, 2) + "\n";
1625
+ });
1626
+ if (errTemplatesJson) return errTemplatesJson;
1627
+ const errTemplate = await writeOrPreserve(`${TEMPLATE_FOLDER}/tpl-ad-hoc-capture.md`, async () => {
1628
+ return [
1629
+ "---",
1630
+ "source_url:",
1631
+ "ingested: {{date:YYYY-MM-DD}}",
1632
+ "kind: # idea | bug | task | note | other",
1633
+ 'project: # optional: "[[slug]]"',
1634
+ "---",
1635
+ "",
1636
+ ""
1637
+ ].join("\n");
1638
+ });
1639
+ if (errTemplate) return errTemplate;
1315
1640
  const err22 = await writeOrPreserve("log.md", async () => {
1316
- const tpl = await readFile6(join7(input.templates, "log.md"), "utf8");
1641
+ const tpl = await readFile7(join10(input.templates, "log.md"), "utf8");
1317
1642
  return tpl.replace(/\{\{INIT_DATE\}\}/g, today).replace("{{DOMAIN}}", domain).replace("{{WIKI_LANG}}", canonicalLang);
1318
1643
  });
1319
1644
  if (err22) return err22;
1320
- const skipEnv = !!input.noEnv;
1645
+ const skipEnv = !!input.noEnv || explicitTarget && !input.profile && swDotenvHadPath && !input.force;
1321
1646
  let envWritten = "";
1322
1647
  if (!skipEnv) {
1323
1648
  try {
@@ -1345,6 +1670,14 @@ async function runInit(input) {
1345
1670
  `discovered tags: ${discovered_tags}`,
1346
1671
  skipEnv ? "env: skipped" : `env: ${envWritten}`
1347
1672
  ].join("\n");
1673
+ if (created.length > 0) {
1674
+ appendLastOp(target, {
1675
+ operation: "init",
1676
+ summary: `initialized vault: ${domain}`,
1677
+ files: created,
1678
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1679
+ });
1680
+ }
1348
1681
  return {
1349
1682
  exitCode: ExitCode.OK,
1350
1683
  result: ok({
@@ -1358,7 +1691,8 @@ async function runInit(input) {
1358
1691
  env_skipped: skipEnv,
1359
1692
  imported_from_hermes: importedFromHermes,
1360
1693
  discovered_tags,
1361
- humanHint
1694
+ humanHint,
1695
+ templates_created: created.includes(`${TEMPLATE_FOLDER}/tpl-ad-hoc-capture.md`)
1362
1696
  })
1363
1697
  };
1364
1698
  }
@@ -1401,12 +1735,12 @@ ${broken.map((b) => ` ${b.page}:[[${b.slug}]] (line ${b.line})`).join("\n")}` }
1401
1735
  }
1402
1736
 
1403
1737
  // src/commands/tag-audit.ts
1404
- import { readFile as readFile7 } from "fs/promises";
1405
- import { join as join8 } from "path";
1738
+ import { readFile as readFile8 } from "fs/promises";
1739
+ import { join as join11 } from "path";
1406
1740
  async function runTagAudit(input) {
1407
1741
  const scan = await scanVault(input.vault);
1408
1742
  if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
1409
- const schemaText = await readFile7(join8(input.vault, "SCHEMA.md"), "utf8");
1743
+ const schemaText = await readFile8(join11(input.vault, "SCHEMA.md"), "utf8");
1410
1744
  const tax = extractTaxonomy(schemaText);
1411
1745
  if (!tax.ok) return { exitCode: ExitCode.INVALID_FRONTMATTER, result: tax };
1412
1746
  const allowed = new Set(tax.data);
@@ -1430,14 +1764,14 @@ async function runTagAudit(input) {
1430
1764
  }
1431
1765
 
1432
1766
  // src/commands/index-check.ts
1433
- import { readFile as readFile8 } from "fs/promises";
1434
- import { join as join9 } from "path";
1767
+ import { readFile as readFile9 } from "fs/promises";
1768
+ import { join as join12 } from "path";
1435
1769
  async function runIndexCheck(input) {
1436
1770
  const scan = await scanVault(input.vault);
1437
1771
  if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
1438
1772
  let indexText = "";
1439
1773
  try {
1440
- indexText = await readFile8(join9(input.vault, "index.md"), "utf8");
1774
+ indexText = await readFile9(join12(input.vault, "index.md"), "utf8");
1441
1775
  } catch {
1442
1776
  }
1443
1777
  const indexSlugsLower = /* @__PURE__ */ new Map();
@@ -1446,12 +1780,18 @@ async function runIndexCheck(input) {
1446
1780
  indexSlugsLower.set(tail.toLowerCase(), tail);
1447
1781
  }
1448
1782
  const fileSlugs = /* @__PURE__ */ new Map();
1783
+ const requiredSlugs = /* @__PURE__ */ new Map();
1449
1784
  for (const p of scan.data.typedKnowledge) {
1450
1785
  const slug = p.relPath.replace(/\.md$/, "").split("/").pop();
1451
1786
  fileSlugs.set(slug, p.relPath);
1787
+ requiredSlugs.set(slug, p.relPath);
1788
+ }
1789
+ for (const p of scan.data.compound) {
1790
+ const slug = p.relPath.replace(/\.md$/, "").split("/").pop();
1791
+ fileSlugs.set(slug, p.relPath);
1452
1792
  }
1453
1793
  const missing_from_index = [];
1454
- for (const [slug, relPath] of fileSlugs.entries()) {
1794
+ for (const [slug, relPath] of requiredSlugs.entries()) {
1455
1795
  if (!indexSlugsLower.has(slug.toLowerCase())) missing_from_index.push(relPath);
1456
1796
  }
1457
1797
  const fileSlugsLower = new Set([...fileSlugs.keys()].map((s) => s.toLowerCase()));
@@ -1470,44 +1810,176 @@ async function runIndexCheck(input) {
1470
1810
  }
1471
1811
 
1472
1812
  // src/commands/stale.ts
1473
- import { readFile as readFile9 } from "fs/promises";
1474
- import { join as join10 } from "path";
1475
- function dayDiff(a, b) {
1476
- const da = Date.parse(a);
1477
- const db = Date.parse(b);
1478
- return Math.round((db - da) / 864e5);
1813
+ import { readdir as readdir4, rename as rename2, mkdir as mkdir6, readFile as readFile10 } from "fs/promises";
1814
+ import { join as join13 } from "path";
1815
+ function daysSince(isoDate2) {
1816
+ return Math.floor((Date.now() - Date.parse(isoDate2)) / 864e5);
1479
1817
  }
1480
1818
  async function runStale(input) {
1481
1819
  const scan = await scanVault(input.vault);
1482
1820
  if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
1483
- const stale = [];
1484
- for (const p of scan.data.typedKnowledge) {
1485
- const fm = extractFrontmatter(await readPage(p));
1486
- if (!fm.ok) continue;
1487
- const updated = typeof fm.data.updated === "string" ? fm.data.updated : void 0;
1488
- const sources = Array.isArray(fm.data.sources) ? fm.data.sources.filter((s) => typeof s === "string") : [];
1489
- if (!updated || sources.length === 0) continue;
1490
- let newest;
1491
- for (const rel of sources) {
1492
- let raw;
1821
+ const staleTranscripts = [];
1822
+ const incompleteWorkItems = [];
1823
+ const archived = [];
1824
+ const workDirs = /* @__PURE__ */ new Map();
1825
+ const projectsDir = join13(input.vault, "projects");
1826
+ let projectSlugs = [];
1827
+ try {
1828
+ projectSlugs = (await readdir4(projectsDir, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name);
1829
+ } catch {
1830
+ }
1831
+ for (const slug of projectSlugs) {
1832
+ const workPath = join13(projectsDir, slug, "work");
1833
+ let entries;
1834
+ try {
1835
+ entries = await readdir4(workPath, { withFileTypes: true });
1836
+ } catch {
1837
+ continue;
1838
+ }
1839
+ for (const e of entries) {
1840
+ if (!e.isDirectory()) continue;
1841
+ const relDir = `projects/${slug}/work/${e.name}`;
1842
+ const absDir = join13(workPath, e.name);
1843
+ let status = "";
1844
+ let files;
1493
1845
  try {
1494
- raw = await readFile9(join10(input.vault, rel), "utf8");
1846
+ files = await readdir4(absDir);
1495
1847
  } catch {
1848
+ workDirs.set(relDir, "");
1496
1849
  continue;
1497
1850
  }
1498
- const rfm = extractFrontmatter(raw);
1499
- if (!rfm.ok) continue;
1500
- const ing = typeof rfm.data.ingested === "string" ? rfm.data.ingested : void 0;
1501
- if (ing && (!newest || Date.parse(ing) > Date.parse(newest))) newest = ing;
1851
+ for (const f of files) {
1852
+ if (!f.endsWith(".md")) continue;
1853
+ try {
1854
+ const fm = extractFrontmatter(await readFile10(join13(absDir, f), "utf8"));
1855
+ if (fm.ok && typeof fm.data.status === "string") {
1856
+ status = fm.data.status;
1857
+ break;
1858
+ }
1859
+ } catch {
1860
+ }
1861
+ }
1862
+ workDirs.set(relDir, status);
1863
+ }
1864
+ }
1865
+ const transcripts = scan.data.raw.filter((p) => p.relPath.startsWith("raw/transcripts/") && p.relPath.endsWith(".md"));
1866
+ for (const t of transcripts) {
1867
+ const datePrefix = t.relPath.split("/").pop().slice(0, 10);
1868
+ for (const [dir, status] of workDirs) {
1869
+ if (dir.split("/").pop().startsWith(datePrefix) && (status === "done" || status === "invalid")) {
1870
+ staleTranscripts.push({ path: t.relPath, reason: `work item ${dir} is ${status}` });
1871
+ break;
1872
+ }
1873
+ }
1874
+ }
1875
+ const doneWorkItems = [];
1876
+ for (const [relDir, status] of workDirs) {
1877
+ const dirName = relDir.split("/").pop();
1878
+ const dateStr = dirName.slice(0, 10);
1879
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) continue;
1880
+ if (daysSince(dateStr) < input.days) continue;
1881
+ let files;
1882
+ try {
1883
+ files = await readdir4(join13(input.vault, relDir));
1884
+ } catch {
1885
+ continue;
1886
+ }
1887
+ const hasSpec = files.includes("spec.md"), hasPlan = files.includes("plan.md"), hasWI = files.includes("work-item.md");
1888
+ if (status === "done") {
1889
+ doneWorkItems.push({ path: relDir, reason: "completed \u2014 should be archived" });
1890
+ } else if (status === "invalid") {
1891
+ doneWorkItems.push({ path: relDir, reason: "invalid \u2014 should be archived" });
1892
+ } else if (hasSpec && !hasPlan) {
1893
+ incompleteWorkItems.push({ path: relDir, reason: "has spec but no plan" });
1894
+ } else if (hasWI && !hasSpec && !hasPlan) {
1895
+ incompleteWorkItems.push({ path: relDir, reason: "only work-item.md, no spec or plan" });
1896
+ }
1897
+ }
1898
+ const stale = [];
1899
+ for (const page of scan.data.typedKnowledge) {
1900
+ try {
1901
+ const text = await readFile10(join13(input.vault, page.relPath), "utf8");
1902
+ const fm = extractFrontmatter(text);
1903
+ if (fm.ok && typeof fm.data.updated === "string") {
1904
+ const age = daysSince(fm.data.updated);
1905
+ if (age >= input.days) {
1906
+ stale.push({ page: page.relPath, reason: `updated ${age} days ago (threshold: ${input.days})` });
1907
+ }
1908
+ }
1909
+ } catch {
1910
+ }
1911
+ }
1912
+ if (input.archive) {
1913
+ const archiveDir = join13(input.vault, "_archive", (/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
1914
+ await mkdir6(archiveDir, { recursive: true });
1915
+ const citedRawPaths = /* @__PURE__ */ new Set();
1916
+ for (const page of scan.data.typedKnowledge) {
1917
+ const text = await readFile10(join13(input.vault, page.relPath), "utf8").catch(() => "");
1918
+ for (const line of text.split("\n")) {
1919
+ for (const m of line.matchAll(/\^\[(raw\/[^\]]+)\]/g)) {
1920
+ citedRawPaths.add(m[1]);
1921
+ }
1922
+ for (const m of line.matchAll(/raw\/[^\s,\]"]+\.md/g)) {
1923
+ citedRawPaths.add(m[0]);
1924
+ }
1925
+ }
1926
+ }
1927
+ for (const t of staleTranscripts) {
1928
+ if (citedRawPaths.has(t.path) || citedRawPaths.has(t.path.replace(/\.md$/, ""))) continue;
1929
+ const dest = join13(archiveDir, t.path.split("/").pop());
1930
+ try {
1931
+ await rename2(join13(input.vault, t.path), dest);
1932
+ archived.push(t.path);
1933
+ } catch {
1934
+ }
1502
1935
  }
1503
- if (!newest) continue;
1504
- const gap = dayDiff(updated, newest);
1505
- if (gap > input.days) {
1506
- stale.push({ page: p.relPath, page_updated: updated, newest_source_ingested: newest, gap_days: gap });
1936
+ for (const w of [...incompleteWorkItems, ...doneWorkItems]) {
1937
+ const parts = w.path.split("/");
1938
+ if (parts.length >= 4 && parts[0] === "projects") {
1939
+ const slug = parts[1];
1940
+ const itemName = parts[3];
1941
+ const histDir = join13(input.vault, "projects", slug, "history", "archived-work");
1942
+ await mkdir6(histDir, { recursive: true });
1943
+ const dest = join13(histDir, itemName);
1944
+ try {
1945
+ await rename2(join13(input.vault, w.path), dest);
1946
+ archived.push(w.path);
1947
+ } catch {
1948
+ }
1949
+ } else {
1950
+ const dest = join13(archiveDir, w.path.replace(/\//g, "_"));
1951
+ try {
1952
+ await rename2(join13(input.vault, w.path), dest);
1953
+ archived.push(w.path);
1954
+ } catch {
1955
+ }
1956
+ }
1507
1957
  }
1508
1958
  }
1509
- if (stale.length > 0) return { exitCode: ExitCode.STALE_PAGE, result: ok({ stale, humanHint: stale.map((s) => `${s.page} (${s.gap_days}d stale)`).join("\n") }) };
1510
- return { exitCode: ExitCode.OK, result: ok({ stale, humanHint: "no stale pages" }) };
1959
+ if (input.archive && archived.length > 0) {
1960
+ appendLastOp(input.vault, {
1961
+ operation: "stale-archive",
1962
+ summary: `archived ${archived.length} stale items`,
1963
+ files: archived,
1964
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1965
+ });
1966
+ }
1967
+ const total = stale.length + staleTranscripts.length + incompleteWorkItems.length + doneWorkItems.length;
1968
+ const hintLines = [];
1969
+ if (stale.length > 0) hintLines.push(`stale_pages: ${stale.length}`, ...stale.map((p) => ` ${p.page}: ${p.reason}`));
1970
+ if (staleTranscripts.length > 0) hintLines.push(`stale_transcripts: ${staleTranscripts.length}`, ...staleTranscripts.map((t) => ` ${t.path}: ${t.reason}`));
1971
+ if (incompleteWorkItems.length > 0) hintLines.push(`incomplete_work_items: ${incompleteWorkItems.length}`, ...incompleteWorkItems.map((w) => ` ${w.path}: ${w.reason}`));
1972
+ if (doneWorkItems.length > 0) hintLines.push(`done_work_items: ${doneWorkItems.length}`, ...doneWorkItems.map((w) => ` ${w.path}: ${w.reason}`));
1973
+ if (archived.length > 0) hintLines.push(`archived: ${archived.length}`, ...archived.map((a) => ` ${a}`));
1974
+ if (hintLines.length === 0) hintLines.push("no stale transcripts or incomplete work items");
1975
+ return { exitCode: total > 0 ? ExitCode.STALE_PAGE : ExitCode.OK, result: ok({
1976
+ stale: [...stale, ...staleTranscripts.map((t) => ({ page: t.path, reason: t.reason })), ...incompleteWorkItems.map((w) => ({ page: w.path, reason: w.reason })), ...doneWorkItems.map((w) => ({ page: w.path, reason: w.reason }))],
1977
+ stale_transcripts: staleTranscripts,
1978
+ incomplete_work_items: incompleteWorkItems,
1979
+ done_work_items: doneWorkItems,
1980
+ archived,
1981
+ humanHint: hintLines.join("\n")
1982
+ }) };
1511
1983
  }
1512
1984
 
1513
1985
  // src/commands/pagesize.ts
@@ -1527,19 +1999,19 @@ async function runPagesize(input) {
1527
1999
  }
1528
2000
 
1529
2001
  // src/commands/log-rotate.ts
1530
- import { readFile as readFile10, rename as rename2, writeFile as writeFile5, stat as stat5 } from "fs/promises";
1531
- import { join as join11 } from "path";
2002
+ import { readFile as readFile11, rename as rename3, writeFile as writeFile6, stat as stat5 } from "fs/promises";
2003
+ import { join as join14 } from "path";
1532
2004
  var ENTRY_RE = /^## \[(\d{4})-\d{2}-\d{2}\]/gm;
1533
2005
  async function runLogRotate(input) {
1534
2006
  try {
1535
- await stat5(join11(input.vault, "SCHEMA.md"));
2007
+ await stat5(join14(input.vault, "SCHEMA.md"));
1536
2008
  } catch {
1537
2009
  return { exitCode: ExitCode.VAULT_PATH_INVALID, result: err("VAULT_PATH_INVALID", { vault: input.vault }) };
1538
2010
  }
1539
- const logPath = join11(input.vault, "log.md");
2011
+ const logPath = join14(input.vault, "log.md");
1540
2012
  let logText;
1541
2013
  try {
1542
- logText = await readFile10(logPath, "utf8");
2014
+ logText = await readFile11(logPath, "utf8");
1543
2015
  } catch {
1544
2016
  return { exitCode: ExitCode.FILE_NOT_FOUND, result: err("FILE_NOT_FOUND", { path: logPath }) };
1545
2017
  }
@@ -1556,9 +2028,9 @@ async function runLogRotate(input) {
1556
2028
  }
1557
2029
  const newestYear = matches[matches.length - 1][1];
1558
2030
  const rotatedName = `log-${newestYear}.md`;
1559
- const rotatedPath = join11(input.vault, rotatedName);
2031
+ const rotatedPath = join14(input.vault, rotatedName);
1560
2032
  try {
1561
- await rename2(logPath, rotatedPath);
2033
+ await rename3(logPath, rotatedPath);
1562
2034
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1563
2035
  const fresh = `# Vault Log
1564
2036
 
@@ -1568,13 +2040,24 @@ Chronological action log. Newest entries last. Skill writes append entries; lint
1568
2040
 
1569
2041
  - Previous log moved to ${rotatedName}
1570
2042
  `;
1571
- await writeFile5(logPath, fresh, "utf8");
2043
+ await writeFile6(logPath, fresh, "utf8");
1572
2044
  } catch (e) {
1573
2045
  return { exitCode: ExitCode.WRITE_FAILED, result: err("WRITE_FAILED", { message: String(e) }) };
1574
2046
  }
2047
+ appendLastOp(input.vault, {
2048
+ operation: "log-rotate",
2049
+ summary: `rotated ${entries} entries to ${rotatedName}`,
2050
+ files: ["log.md", rotatedName],
2051
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2052
+ });
1575
2053
  return { exitCode: ExitCode.OK, result: ok({ entries, threshold: input.threshold, rotated: true, rotated_to: rotatedName, humanHint: `rotated ${entries} entries to ${rotatedName}` }) };
1576
2054
  }
1577
2055
 
2056
+ // src/commands/lint.ts
2057
+ import { existsSync as existsSync2 } from "fs";
2058
+ import { readFile as readFile13, writeFile as writeFile7 } from "fs/promises";
2059
+ import { join as join17 } from "path";
2060
+
1578
2061
  // src/commands/topic-map-check.ts
1579
2062
  var DEFAULT_THRESHOLD = 200;
1580
2063
  async function runTopicMapCheck(input) {
@@ -1595,13 +2078,13 @@ async function runTopicMapCheck(input) {
1595
2078
  }
1596
2079
 
1597
2080
  // src/commands/index-link-format.ts
1598
- import { readFile as readFile11 } from "fs/promises";
1599
- import { join as join12 } from "path";
2081
+ import { readFile as readFile12 } from "fs/promises";
2082
+ import { join as join15 } from "path";
1600
2083
  var MD_LINK_RE = /\[[^\[\]]+\]\([^)]+\.md\)/;
1601
2084
  async function runIndexLinkFormat(input) {
1602
2085
  let text = "";
1603
2086
  try {
1604
- text = await readFile11(join12(input.vault, "index.md"), "utf8");
2087
+ text = await readFile12(join15(input.vault, "index.md"), "utf8");
1605
2088
  } catch {
1606
2089
  }
1607
2090
  const markdown_links = [];
@@ -1614,8 +2097,8 @@ ${markdown_links.map((l) => ` line ${l.line}: ${l.text}`).join("\n")}`;
1614
2097
  }
1615
2098
 
1616
2099
  // src/commands/dedup.ts
1617
- import { readFileSync, writeFileSync, unlinkSync } from "fs";
1618
- import { join as join13 } from "path";
2100
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2 } from "fs";
2101
+ import { join as join16 } from "path";
1619
2102
  async function runDedup(input) {
1620
2103
  const scan = await scanVault(input.vault);
1621
2104
  if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
@@ -1643,7 +2126,7 @@ async function runDedup(input) {
1643
2126
  }
1644
2127
  }
1645
2128
  for (const page of scan.data.typedKnowledge) {
1646
- const text = readFileSync(join13(input.vault, page.relPath), "utf-8");
2129
+ const text = readFileSync3(join16(input.vault, page.relPath), "utf-8");
1647
2130
  let updated = text;
1648
2131
  let changed = false;
1649
2132
  for (const [oldPath, newPath] of replacements) {
@@ -1661,19 +2144,27 @@ async function runDedup(input) {
1661
2144
  }
1662
2145
  }
1663
2146
  if (changed) {
1664
- writeFileSync(join13(input.vault, page.relPath), updated);
2147
+ writeFileSync2(join16(input.vault, page.relPath), updated);
1665
2148
  rewired.push(page.relPath);
1666
2149
  }
1667
2150
  }
1668
2151
  for (const [oldPath] of replacements) {
1669
- const fullPath = join13(input.vault, oldPath);
2152
+ const fullPath = join16(input.vault, oldPath);
1670
2153
  try {
1671
- unlinkSync(fullPath);
2154
+ unlinkSync2(fullPath);
1672
2155
  removed.push(oldPath);
1673
2156
  } catch {
1674
2157
  }
1675
2158
  }
1676
2159
  }
2160
+ if (input.apply && (rewired.length > 0 || removed.length > 0)) {
2161
+ appendLastOp(input.vault, {
2162
+ operation: "dedup",
2163
+ summary: `rewired ${rewired.length} pages, removed ${removed.length} duplicates`,
2164
+ files: [...rewired, ...removed],
2165
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2166
+ });
2167
+ }
1677
2168
  const exitCode = duplicates.length > 0 ? input.apply ? ExitCode.DEDUP_APPLIED : ExitCode.RAW_DEDUP_DETECTED : ExitCode.OK;
1678
2169
  const hintLines = [`scanned: ${totalFiles} raw files`];
1679
2170
  if (duplicates.length > 0) {
@@ -1706,11 +2197,30 @@ function hasDuplicateFrontmatter(body) {
1706
2197
  }
1707
2198
  return false;
1708
2199
  }
1709
- var ERROR_ORDER = ["broken_wikilinks", "invalid_frontmatter", "raw_dedup", "tag_not_in_taxonomy"];
1710
- var WARNING_ORDER = ["index_incomplete", "index_link_format", "stale_page", "page_too_large", "log_rotate_needed", "orphans", "legacy_citation_style", "orphaned_citations", "duplicate_frontmatter", "missing_overview"];
2200
+ function extractSourceEntries(rawFm) {
2201
+ const lines = rawFm.split(/\r?\n/);
2202
+ const sourcesLineIdx = lines.findIndex((l) => /^sources:/.test(l));
2203
+ if (sourcesLineIdx === -1) return [];
2204
+ const sourcesLine = lines[sourcesLineIdx].trim();
2205
+ const inlineMatch = sourcesLine.match(/^sources:\s*\[(.+)]\s*$/);
2206
+ if (inlineMatch) {
2207
+ return [...inlineMatch[1].matchAll(/"[^"]*"|'[^']*'|[^,\s]\S*/g)].map((m) => m[0].replace(/,\s*$/, ""));
2208
+ }
2209
+ const entries = [];
2210
+ for (let i = sourcesLineIdx + 1; i < lines.length; i++) {
2211
+ const line = lines[i];
2212
+ if (!/^\s+- /.test(line)) break;
2213
+ entries.push(line.replace(/^\s+- /, "").trim());
2214
+ }
2215
+ return entries;
2216
+ }
2217
+ var ERROR_ORDER = ["broken_wikilinks", "invalid_frontmatter", "raw_dedup", "broken_sources", "tag_not_in_taxonomy"];
2218
+ var WARNING_ORDER = ["index_incomplete", "index_link_format", "stale_page", "page_too_large", "log_rotate_needed", "orphans", "compound_refs", "legacy_citation_style", "orphaned_citations", "duplicate_frontmatter", "work_item_health", "orphaned_project_pages", "missing_overview"];
1711
2219
  var INFO_ORDER = ["bridges", "page_structure", "topic_map_recommended", "frontmatter_wikilink", "wikilink_citation"];
1712
2220
  async function runLint(input) {
1713
2221
  const buckets = {};
2222
+ const fixed = [];
2223
+ const unresolved = [];
1714
2224
  const links = await runLinks({ vault: input.vault });
1715
2225
  if (links.result.ok && links.result.data.broken.length > 0) buckets.broken_wikilinks = links.result.data.broken;
1716
2226
  if (!links.result.ok && links.result.error === "INVALID_FRONTMATTER") {
@@ -1732,8 +2242,12 @@ async function runLint(input) {
1732
2242
  if (linkFmt.result.ok && linkFmt.result.data.markdown_links.length > 0) {
1733
2243
  buckets.index_link_format = linkFmt.result.data.markdown_links;
1734
2244
  }
1735
- const stale = await runStale({ vault: input.vault, days: input.days });
1736
- if (stale.result.ok && stale.result.data.stale.length > 0) buckets.stale_page = stale.result.data.stale;
2245
+ const staleResult = await runStale({ vault: input.vault, days: input.days });
2246
+ if (staleResult.result.ok) {
2247
+ const st = staleResult.result.data;
2248
+ const staleList = [...st.stale_transcripts.map((t) => t.path), ...st.incomplete_work_items.map((w) => w.path), ...(st.done_work_items ?? []).map((w) => w.path)];
2249
+ if (staleList.length > 0) buckets.stale_page = staleList;
2250
+ }
1737
2251
  const pagesize = await runPagesize({ vault: input.vault, lines: input.lines });
1738
2252
  if (pagesize.result.ok && pagesize.result.data.oversized.length > 0) buckets.page_too_large = pagesize.result.data.oversized;
1739
2253
  const rotate = await runLogRotate({ vault: input.vault, threshold: input.logThreshold, apply: false });
@@ -1751,6 +2265,8 @@ async function runLint(input) {
1751
2265
  }
1752
2266
  const dedup = await runDedup({ vault: input.vault });
1753
2267
  if (dedup.result.ok && dedup.result.data.duplicates.length > 0) buckets.raw_dedup = dedup.result.data.duplicates;
2268
+ const compoundRefs = await validateCompoundReferences(input.vault);
2269
+ if (compoundRefs.ok && compoundRefs.data.length > 0) buckets.compound_refs = compoundRefs.data;
1754
2270
  const scan = await scanVault(input.vault);
1755
2271
  const allPages = scan.ok ? [...scan.data.typedKnowledge, ...scan.data.raw, ...scan.data.workItems, ...scan.data.compound] : [];
1756
2272
  const slugs = scan.ok ? buildSlugMap(allPages) : /* @__PURE__ */ new Map();
@@ -1762,6 +2278,7 @@ async function runLint(input) {
1762
2278
  const noOverview = [];
1763
2279
  const fmWikilinkFlags = [];
1764
2280
  const wikilinkCitationFlags = [];
2281
+ const brokenSourceFlags = [];
1765
2282
  for (const page of scan.data.typedKnowledge) {
1766
2283
  const text = await readPage(page);
1767
2284
  const split = splitFrontmatter(text);
@@ -1772,6 +2289,15 @@ async function runLint(input) {
1772
2289
  if (isLegacyCitationStyle(body)) legacyPages.push(page.relPath);
1773
2290
  if (hasOrphanedCitations(body)) orphanedPages.push(page.relPath);
1774
2291
  if (hasWikilinkCitations(body)) wikilinkCitationFlags.push(page.relPath);
2292
+ const sourcesEntries = extractSourceEntries(rawFm);
2293
+ for (const entry of sourcesEntries) {
2294
+ let rawPath = entry.replace(/^"/, "").replace(/"$/, "").replace(/^'/, "").replace(/'$/, "");
2295
+ rawPath = rawPath.replace(/^\^\[/, "").replace(/\]$/, "");
2296
+ if (!rawPath.startsWith("raw/") && !rawPath.startsWith("_archive/raw/")) continue;
2297
+ if (!existsSync2(join17(input.vault, rawPath)) && !existsSync2(join17(input.vault, rawPath + ".md")) && !rawPath.startsWith("_archive/") && !existsSync2(join17(input.vault, "_archive", rawPath)) && !existsSync2(join17(input.vault, "_archive", rawPath + ".md"))) {
2298
+ brokenSourceFlags.push(`${page.relPath}: ${rawPath}`);
2299
+ }
2300
+ }
1775
2301
  const fmLinks = rawFm.match(/\[\[([^\[\]|]+)(?:\|[^\[\]]*)?\]\]/g) ?? [];
1776
2302
  for (const link of fmLinks) {
1777
2303
  const target = link.replace(/^\[\[/, "").replace(/(?:\|[^\[\]]*)?\]\]$/, "").trim();
@@ -1801,11 +2327,288 @@ async function runLint(input) {
1801
2327
  if (noOverview.length > 0) buckets.missing_overview = noOverview;
1802
2328
  if (fmWikilinkFlags.length > 0) buckets.frontmatter_wikilink = fmWikilinkFlags;
1803
2329
  if (wikilinkCitationFlags.length > 0) buckets.wikilink_citation = wikilinkCitationFlags;
1804
- }
1805
- const errorOut = ERROR_ORDER.flatMap((k) => buckets[k] ? [{ kind: k, items: buckets[k] }] : []);
1806
- const warningOut = WARNING_ORDER.flatMap((k) => buckets[k] ? [{ kind: k, items: buckets[k] }] : []);
1807
- const infoOut = INFO_ORDER.flatMap((k) => buckets[k] ? [{ kind: k, items: buckets[k] }] : []);
1808
- const summary = {
2330
+ if (brokenSourceFlags.length > 0) buckets.broken_sources = brokenSourceFlags;
2331
+ const workItemHealth = [];
2332
+ const workItemDirs = /* @__PURE__ */ new Map();
2333
+ for (const page of scan.data.workItems) {
2334
+ const dir = page.relPath.replace(/\/(spec|plan|log)\.md$/, "");
2335
+ const pages = workItemDirs.get(dir) ?? [];
2336
+ pages.push(page);
2337
+ workItemDirs.set(dir, pages);
2338
+ }
2339
+ for (const [dir, pages] of workItemDirs) {
2340
+ const hasSpec = pages.some((p) => p.relPath.endsWith("/spec.md"));
2341
+ const hasPlan = pages.some((p) => p.relPath.endsWith("/plan.md"));
2342
+ if (hasSpec && !hasPlan) {
2343
+ const lastSegment = dir.split("/").pop();
2344
+ const dateMatch = lastSegment.match(/^(\d{4}-\d{2}-\d{2})/);
2345
+ if (dateMatch) {
2346
+ const dirDate = Date.parse(dateMatch[1]);
2347
+ if (!isNaN(dirDate) && Date.now() - dirDate > 24 * 60 * 60 * 1e3) {
2348
+ workItemHealth.push(`${dir}/spec.md: has spec but no plan after 24h`);
2349
+ }
2350
+ }
2351
+ }
2352
+ for (const page of pages) {
2353
+ if (!page.relPath.endsWith("/spec.md")) continue;
2354
+ const text = await readPage(page);
2355
+ const fm = extractFrontmatter(text);
2356
+ if (fm.ok && fm.data.status === "in-progress" && !fm.data.started) {
2357
+ workItemHealth.push(`${page.relPath}: in-progress without started date`);
2358
+ }
2359
+ }
2360
+ }
2361
+ if (workItemHealth.length > 0) buckets.work_item_health = workItemHealth;
2362
+ const orphanedProjectPages = [];
2363
+ for (const page of scan.data.typedKnowledge) {
2364
+ const text = await readPage(page);
2365
+ const fm = extractFrontmatter(text);
2366
+ if (!fm.ok) continue;
2367
+ const pp = fm.data.provenance_projects;
2368
+ if (!Array.isArray(pp)) continue;
2369
+ for (const entry of pp) {
2370
+ const slugMatch = String(entry).match(/\[\[([^\]]+)\]\]/);
2371
+ if (!slugMatch) continue;
2372
+ const slug = slugMatch[1];
2373
+ const knowledgePath = join17(input.vault, "projects", slug, "knowledge.md");
2374
+ if (!existsSync2(knowledgePath)) continue;
2375
+ const pageRef = page.relPath.replace(/\.md$/, "");
2376
+ try {
2377
+ const knowledgeContent = await readFile13(knowledgePath, "utf8");
2378
+ if (!knowledgeContent.includes(`[[${pageRef}]]`)) {
2379
+ orphanedProjectPages.push(`${page.relPath}: not in projects/${slug}/knowledge.md`);
2380
+ }
2381
+ } catch {
2382
+ }
2383
+ }
2384
+ }
2385
+ if (orphanedProjectPages.length > 0) buckets.orphaned_project_pages = orphanedProjectPages;
2386
+ if (input.fix && legacyPages.length > 0) {
2387
+ const FENCE_RE2 = /```[\s\S]*?```/g;
2388
+ const INLINE_MARKER = /\^\[raw\/[^\]]+\]/g;
2389
+ for (const relPath of legacyPages) {
2390
+ try {
2391
+ const absPath = `${input.vault}/${relPath}`;
2392
+ const raw = await readFile13(absPath, "utf8");
2393
+ const split = splitFrontmatter(raw);
2394
+ if (!split.ok) {
2395
+ unresolved.push(relPath);
2396
+ continue;
2397
+ }
2398
+ const body = split.data.body;
2399
+ const rawFm = split.data.rawFrontmatter;
2400
+ const stripped = body.replace(FENCE_RE2, "");
2401
+ const lines = stripped.split("\n");
2402
+ const inlineMarkers = [];
2403
+ let inSources = false;
2404
+ for (const line of lines) {
2405
+ if (/^## Sources\b/.test(line.trim())) {
2406
+ inSources = true;
2407
+ continue;
2408
+ }
2409
+ if (inSources) continue;
2410
+ for (const m of line.matchAll(INLINE_MARKER)) {
2411
+ inlineMarkers.push(m[0]);
2412
+ }
2413
+ }
2414
+ if (inlineMarkers.length === 0) {
2415
+ unresolved.push(relPath);
2416
+ continue;
2417
+ }
2418
+ const bodyLines = body.split("\n");
2419
+ let inSrc = false;
2420
+ const newBodyLines = [];
2421
+ const seen = /* @__PURE__ */ new Set();
2422
+ for (const line of bodyLines) {
2423
+ if (/^## Sources\b/.test(line.trim())) {
2424
+ inSrc = true;
2425
+ newBodyLines.push(line);
2426
+ continue;
2427
+ }
2428
+ if (inSrc) {
2429
+ newBodyLines.push(line);
2430
+ continue;
2431
+ }
2432
+ const lineWithoutMarkers = line.replace(INLINE_MARKER, "").trim();
2433
+ if (lineWithoutMarkers.length === 0 && INLINE_MARKER.test(line)) {
2434
+ continue;
2435
+ }
2436
+ let cleaned = line;
2437
+ for (const marker of inlineMarkers) {
2438
+ if (seen.has(marker)) continue;
2439
+ const escapedMarker = marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2440
+ const trailingRe = new RegExp(`([.!?]\\s*)${escapedMarker}`);
2441
+ if (trailingRe.test(cleaned)) {
2442
+ cleaned = cleaned.replace(trailingRe, "$1");
2443
+ seen.add(marker);
2444
+ }
2445
+ const midRe = new RegExp(`${escapedMarker}\\s*`);
2446
+ if (!seen.has(marker) && midRe.test(cleaned)) {
2447
+ cleaned = cleaned.replace(midRe, "");
2448
+ seen.add(marker);
2449
+ }
2450
+ }
2451
+ newBodyLines.push(cleaned);
2452
+ }
2453
+ let newBody = newBodyLines.join("\n");
2454
+ const dedupedMarkers = [...new Set(inlineMarkers)];
2455
+ if (inSrc) {
2456
+ const existingSources = new Set(
2457
+ body.split("\n").filter((l) => /^- \^\[raw\//.test(l.trim())).map((l) => l.trim().replace(/^- /, ""))
2458
+ );
2459
+ const newMarkers = dedupedMarkers.filter((m) => !existingSources.has(m));
2460
+ const sourceLines = newMarkers.map((m) => `- ${m}`);
2461
+ if (sourceLines.length > 0) {
2462
+ newBody = newBody.trimEnd() + "\n" + sourceLines.join("\n") + "\n";
2463
+ }
2464
+ } else {
2465
+ const sourceLines = dedupedMarkers.map((m) => `- ${m}`);
2466
+ newBody = newBody.trimEnd() + "\n\n## Sources\n\n" + sourceLines.join("\n") + "\n";
2467
+ }
2468
+ const newContent = `---
2469
+ ${rawFm}
2470
+ ---
2471
+ ${newBody}`;
2472
+ await writeFile7(absPath, newContent, "utf8");
2473
+ fixed.push(relPath);
2474
+ } catch {
2475
+ unresolved.push(relPath);
2476
+ }
2477
+ }
2478
+ if (fixed.length > 0) {
2479
+ const fixedSet = new Set(fixed);
2480
+ const remaining = legacyPages.filter((p) => !fixedSet.has(p));
2481
+ if (remaining.length > 0) buckets.legacy_citation_style = remaining;
2482
+ else delete buckets.legacy_citation_style;
2483
+ }
2484
+ }
2485
+ if (input.fix && noOverview.length > 0) {
2486
+ for (const relPath of noOverview) {
2487
+ try {
2488
+ const absPath = `${input.vault}/${relPath}`;
2489
+ const raw = await readFile13(absPath, "utf8");
2490
+ const split = splitFrontmatter(raw);
2491
+ if (!split.ok) {
2492
+ unresolved.push(relPath);
2493
+ continue;
2494
+ }
2495
+ const body = split.data.body;
2496
+ const rawFm = split.data.rawFrontmatter;
2497
+ const fm = extractFrontmatter(raw);
2498
+ const title = fm.ok && typeof fm.data.title === "string" ? fm.data.title : "";
2499
+ const overviewSection = `## Overview
2500
+
2501
+ ${title}`;
2502
+ const trimmedBody = body.replace(/^\n+/, "");
2503
+ const newContent = `---
2504
+ ${rawFm}
2505
+ ---
2506
+
2507
+ ${overviewSection}
2508
+
2509
+ ${trimmedBody}`;
2510
+ await writeFile7(absPath, newContent, "utf8");
2511
+ fixed.push(relPath);
2512
+ } catch {
2513
+ unresolved.push(relPath);
2514
+ }
2515
+ }
2516
+ const fixedBeforeOverview = fixed.length;
2517
+ const fixedSet = new Set(fixed);
2518
+ const remaining = noOverview.filter((p) => !fixedSet.has(p));
2519
+ if (remaining.length > 0) buckets.missing_overview = remaining;
2520
+ else delete buckets.missing_overview;
2521
+ }
2522
+ if (input.fix && wikilinkCitationFlags.length > 0) {
2523
+ const WIKILINK_RE = /\[\[raw\/([^\]|]+)(?:\|[^\]]*)?\]\]/g;
2524
+ const FENCE_RE2 = /```[\s\S]*?```/g;
2525
+ const wikilinkFixed = [];
2526
+ for (const relPath of wikilinkCitationFlags) {
2527
+ try {
2528
+ const absPath = `${input.vault}/${relPath}`;
2529
+ const raw = await readFile13(absPath, "utf8");
2530
+ const split = splitFrontmatter(raw);
2531
+ if (!split.ok) {
2532
+ unresolved.push(relPath);
2533
+ continue;
2534
+ }
2535
+ const body = split.data.body;
2536
+ const rawFm = split.data.rawFrontmatter;
2537
+ const stripped = body.replace(FENCE_RE2, "");
2538
+ const wikilinkMatches = [...stripped.matchAll(WIKILINK_RE)];
2539
+ if (wikilinkMatches.length === 0) {
2540
+ unresolved.push(relPath);
2541
+ continue;
2542
+ }
2543
+ const wikilinkPaths = [...new Set(wikilinkMatches.map((m) => m[1]))];
2544
+ const bodyLines = body.split("\n");
2545
+ let inSrc = false;
2546
+ const newBodyLines = [];
2547
+ for (const line of bodyLines) {
2548
+ if (/^## Sources\b/.test(line.trim())) {
2549
+ inSrc = true;
2550
+ newBodyLines.push(line);
2551
+ continue;
2552
+ }
2553
+ if (inSrc) {
2554
+ newBodyLines.push(line);
2555
+ continue;
2556
+ }
2557
+ let cleaned = line.replace(/\[\[raw\/[^\]|]+(?:\|[^\]]*)?\]\]/g, "");
2558
+ cleaned = cleaned.replace(/\s+\./g, ".").replace(/\s{2,}/g, " ").replace(/\s+$/, "");
2559
+ if (cleaned.length > 0 || line.trim().length === 0) {
2560
+ newBodyLines.push(cleaned);
2561
+ }
2562
+ }
2563
+ let newBody = newBodyLines.join("\n");
2564
+ const citationMarkers = wikilinkPaths.map((p) => `^[raw/${p}]`);
2565
+ const sourceEntries = extractSourceEntries(rawFm);
2566
+ const fmMarkers = [];
2567
+ for (const entry of sourceEntries) {
2568
+ let rawPath = entry.replace(/^"/, "").replace(/"$/, "").replace(/^'/, "").replace(/'$/, "");
2569
+ rawPath = rawPath.replace(/^\^\[/, "").replace(/\]$/, "");
2570
+ if (rawPath.startsWith("raw/")) {
2571
+ fmMarkers.push(`^[${rawPath}]`);
2572
+ }
2573
+ }
2574
+ const allMarkers = [.../* @__PURE__ */ new Set([...citationMarkers, ...fmMarkers])];
2575
+ const hasSourcesSection = /^## Sources\b/m.test(newBody);
2576
+ if (hasSourcesSection) {
2577
+ const existingSources = new Set(
2578
+ newBody.split("\n").filter((l) => /^- \^\[raw\//.test(l.trim())).map((l) => l.trim().replace(/^- /, ""))
2579
+ );
2580
+ const newMarkers = allMarkers.filter((m) => !existingSources.has(m));
2581
+ const sourceLines = newMarkers.map((m) => `- ${m}`);
2582
+ if (sourceLines.length > 0) {
2583
+ newBody = newBody.trimEnd() + "\n" + sourceLines.join("\n") + "\n";
2584
+ }
2585
+ } else {
2586
+ const sourceLines = allMarkers.map((m) => `- ${m}`);
2587
+ newBody = newBody.trimEnd() + "\n\n## Sources\n\n" + sourceLines.join("\n") + "\n";
2588
+ }
2589
+ const newContent = `---
2590
+ ${rawFm}
2591
+ ---
2592
+ ${newBody}`;
2593
+ await writeFile7(absPath, newContent, "utf8");
2594
+ wikilinkFixed.push(relPath);
2595
+ } catch {
2596
+ unresolved.push(relPath);
2597
+ }
2598
+ }
2599
+ fixed.push(...wikilinkFixed);
2600
+ if (wikilinkFixed.length > 0) {
2601
+ const fixedSet = new Set(wikilinkFixed);
2602
+ const remaining = wikilinkCitationFlags.filter((p) => !fixedSet.has(p));
2603
+ if (remaining.length > 0) buckets.wikilink_citation = remaining;
2604
+ else delete buckets.wikilink_citation;
2605
+ }
2606
+ }
2607
+ }
2608
+ const errorOut = ERROR_ORDER.flatMap((k) => buckets[k] ? [{ kind: k, items: buckets[k] }] : []);
2609
+ const warningOut = WARNING_ORDER.flatMap((k) => buckets[k] ? [{ kind: k, items: buckets[k] }] : []);
2610
+ const infoOut = INFO_ORDER.flatMap((k) => buckets[k] ? [{ kind: k, items: buckets[k] }] : []);
2611
+ const summary = {
1809
2612
  errors: errorOut.reduce((n, b) => n + b.items.length, 0),
1810
2613
  warnings: warningOut.reduce((n, b) => n + b.items.length, 0),
1811
2614
  info: infoOut.reduce((n, b) => n + b.items.length, 0)
@@ -1822,26 +2625,36 @@ async function runLint(input) {
1822
2625
  hintLines.push(` ${b.kind}: ${b.items.length}`);
1823
2626
  }
1824
2627
  if (hintLines.length === 0) hintLines.push("0 errors, 0 warnings, 0 info");
2628
+ if (input.fix && fixed.length > 0) {
2629
+ appendLastOp(input.vault, {
2630
+ operation: "lint-fix",
2631
+ summary: `fixed ${fixed.length} page(s)`,
2632
+ files: fixed,
2633
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2634
+ });
2635
+ }
1825
2636
  return {
1826
2637
  exitCode,
1827
2638
  result: ok({
1828
2639
  vault: { path: input.vault, source: input.source ?? "resolved" },
1829
2640
  summary,
1830
2641
  by_severity: { error: errorOut, warning: warningOut, info: infoOut },
2642
+ fixed,
2643
+ unresolved,
1831
2644
  humanHint: hintLines.join("\n")
1832
2645
  })
1833
2646
  };
1834
2647
  }
1835
2648
 
1836
2649
  // src/commands/config.ts
1837
- import { readFile as readFile12 } from "fs/promises";
1838
- import { existsSync } from "fs";
1839
- import { join as join14 } from "path";
2650
+ import { readFile as readFile14 } from "fs/promises";
2651
+ import { existsSync as existsSync3 } from "fs";
2652
+ import { join as join18 } from "path";
1840
2653
  function validateKey(key) {
1841
2654
  return CONFIG_KEYS.includes(key) || isValidWikiProfileKey(key);
1842
2655
  }
1843
2656
  function configPath(home) {
1844
- return join14(home, ".skillwiki", ".env");
2657
+ return join18(home, ".skillwiki", ".env");
1845
2658
  }
1846
2659
  async function runConfigGet(input) {
1847
2660
  if (!validateKey(input.key)) {
@@ -1859,7 +2672,7 @@ async function runConfigSet(input) {
1859
2672
  try {
1860
2673
  let originalContent;
1861
2674
  try {
1862
- originalContent = await readFile12(filePath, "utf8");
2675
+ originalContent = await readFile14(filePath, "utf8");
1863
2676
  } catch {
1864
2677
  }
1865
2678
  const existing = originalContent !== void 0 ? parseDotenvText(originalContent) : {};
@@ -1891,17 +2704,17 @@ async function runConfigList(input) {
1891
2704
  }
1892
2705
  async function runConfigPath(input) {
1893
2706
  const filePath = configPath(input.home);
1894
- return { exitCode: ExitCode.OK, result: ok({ path: filePath, exists: existsSync(filePath), humanHint: filePath }) };
2707
+ return { exitCode: ExitCode.OK, result: ok({ path: filePath, exists: existsSync3(filePath), humanHint: filePath }) };
1895
2708
  }
1896
2709
 
1897
2710
  // src/commands/doctor.ts
1898
- import { existsSync as existsSync3, readdirSync, statSync } from "fs";
1899
- import { join as join17 } from "path";
2711
+ import { existsSync as existsSync5, lstatSync, readlinkSync, readdirSync, statSync } from "fs";
2712
+ import { join as join21, resolve as resolve4 } from "path";
1900
2713
  import { execSync } from "child_process";
1901
2714
 
1902
2715
  // src/utils/auto-update.ts
1903
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync } from "fs";
1904
- import { join as join15, dirname as dirname6 } from "path";
2716
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "fs";
2717
+ import { join as join19, dirname as dirname8 } from "path";
1905
2718
  import { spawn } from "child_process";
1906
2719
 
1907
2720
  // src/utils/update-consts.ts
@@ -1912,11 +2725,11 @@ var CLI_DISABLE_FLAG = "--no-update-notifier";
1912
2725
 
1913
2726
  // src/utils/auto-update.ts
1914
2727
  function cachePath(home) {
1915
- return join15(home, ".skillwiki", CACHE_FILENAME);
2728
+ return join19(home, ".skillwiki", CACHE_FILENAME);
1916
2729
  }
1917
2730
  function readCacheRaw(home) {
1918
2731
  try {
1919
- const raw = readFileSync2(cachePath(home), "utf8");
2732
+ const raw = readFileSync4(cachePath(home), "utf8");
1920
2733
  return JSON.parse(raw);
1921
2734
  } catch {
1922
2735
  return null;
@@ -1931,8 +2744,8 @@ function readCache(home) {
1931
2744
  }
1932
2745
  function writeCache(home, cache) {
1933
2746
  const p = cachePath(home);
1934
- mkdirSync(dirname6(p), { recursive: true });
1935
- writeFileSync2(p, JSON.stringify(cache, null, 2));
2747
+ mkdirSync2(dirname8(p), { recursive: true });
2748
+ writeFileSync3(p, JSON.stringify(cache, null, 2));
1936
2749
  }
1937
2750
  function latestFromCache(home, currentVersion) {
1938
2751
  const { cache } = readCache(home);
@@ -1950,7 +2763,7 @@ function triggerAutoUpdate(home, currentVersion) {
1950
2763
  const { isStale } = readCache(home);
1951
2764
  if (!isStale) return;
1952
2765
  const bgScript = new URL("../auto-update-bg.js", import.meta.url).pathname;
1953
- if (!existsSync2(bgScript)) return;
2766
+ if (!existsSync4(bgScript)) return;
1954
2767
  const child = spawn(process.execPath, [bgScript, home, currentVersion], {
1955
2768
  detached: true,
1956
2769
  stdio: "ignore"
@@ -1961,13 +2774,13 @@ function triggerAutoUpdate(home, currentVersion) {
1961
2774
  }
1962
2775
 
1963
2776
  // src/utils/plugin-registry.ts
1964
- import { readFileSync as readFileSync3 } from "fs";
1965
- import { join as join16 } from "path";
1966
- var REGISTRY_PATH = join16(".claude", "plugins", "installed_plugins.json");
2777
+ import { readFileSync as readFileSync5 } from "fs";
2778
+ import { join as join20 } from "path";
2779
+ var REGISTRY_PATH = join20(".claude", "plugins", "installed_plugins.json");
1967
2780
  var PLUGIN_KEY = "skillwiki@llm-wiki";
1968
2781
  function readInstalledPlugins(home) {
1969
2782
  try {
1970
- const raw = readFileSync3(join16(home, REGISTRY_PATH), "utf8");
2783
+ const raw = readFileSync5(join20(home, REGISTRY_PATH), "utf8");
1971
2784
  return JSON.parse(raw);
1972
2785
  } catch {
1973
2786
  return null;
@@ -1992,23 +2805,79 @@ function checkNodeVersion() {
1992
2805
  }
1993
2806
  return check("error", "node_version", "Node.js version", `Node.js v${major} is below minimum v20`);
1994
2807
  }
1995
- function checkCliOnPath(argv) {
2808
+ function detectCliChannels(argv, home) {
2809
+ const channels = [];
1996
2810
  if (argv.length >= 2 && argv[1].endsWith("cli.js")) {
1997
- return check("warn", "cli_on_path", "skillwiki on PATH", "Running via node cli.js (dev mode) \u2014 PATH check skipped");
2811
+ const devPath = resolve4(argv[1]);
2812
+ channels.push({ name: "dev", path: devPath, isDevLink: true });
2813
+ }
2814
+ try {
2815
+ const whichOut = execSync("which skillwiki 2>/dev/null", { encoding: "utf8" }).trim();
2816
+ if (whichOut) {
2817
+ const isDev = isDevSymlink(whichOut);
2818
+ if (!channels.some((c) => c.path === resolve4(whichOut))) {
2819
+ channels.push({ name: "npm", path: whichOut, isDevLink: isDev });
2820
+ }
2821
+ }
2822
+ } catch {
2823
+ }
2824
+ const plugin = findPlugin(home);
2825
+ if (plugin) {
2826
+ const pluginBin = join21(plugin.installPath, "bin", "skillwiki");
2827
+ if (existsSync5(pluginBin)) {
2828
+ channels.push({ name: "plugin", path: pluginBin, isDevLink: false });
2829
+ }
1998
2830
  }
1999
- if (argv.length >= 2 && argv[1] === "skillwiki") {
2000
- return check("pass", "cli_on_path", "skillwiki on PATH", "Running as skillwiki \u2014 already on PATH");
2831
+ const installBin = join21(home, ".claude", "skills", "bin", "skillwiki");
2832
+ if (existsSync5(installBin)) {
2833
+ channels.push({ name: "install", path: installBin, isDevLink: false });
2001
2834
  }
2835
+ return channels;
2836
+ }
2837
+ function isDevSymlink(binPath) {
2002
2838
  try {
2003
- execSync("which skillwiki 2>/dev/null", { encoding: "utf8" }).trim();
2004
- return check("pass", "cli_on_path", "skillwiki on PATH", "skillwiki found on PATH");
2839
+ const st = lstatSync(binPath);
2840
+ if (st.isSymbolicLink()) {
2841
+ const target = resolve4(binPath, "..", readlinkSync(binPath));
2842
+ return target.includes("packages/cli") || target.includes("packages\\cli");
2843
+ }
2005
2844
  } catch {
2006
- return check("warn", "cli_on_path", "skillwiki on PATH", "skillwiki not found on PATH");
2007
2845
  }
2846
+ return false;
2847
+ }
2848
+ function checkCliChannels(argv, home) {
2849
+ const channels = detectCliChannels(argv, home);
2850
+ if (channels.length === 0) {
2851
+ return check("warn", "cli_channels", "CLI channels", "skillwiki not found on any channel");
2852
+ }
2853
+ if (channels.length === 1) {
2854
+ const ch = channels[0];
2855
+ const label = ch.isDevLink ? `${ch.name} (dev source)` : ch.name;
2856
+ return check("pass", "cli_channels", "CLI channels", `Single channel: ${label}`);
2857
+ }
2858
+ const devChannels = channels.filter((c) => c.isDevLink);
2859
+ const prodChannels = channels.filter((c) => !c.isDevLink);
2860
+ if (devChannels.length > 0 && prodChannels.length > 0) {
2861
+ const devNames = devChannels.map((c) => `${c.name}(dev)`);
2862
+ const prodNames = prodChannels.map((c) => c.name);
2863
+ return check(
2864
+ "warn",
2865
+ "cli_channels",
2866
+ "CLI channels",
2867
+ `${channels.length} channels: ${[...devNames, ...prodNames].join(", ")} \u2014 dev and prod binaries overlap; dev repo should use project-local settings only`
2868
+ );
2869
+ }
2870
+ const names = channels.map((c) => c.name);
2871
+ return check(
2872
+ "warn",
2873
+ "cli_channels",
2874
+ "CLI channels",
2875
+ `${channels.length} channels: ${names.join(", ")} \u2014 remove unused install with: rm ~/.claude/skills/bin/skillwiki`
2876
+ );
2008
2877
  }
2009
2878
  async function checkConfigFile(home) {
2010
2879
  const cfgPath = configPath(home);
2011
- if (!existsSync3(cfgPath)) {
2880
+ if (!existsSync5(cfgPath)) {
2012
2881
  return check("warn", "config_file", "Config file exists", `${cfgPath} not found`);
2013
2882
  }
2014
2883
  try {
@@ -2023,7 +2892,7 @@ function checkWikiPathExists(resolvedPath) {
2023
2892
  if (resolvedPath === void 0) {
2024
2893
  return check("error", "wiki_path_exists", "Vault directory exists", "Cannot check \u2014 WIKI_PATH not resolved");
2025
2894
  }
2026
- if (existsSync3(resolvedPath) && statSync(resolvedPath).isDirectory()) {
2895
+ if (existsSync5(resolvedPath) && statSync(resolvedPath).isDirectory()) {
2027
2896
  return check("pass", "wiki_path_exists", "Vault directory exists", resolvedPath);
2028
2897
  }
2029
2898
  return check("error", "wiki_path_exists", "Vault directory exists", `${resolvedPath} does not exist or is not a directory`);
@@ -2032,20 +2901,27 @@ function checkVaultStructure(resolvedPath) {
2032
2901
  if (resolvedPath === void 0) {
2033
2902
  return check("error", "vault_structure", "Vault structure valid", "Cannot check \u2014 WIKI_PATH not resolved");
2034
2903
  }
2035
- if (!existsSync3(resolvedPath)) {
2904
+ if (!existsSync5(resolvedPath)) {
2036
2905
  return check("error", "vault_structure", "Vault structure valid", "Cannot check \u2014 vault directory does not exist");
2037
2906
  }
2038
2907
  const missing = [];
2039
- if (!existsSync3(join17(resolvedPath, "SCHEMA.md"))) missing.push("SCHEMA.md");
2908
+ if (!existsSync5(join21(resolvedPath, "SCHEMA.md"))) missing.push("SCHEMA.md");
2040
2909
  for (const dir of ["raw", "entities", "concepts", "meta"]) {
2041
- if (!existsSync3(join17(resolvedPath, dir))) missing.push(dir + "/");
2910
+ if (!existsSync5(join21(resolvedPath, dir))) missing.push(dir + "/");
2042
2911
  }
2043
2912
  if (missing.length === 0) {
2044
2913
  return check("pass", "vault_structure", "Vault structure valid", "All required files and directories present");
2045
2914
  }
2046
2915
  return check("warn", "vault_structure", "Vault structure valid", `Missing: ${missing.join(", ")} \u2014 run \`skillwiki init\` to add CodeWiki structure`);
2047
2916
  }
2048
- function checkSkillsInstalled(home) {
2917
+ function checkSkillsInstalled(home, cwd) {
2918
+ const srcDir = cwd ? join21(cwd, "packages", "skills") : void 0;
2919
+ if (srcDir && existsSync5(srcDir)) {
2920
+ const found = findSkillMd(srcDir);
2921
+ if (found.length > 0) {
2922
+ return check("pass", "skills_installed", "Skills installed", `${found.length} SKILL.md file(s) found (source)`);
2923
+ }
2924
+ }
2049
2925
  const plugin = findPlugin(home);
2050
2926
  if (plugin) {
2051
2927
  const found = findSkillMd(plugin.installPath);
@@ -2053,8 +2929,8 @@ function checkSkillsInstalled(home) {
2053
2929
  return check("pass", "skills_installed", "Skills installed", `${found.length} SKILL.md file(s) found (plugin v${plugin.version})`);
2054
2930
  }
2055
2931
  }
2056
- const skillsDir = join17(home, ".claude", "skills");
2057
- if (existsSync3(skillsDir)) {
2932
+ const skillsDir = join21(home, ".claude", "skills");
2933
+ if (existsSync5(skillsDir)) {
2058
2934
  const found = findSkillMd(skillsDir);
2059
2935
  if (found.length > 0) {
2060
2936
  return check("pass", "skills_installed", "Skills installed", `${found.length} SKILL.md file(s) found (CLI install)`);
@@ -2062,6 +2938,25 @@ function checkSkillsInstalled(home) {
2062
2938
  }
2063
2939
  return check("warn", "skills_installed", "Skills installed", "No SKILL.md files found");
2064
2940
  }
2941
+ function checkDuplicateSkills(home) {
2942
+ const plugin = findPlugin(home);
2943
+ const skillsDir = join21(home, ".claude", "skills");
2944
+ if (!plugin || !existsSync5(skillsDir)) {
2945
+ return check("pass", "skills_duplicate", "Skills not duplicated", "Single install channel");
2946
+ }
2947
+ const pluginSkills = findSkillNames(plugin.installPath);
2948
+ const cliSkills = findSkillNames(skillsDir);
2949
+ const duplicates = pluginSkills.filter((name) => cliSkills.includes(name));
2950
+ if (duplicates.length === 0) {
2951
+ return check("pass", "skills_duplicate", "Skills not duplicated", "No overlap between plugin and CLI install");
2952
+ }
2953
+ return check(
2954
+ "warn",
2955
+ "skills_duplicate",
2956
+ "Skills not duplicated",
2957
+ `${duplicates.length} skill(s) in both plugin and ~/.claude/skills/ \u2014 remove CLI copies: rm -r ~/.claude/skills/{${duplicates.slice(0, 3).join(",")}${duplicates.length > 3 ? ",\u2026" : ""}}`
2958
+ );
2959
+ }
2065
2960
  function checkNpmUpdate(home, currentVersion) {
2066
2961
  const { hasUpdate, latest } = latestFromCache(home, currentVersion);
2067
2962
  if (!latest) {
@@ -2111,12 +3006,112 @@ async function checkProfiles(home) {
2111
3006
  }
2112
3007
  async function checkProjectLocalOverride(cwd) {
2113
3008
  const dir = cwd ?? process.cwd();
2114
- const envPath = join17(dir, ".skillwiki", ".env");
2115
- if (existsSync3(envPath)) {
3009
+ const envPath = join21(dir, ".skillwiki", ".env");
3010
+ if (existsSync5(envPath)) {
2116
3011
  return check("pass", "project_local", "Project-local config", `Found: ${envPath}`);
2117
3012
  }
2118
3013
  return check("pass", "project_local", "Project-local config", "None");
2119
3014
  }
3015
+ function checkVaultGitRemote(resolvedPath) {
3016
+ if (resolvedPath === void 0) {
3017
+ return check("error", "vault_git_remote", "Vault git remote", "Cannot check \u2014 WIKI_PATH not resolved");
3018
+ }
3019
+ if (!existsSync5(join21(resolvedPath, ".git"))) {
3020
+ return check("warn", "vault_git_remote", "Vault git remote", "Vault is not a git repository \u2014 sync features unavailable");
3021
+ }
3022
+ try {
3023
+ const remote = execSync("git remote", { cwd: resolvedPath, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
3024
+ if (!remote) {
3025
+ return check("warn", "vault_git_remote", "Vault git remote", "No remote configured \u2014 push/pull unavailable");
3026
+ }
3027
+ let branch = "(no commits yet)";
3028
+ try {
3029
+ branch = execSync("git rev-parse --abbrev-ref HEAD", { cwd: resolvedPath, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
3030
+ } catch {
3031
+ }
3032
+ return check("pass", "vault_git_remote", "Vault git remote", `Remote: ${remote.split("\n")[0]}, branch: ${branch}`);
3033
+ } catch {
3034
+ return check("warn", "vault_git_remote", "Vault git remote", "Could not read git remote info");
3035
+ }
3036
+ }
3037
+ function checkObsidianTemplates(resolvedPath) {
3038
+ if (resolvedPath === void 0) {
3039
+ return check("error", "obsidian_templates", "Obsidian templates", "Cannot check \u2014 WIKI_PATH not resolved");
3040
+ }
3041
+ const missing = [];
3042
+ if (!existsSync5(join21(resolvedPath, "_Templates"))) missing.push("_Templates/");
3043
+ if (!existsSync5(join21(resolvedPath, ".obsidian", "templates.json"))) missing.push(".obsidian/templates.json");
3044
+ if (!existsSync5(join21(resolvedPath, ".obsidian", "app.json"))) missing.push(".obsidian/app.json");
3045
+ if (missing.length === 0) {
3046
+ return check("pass", "obsidian_templates", "Obsidian templates", "Template folder and config present");
3047
+ }
3048
+ return check("warn", "obsidian_templates", "Obsidian templates", `Missing: ${missing.join(", ")} \u2014 run \`skillwiki init\` to create`);
3049
+ }
3050
+ function checkDotStoreClean(resolvedPath) {
3051
+ if (resolvedPath === void 0) {
3052
+ return check("error", "dsstore_clean", "No .DS_Store in raw/", "Cannot check \u2014 WIKI_PATH not resolved");
3053
+ }
3054
+ const rawDir = join21(resolvedPath, "raw");
3055
+ if (!existsSync5(rawDir)) {
3056
+ return check("pass", "dsstore_clean", "No .DS_Store in raw/", "raw/ directory not found \u2014 check skipped");
3057
+ }
3058
+ const found = [];
3059
+ (function walk2(dir, rel) {
3060
+ let entries;
3061
+ try {
3062
+ entries = readdirSync(dir, { withFileTypes: true });
3063
+ } catch {
3064
+ return;
3065
+ }
3066
+ for (const entry of entries) {
3067
+ if (entry.name === ".DS_Store") {
3068
+ found.push(rel ? `${rel}/.DS_Store` : ".DS_Store");
3069
+ } else if (entry.isDirectory()) {
3070
+ walk2(join21(dir, entry.name), rel ? `${rel}/${entry.name}` : entry.name);
3071
+ }
3072
+ }
3073
+ })(rawDir, "");
3074
+ if (found.length === 0) {
3075
+ return check("pass", "dsstore_clean", "No .DS_Store in raw/", "No .DS_Store files found");
3076
+ }
3077
+ return check("warn", "dsstore_clean", "No .DS_Store in raw/", `${found.length} .DS_Store file(s) found \u2014 remove with: find ${rawDir} -name .DS_Store -delete`);
3078
+ }
3079
+ function checkSyncLastPush(resolvedPath) {
3080
+ if (resolvedPath === void 0) {
3081
+ return check("error", "sync_last_push", "Vault sync recency", "Cannot check \u2014 WIKI_PATH not resolved");
3082
+ }
3083
+ if (!existsSync5(join21(resolvedPath, ".git"))) {
3084
+ return check("pass", "sync_last_push", "Vault sync recency", "No git repo \u2014 sync check skipped");
3085
+ }
3086
+ let timestamp;
3087
+ try {
3088
+ const out = execSync("git log -1 --format=%ct origin/HEAD", {
3089
+ cwd: resolvedPath,
3090
+ encoding: "utf8",
3091
+ stdio: ["pipe", "pipe", "pipe"]
3092
+ }).trim();
3093
+ timestamp = parseInt(out, 10);
3094
+ } catch {
3095
+ try {
3096
+ const out = execSync("git log -1 --format=%ct HEAD", {
3097
+ cwd: resolvedPath,
3098
+ encoding: "utf8",
3099
+ stdio: ["pipe", "pipe", "pipe"]
3100
+ }).trim();
3101
+ timestamp = parseInt(out, 10);
3102
+ } catch {
3103
+ }
3104
+ }
3105
+ if (timestamp === void 0 || isNaN(timestamp)) {
3106
+ return check("warn", "sync_last_push", "Vault sync recency", "No commits found \u2014 consider running `skillwiki sync status`");
3107
+ }
3108
+ const daysSince2 = Math.floor((Date.now() / 1e3 - timestamp) / 86400);
3109
+ const dateStr = new Date(timestamp * 1e3).toISOString().slice(0, 10);
3110
+ if (daysSince2 > 7) {
3111
+ return check("warn", "sync_last_push", "Vault sync recency", `Last push was ${daysSince2} days ago \u2014 consider running \`skillwiki sync status\``);
3112
+ }
3113
+ return check("pass", "sync_last_push", "Vault sync recency", `Last push: ${dateStr} (${daysSince2} day(s) ago)`);
3114
+ }
2120
3115
  function findSkillMd(dir) {
2121
3116
  const results = [];
2122
3117
  let entries;
@@ -2127,9 +3122,24 @@ function findSkillMd(dir) {
2127
3122
  }
2128
3123
  for (const entry of entries) {
2129
3124
  if (entry.isFile() && entry.name === "SKILL.md") {
2130
- results.push(join17(dir, entry.name));
3125
+ results.push(join21(dir, entry.name));
2131
3126
  } else if (entry.isDirectory()) {
2132
- results.push(...findSkillMd(join17(dir, entry.name)));
3127
+ results.push(...findSkillMd(join21(dir, entry.name)));
3128
+ }
3129
+ }
3130
+ return results;
3131
+ }
3132
+ function findSkillNames(dir) {
3133
+ const results = [];
3134
+ let entries;
3135
+ try {
3136
+ entries = readdirSync(dir, { withFileTypes: true });
3137
+ } catch {
3138
+ return results;
3139
+ }
3140
+ for (const entry of entries) {
3141
+ if (entry.isDirectory() && existsSync5(join21(dir, entry.name, "SKILL.md"))) {
3142
+ results.push(entry.name);
2133
3143
  }
2134
3144
  }
2135
3145
  return results;
@@ -2137,7 +3147,7 @@ function findSkillMd(dir) {
2137
3147
  async function runDoctor(input) {
2138
3148
  const checks = [];
2139
3149
  checks.push(checkNodeVersion());
2140
- checks.push(checkCliOnPath(input.argv));
3150
+ checks.push(checkCliChannels(input.argv, input.home));
2141
3151
  checks.push(await checkConfigFile(input.home));
2142
3152
  checks.push(await checkProfiles(input.home));
2143
3153
  checks.push(await checkProjectLocalOverride(input.cwd));
@@ -2150,7 +3160,12 @@ async function runDoctor(input) {
2150
3160
  const resolvedPath = resolved.ok ? resolved.data.path : void 0;
2151
3161
  checks.push(checkWikiPathExists(resolvedPath));
2152
3162
  checks.push(checkVaultStructure(resolvedPath));
2153
- checks.push(checkSkillsInstalled(input.home));
3163
+ checks.push(checkObsidianTemplates(resolvedPath));
3164
+ checks.push(checkVaultGitRemote(resolvedPath));
3165
+ checks.push(checkSyncLastPush(resolvedPath));
3166
+ checks.push(checkDotStoreClean(resolvedPath));
3167
+ checks.push(checkSkillsInstalled(input.home, input.cwd));
3168
+ checks.push(checkDuplicateSkills(input.home));
2154
3169
  checks.push(checkNpmUpdate(input.home, input.currentVersion));
2155
3170
  checks.push(checkPluginVersionDrift(input.home, input.currentVersion));
2156
3171
  const summary = {
@@ -2172,42 +3187,54 @@ async function runDoctor(input) {
2172
3187
  }
2173
3188
 
2174
3189
  // src/commands/archive.ts
2175
- import { rename as rename3, mkdir as mkdir5, readFile as readFile13, writeFile as writeFile6 } from "fs/promises";
2176
- import { join as join18, dirname as dirname7 } from "path";
3190
+ import { rename as rename4, mkdir as mkdir7, readFile as readFile15, writeFile as writeFile8 } from "fs/promises";
3191
+ import { join as join22, dirname as dirname9 } from "path";
2177
3192
  async function runArchive(input) {
2178
3193
  const scan = await scanVault(input.vault);
2179
3194
  if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
2180
- let relPath;
2181
- if (input.page.includes("/")) {
2182
- relPath = scan.data.typedKnowledge.find((p) => p.relPath === input.page)?.relPath;
2183
- } else {
2184
- relPath = scan.data.typedKnowledge.find((p) => p.relPath.replace(/\.md$/, "").split("/").pop() === input.page)?.relPath;
3195
+ const lookup = (pages) => {
3196
+ if (input.page.includes("/")) return pages.find((p) => p.relPath === input.page)?.relPath;
3197
+ return pages.find((p) => p.relPath.replace(/\.md$/, "").split("/").pop() === input.page)?.relPath;
3198
+ };
3199
+ let relPath = lookup(scan.data.typedKnowledge);
3200
+ let isRaw = false;
3201
+ if (!relPath) {
3202
+ relPath = lookup(scan.data.raw);
3203
+ isRaw = relPath != null;
2185
3204
  }
2186
3205
  if (!relPath) return { exitCode: ExitCode.ARCHIVE_TARGET_NOT_FOUND, result: err("ARCHIVE_TARGET_NOT_FOUND", { page: input.page }) };
2187
3206
  if (relPath.startsWith("_archive/")) return { exitCode: ExitCode.ARCHIVE_ALREADY_ARCHIVED, result: err("ARCHIVE_ALREADY_ARCHIVED", { page: relPath }) };
2188
- const archivePath = join18("_archive", relPath);
2189
- await mkdir5(dirname7(join18(input.vault, archivePath)), { recursive: true });
3207
+ const archivePath = join22("_archive", relPath).replace(/\\/g, "/");
3208
+ await mkdir7(dirname9(join22(input.vault, archivePath)), { recursive: true });
2190
3209
  let indexUpdated = false;
2191
- const indexPath = join18(input.vault, "index.md");
2192
- try {
2193
- const idx = await readFile13(indexPath, "utf8");
2194
- const slug = relPath.replace(/\.md$/, "").split("/").pop();
2195
- const originalLines = idx.split("\n");
2196
- const filtered = originalLines.filter((l) => !l.includes(`[[${slug}]]`));
2197
- if (filtered.length !== originalLines.length) {
2198
- await writeFile6(indexPath, filtered.join("\n"), "utf8");
2199
- indexUpdated = true;
3210
+ if (!isRaw) {
3211
+ const indexPath = join22(input.vault, "index.md");
3212
+ try {
3213
+ const idx = await readFile15(indexPath, "utf8");
3214
+ const slug = relPath.replace(/\.md$/, "").split("/").pop();
3215
+ const originalLines = idx.split("\n");
3216
+ const filtered = originalLines.filter((l) => !l.includes(`[[${slug}]]`));
3217
+ if (filtered.length !== originalLines.length) {
3218
+ await writeFile8(indexPath, filtered.join("\n"), "utf8");
3219
+ indexUpdated = true;
3220
+ }
3221
+ } catch (e) {
3222
+ if (e?.code !== "ENOENT") throw e;
2200
3223
  }
2201
- } catch (e) {
2202
- if (e?.code !== "ENOENT") throw e;
2203
3224
  }
2204
- await rename3(join18(input.vault, relPath), join18(input.vault, archivePath));
3225
+ await rename4(join22(input.vault, relPath), join22(input.vault, archivePath));
3226
+ appendLastOp(input.vault, {
3227
+ operation: "archive",
3228
+ summary: `moved ${relPath} to ${archivePath}`,
3229
+ files: [relPath],
3230
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3231
+ });
2205
3232
  return { exitCode: ExitCode.OK, result: ok({ archived_from: relPath, archived_to: archivePath, index_updated: indexUpdated, humanHint: `${relPath} -> ${archivePath}${indexUpdated ? " (index updated)" : ""}` }) };
2206
3233
  }
2207
3234
 
2208
3235
  // src/commands/drift.ts
2209
3236
  import { createHash as createHash2 } from "crypto";
2210
- import { writeFile as writeFile7 } from "fs/promises";
3237
+ import { writeFile as writeFile9 } from "fs/promises";
2211
3238
 
2212
3239
  // src/utils/fetch.ts
2213
3240
  async function controlledFetch(url, opts) {
@@ -2248,16 +3275,32 @@ async function runDrift(input) {
2248
3275
  const scan = await scanVault(input.vault);
2249
3276
  if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
2250
3277
  const results = [];
3278
+ const newResults = [];
2251
3279
  for (const raw of scan.data.raw) {
2252
3280
  const text = await readPage(raw);
2253
3281
  const split = splitFrontmatter(text);
2254
3282
  if (!split.ok) continue;
2255
3283
  const { rawFrontmatter, body } = split.data;
3284
+ const ingestedMatch = rawFrontmatter.match(/^ingested:\s*(.+)$/m);
3285
+ const ingestedRaw = ingestedMatch?.[1]?.trim() ?? "";
3286
+ const ingested = ingestedRaw.replace(/^["']|["']$/g, "");
3287
+ if (input.newSince && ingested && ingested >= input.newSince) {
3288
+ newResults.push({
3289
+ raw_path: raw.relPath,
3290
+ source_url: "",
3291
+ stored_sha256: "",
3292
+ current_sha256: null,
3293
+ status: "new",
3294
+ ingested
3295
+ });
3296
+ }
2256
3297
  const sourceUrlMatch = rawFrontmatter.match(/^source_url:\s*(.+)$/m);
2257
3298
  const storedHashMatch = rawFrontmatter.match(/^sha256:\s*([a-f0-9]+)$/m);
2258
3299
  if (!sourceUrlMatch || !storedHashMatch) continue;
2259
3300
  const sourceUrl = sourceUrlMatch[1].trim();
2260
3301
  const storedHash = storedHashMatch[1];
3302
+ if (!sourceUrl.startsWith("http://") && !sourceUrl.startsWith("https://")) continue;
3303
+ if (/^refreshable:\s*false\b/m.test(rawFrontmatter)) continue;
2261
3304
  const resp = await doFetch(sourceUrl, FETCH_OPTS);
2262
3305
  if (!resp.ok) {
2263
3306
  results.push({
@@ -2278,7 +3321,7 @@ async function runDrift(input) {
2278
3321
  ${newFm}
2279
3322
  ---
2280
3323
  ${body}`;
2281
- await writeFile7(raw.absPath, newText, "utf8");
3324
+ await writeFile9(raw.absPath, newText, "utf8");
2282
3325
  results.push({
2283
3326
  raw_path: raw.relPath,
2284
3327
  source_url: sourceUrl,
@@ -2302,17 +3345,26 @@ ${body}`;
2302
3345
  const unchanged = results.filter((r) => r.status === "unchanged").length;
2303
3346
  const exitCode = drifted.length > 0 ? ExitCode.DRIFT_DETECTED : ExitCode.OK;
2304
3347
  const hintLines = [`scanned: ${results.length}, unchanged: ${unchanged}`];
3348
+ if (newResults.length > 0) hintLines.push(`new: ${newResults.length}`, ...newResults.map((n) => ` ${n.raw_path} (ingested: ${n.ingested})`));
2305
3349
  if (drifted.length > 0) hintLines.push(`drifted: ${drifted.length}`, ...drifted.map((d) => ` ${d.raw_path}`));
2306
3350
  if (fetchFailed.length > 0) hintLines.push(`fetch_failed: ${fetchFailed.length}`, ...fetchFailed.map((f) => ` ${f.raw_path}: ${f.fetch_error}`));
2307
3351
  if (updated.length > 0) hintLines.push(`updated: ${updated.length}`, ...updated.map((u) => ` ${u.raw_path}`));
3352
+ if (input.apply && updated.length > 0) {
3353
+ appendLastOp(input.vault, {
3354
+ operation: "drift-apply",
3355
+ summary: `updated ${updated.length} raw sources`,
3356
+ files: updated.map((u) => u.raw_path),
3357
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3358
+ });
3359
+ }
2308
3360
  return {
2309
3361
  exitCode,
2310
- result: ok({ scanned: results.length, drifted, fetch_failed: fetchFailed, updated, unchanged, humanHint: hintLines.join("\n") })
3362
+ result: ok({ scanned: results.length, drifted, fetch_failed: fetchFailed, updated, newFiles: newResults, unchanged, humanHint: hintLines.join("\n") })
2311
3363
  };
2312
3364
  }
2313
3365
 
2314
3366
  // src/commands/migrate-citations.ts
2315
- import { writeFile as writeFile8 } from "fs/promises";
3367
+ import { writeFile as writeFile10 } from "fs/promises";
2316
3368
  var MARKER_RE2 = /\^\[(raw\/[^\]]+)\]/g;
2317
3369
  function moveMarkersToParagraphEnd(body) {
2318
3370
  const lines = body.split("\n");
@@ -2435,7 +3487,7 @@ ${migratedBody}${newFooter}`;
2435
3487
  continue;
2436
3488
  }
2437
3489
  if (!input.dryRun) {
2438
- await writeFile8(page.absPath, newText, "utf8");
3490
+ await writeFile10(page.absPath, newText, "utf8");
2439
3491
  }
2440
3492
  migrated.push(page.relPath);
2441
3493
  }
@@ -2444,6 +3496,14 @@ ${migratedBody}${newFooter}`;
2444
3496
  if (migrated.length > 0) hintLines.push(`migrated: ${migrated.length}`);
2445
3497
  if (skipped.length > 0) hintLines.push(`skipped (already clean): ${skipped.length}`);
2446
3498
  if (unchanged > 0) hintLines.push(`unchanged (no markers): ${unchanged}`);
3499
+ if (!input.dryRun && migrated.length > 0) {
3500
+ appendLastOp(input.vault, {
3501
+ operation: "migrate-citations",
3502
+ summary: `converted ${migrated.length} citation(s)`,
3503
+ files: migrated,
3504
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3505
+ });
3506
+ }
2447
3507
  return {
2448
3508
  exitCode,
2449
3509
  result: ok({
@@ -2457,7 +3517,7 @@ ${migratedBody}${newFooter}`;
2457
3517
  }
2458
3518
 
2459
3519
  // src/commands/frontmatter-fix.ts
2460
- import { writeFile as writeFile9 } from "fs/promises";
3520
+ import { writeFile as writeFile11 } from "fs/promises";
2461
3521
  function isoToday() {
2462
3522
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2463
3523
  }
@@ -2499,7 +3559,7 @@ ${newBody}`;
2499
3559
  continue;
2500
3560
  }
2501
3561
  if (!input.dryRun) {
2502
- await writeFile9(page.absPath, newText, "utf8");
3562
+ await writeFile11(page.absPath, newText, "utf8");
2503
3563
  }
2504
3564
  fixed.push(page.relPath);
2505
3565
  }
@@ -2509,6 +3569,14 @@ ${newBody}`;
2509
3569
  if (skipped.length > 0) hintLines.push(`skipped (parse error): ${skipped.length}`);
2510
3570
  if (unchanged > 0) hintLines.push(`unchanged: ${unchanged}`);
2511
3571
  if (input.dryRun && fixed.length > 0) hintLines.push("(dry run \u2014 no files written)");
3572
+ if (!input.dryRun && fixed.length > 0) {
3573
+ appendLastOp(input.vault, {
3574
+ operation: "frontmatter-fix",
3575
+ summary: `normalized frontmatter on ${fixed.length} page(s)`,
3576
+ files: fixed,
3577
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3578
+ });
3579
+ }
2512
3580
  return {
2513
3581
  exitCode,
2514
3582
  result: ok({
@@ -2523,13 +3591,41 @@ ${newBody}`;
2523
3591
 
2524
3592
  // src/commands/update.ts
2525
3593
  import { execSync as execSync2 } from "child_process";
2526
- import { readFileSync as readFileSync4 } from "fs";
3594
+ import { readFileSync as readFileSync6 } from "fs";
3595
+ import { join as join23 } from "path";
3596
+ function resolveGlobalSkillsRoot() {
3597
+ try {
3598
+ const globalRoot = execSync2("npm root -g", {
3599
+ encoding: "utf8",
3600
+ timeout: 5e3
3601
+ }).trim();
3602
+ return join23(globalRoot, "skillwiki", "skills");
3603
+ } catch {
3604
+ return null;
3605
+ }
3606
+ }
3607
+ async function refreshInstalledSkills(target) {
3608
+ const skillsRoot = resolveGlobalSkillsRoot();
3609
+ if (!skillsRoot) {
3610
+ return { warnings: ["could not locate global skillwiki installation for skill refresh"], refreshed: false };
3611
+ }
3612
+ try {
3613
+ const result = await runInstall({ skillsRoot, target, dryRun: false, symlink: false });
3614
+ if (result.result.ok) {
3615
+ return { warnings: result.result.data.version_warnings, refreshed: true };
3616
+ }
3617
+ return { warnings: [`skill refresh failed: ${result.result.error}`], refreshed: false };
3618
+ } catch (e) {
3619
+ return { warnings: [`skill refresh error: ${String(e)}`], refreshed: false };
3620
+ }
3621
+ }
2527
3622
  async function runUpdate(input) {
2528
3623
  const pkg2 = JSON.parse(
2529
- readFileSync4(new URL("../../package.json", import.meta.url), "utf8")
3624
+ readFileSync6(new URL("../../package.json", import.meta.url), "utf8")
2530
3625
  );
2531
3626
  const currentVersion = pkg2.version;
2532
3627
  const tag = input.distTag ?? "beta";
3628
+ const target = join23(input.home, ".claude", "skills");
2533
3629
  let latest;
2534
3630
  try {
2535
3631
  latest = execSync2(`npm view skillwiki@${tag} version`, {
@@ -2555,6 +3651,8 @@ async function runUpdate(input) {
2555
3651
  previousVersion: currentVersion,
2556
3652
  newVersion: null,
2557
3653
  wasAlreadyLatest: true,
3654
+ version_warnings: [],
3655
+ skills_refreshed: false,
2558
3656
  humanHint: `Already on latest ${tag}: v${currentVersion}`
2559
3657
  })
2560
3658
  };
@@ -2571,125 +3669,2208 @@ async function runUpdate(input) {
2571
3669
  };
2572
3670
  }
2573
3671
  writeCache(input.home, { ...cache, updateAppliedAt: Date.now() });
3672
+ const installResult = await refreshInstalledSkills(target);
3673
+ const version_warnings = installResult.warnings;
3674
+ const skills_refreshed = installResult.refreshed;
3675
+ const hintLines = [
3676
+ `Updated skillwiki ${currentVersion} \u2192 ${latest}`,
3677
+ `skills refreshed: ${skills_refreshed}`
3678
+ ];
3679
+ if (version_warnings.length > 0) {
3680
+ hintLines.push(`version warnings: ${version_warnings.length}`);
3681
+ for (const w of version_warnings) hintLines.push(` ${w}`);
3682
+ }
2574
3683
  return {
2575
3684
  exitCode: ExitCode.OK,
2576
3685
  result: ok({
2577
3686
  previousVersion: currentVersion,
2578
3687
  newVersion: latest,
2579
3688
  wasAlreadyLatest: false,
2580
- humanHint: `Updated skillwiki ${currentVersion} \u2192 ${latest}`
3689
+ version_warnings,
3690
+ skills_refreshed,
3691
+ humanHint: hintLines.join("\n")
2581
3692
  })
2582
3693
  };
2583
3694
  }
2584
3695
 
2585
- // src/cli.ts
2586
- var pkg = JSON.parse(readFileSync5(new URL("../package.json", import.meta.url), "utf8"));
2587
- var program = new Command();
2588
- program.name("skillwiki").description("Deterministic helpers for CodeWiki skills").version(pkg.version);
2589
- program.option("--human", "render terminal-readable output instead of JSON");
2590
- function emit(r) {
2591
- if (program.opts().human) printHuman(r.result);
2592
- else printJson(r.result);
2593
- process.exit(r.exitCode);
2594
- }
2595
- program.command("hash <file>").action(async (file) => emit(await runHash({ file })));
2596
- program.command("fetch-guard <url>").action(async (url) => emit(await runFetchGuard({ url })));
2597
- program.command("validate <file>").action(async (file) => emit(await runValidate({ file })));
2598
- program.command("graph").description("graph subcommands").command("build <vault>").option("--out <path>", "graph output path", ".skillwiki/graph.json").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => emit(await runGraphBuild({ vault, out: opts.out })));
2599
- program.command("overlap <vault>").action(async (vault) => emit(await runOverlap({ vault })));
2600
- program.command("orphans [vault]").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => emit(await runOrphans({
2601
- vault,
2602
- envValue: process.env.WIKI_PATH,
2603
- home: process.env.HOME ?? "",
2604
- wiki: opts.wiki
2605
- })));
2606
- program.command("audit <file>").action(async (file) => emit(await runAudit({ file })));
2607
- program.command("install").option("--target <dir>", "target install directory", `${process.env.HOME ?? ""}/.claude/skills/`).option("--dry-run", "preview only", false).option("--skills-root <dir>", "source skills directory (defaults to packaged)").action(async (opts) => {
2608
- const skillsRoot = opts.skillsRoot ?? new URL("../skills/", import.meta.url).pathname;
2609
- emit(await runInstall({ skillsRoot, target: opts.target, dryRun: !!opts.dryRun }));
2610
- });
2611
- program.command("path").option("--vault <dir>", "explicit vault override (runtime)").option("--target <dir>", "explicit target override (init-time)").option("--wiki <name>", "wiki profile name").option("--init-time", "use init-time chain instead of runtime", false).option("--explain", "include resolution chain in output", false).action(async (opts) => {
2612
- const initTime = !!opts.initTime;
2613
- const flag = initTime ? opts.target : opts.vault;
2614
- emit(await runPath({
2615
- flag,
2616
- envValue: process.env.WIKI_PATH,
2617
- home: process.env.HOME ?? "",
2618
- initTime,
2619
- wiki: opts.wiki,
2620
- explain: !!opts.explain
2621
- }));
2622
- });
2623
- program.command("lang").option("--lang <code>", "explicit language override").option("--explain", "include resolution chain in output", false).action(async (opts) => {
2624
- emit(await runLang({
2625
- flag: opts.lang,
2626
- envValue: process.env.WIKI_LANG,
2627
- home: process.env.HOME ?? "",
2628
- explain: !!opts.explain
2629
- }));
2630
- });
2631
- program.command("init").option("--target <dir>", "explicit target directory").requiredOption("--domain <text>", "knowledge domain seed").option("--taxonomy <csv>", "comma-separated tag list").option("--lang <code>", "output language (BCP 47 or alias)").option("--force", "override existing target / env conflict", false).option("--no-env", "skip writing ~/.skillwiki/.env").option("--profile <name>", "write as named wiki profile instead of WIKI_PATH").action(async (opts) => {
2632
- const templates = new URL("../templates/", import.meta.url).pathname;
2633
- const taxonomy = typeof opts.taxonomy === "string" ? opts.taxonomy.split(",").map((s) => s.trim()).filter((s) => s.length > 0) : void 0;
2634
- emit(await runInit({
2635
- flag: opts.target,
2636
- envValue: process.env.WIKI_PATH,
2637
- home: process.env.HOME ?? "",
2638
- templates,
2639
- domain: opts.domain,
2640
- taxonomy,
2641
- lang: opts.lang,
2642
- force: !!opts.force,
2643
- noEnv: opts.env === false,
2644
- profile: opts.profile
2645
- }));
2646
- });
2647
- async function resolveVaultArg(arg, wiki) {
2648
- if (arg) return { ok: true, vault: arg };
2649
- const r = await resolveRuntimePath({
2650
- flag: void 0,
2651
- envValue: process.env.WIKI_PATH,
2652
- wikiEnv: process.env.WIKI,
2653
- home: process.env.HOME ?? "",
2654
- wiki
2655
- });
2656
- if (!r.ok) {
2657
- const exitCode = r.error === "UNKNOWN_WIKI_PROFILE" ? 35 : 25;
2658
- return { ok: false, exitCode, payload: r };
3696
+ // src/commands/self-update.ts
3697
+ import { execSync as execSync3 } from "child_process";
3698
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
3699
+ import { join as join24 } from "path";
3700
+ var DEFAULT_SOURCE_ROOT_SUFFIX = "/Desktop/code/llm-wiki";
3701
+ async function runSelfUpdate(input) {
3702
+ const currentVersion = JSON.parse(
3703
+ readFileSync7(new URL("../../package.json", import.meta.url), "utf8")
3704
+ ).version;
3705
+ const sourceRoot = input.sourceRoot ?? `${input.home}${DEFAULT_SOURCE_ROOT_SUFFIX}`;
3706
+ const localPkgPath = join24(sourceRoot, "packages", "cli", "package.json");
3707
+ const hasLocalSource = existsSync6(localPkgPath);
3708
+ if (input.check) {
3709
+ let availableVersion = null;
3710
+ let source;
3711
+ if (hasLocalSource) {
3712
+ source = "local";
3713
+ try {
3714
+ availableVersion = JSON.parse(readFileSync7(localPkgPath, "utf8")).version ?? null;
3715
+ } catch {
3716
+ availableVersion = null;
3717
+ }
3718
+ } else {
3719
+ source = "npm";
3720
+ try {
3721
+ availableVersion = execSync3("npm view skillwiki@beta version", {
3722
+ encoding: "utf8",
3723
+ timeout: 15e3
3724
+ }).trim();
3725
+ } catch (e) {
3726
+ return {
3727
+ exitCode: ExitCode.INTERNAL_ERROR,
3728
+ result: err("PREFLIGHT_FAILED", { message: `Failed to query npm registry: ${String(e)}` })
3729
+ };
3730
+ }
3731
+ }
3732
+ const updateAvailable = availableVersion !== null && availableVersion !== currentVersion;
3733
+ const hint = updateAvailable ? `Update available: ${currentVersion} \u2192 ${availableVersion} (${source})` : `Already up to date: v${currentVersion} (${source})`;
3734
+ return {
3735
+ exitCode: ExitCode.OK,
3736
+ result: ok({
3737
+ source,
3738
+ currentVersion,
3739
+ availableVersion,
3740
+ updateAvailable,
3741
+ humanHint: hint
3742
+ })
3743
+ };
2659
3744
  }
2660
- return { ok: true, vault: r.data.path };
2661
- }
2662
- program.command("links [vault]").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2663
- const v = await resolveVaultArg(vault, opts.wiki);
2664
- if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2665
- else emit(await runLinks({ vault: v.vault }));
2666
- });
2667
- program.command("tag-audit [vault]").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2668
- const v = await resolveVaultArg(vault, opts.wiki);
2669
- if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2670
- else emit(await runTagAudit({ vault: v.vault }));
2671
- });
2672
- program.command("index-check [vault]").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2673
- const v = await resolveVaultArg(vault, opts.wiki);
2674
- if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2675
- else emit(await runIndexCheck({ vault: v.vault }));
3745
+ if (hasLocalSource) {
3746
+ try {
3747
+ execSync3("npm run build -w packages/cli", {
3748
+ cwd: sourceRoot,
3749
+ stdio: "pipe",
3750
+ timeout: 6e4
3751
+ });
3752
+ } catch (e) {
3753
+ return {
3754
+ exitCode: ExitCode.INTERNAL_ERROR,
3755
+ result: err("BUILD_FAILED", { message: `Build failed: ${String(e)}` })
3756
+ };
3757
+ }
3758
+ try {
3759
+ execSync3("npm link ./packages/cli", {
3760
+ cwd: sourceRoot,
3761
+ stdio: "pipe",
3762
+ timeout: 3e4
3763
+ });
3764
+ } catch (e) {
3765
+ return {
3766
+ exitCode: ExitCode.INTERNAL_ERROR,
3767
+ result: err("LINK_FAILED", { message: `npm link failed: ${String(e)}` })
3768
+ };
3769
+ }
3770
+ const newVersion = (() => {
3771
+ try {
3772
+ return JSON.parse(readFileSync7(localPkgPath, "utf8")).version ?? "unknown";
3773
+ } catch {
3774
+ return "unknown";
3775
+ }
3776
+ })();
3777
+ return {
3778
+ exitCode: ExitCode.OK,
3779
+ result: ok({
3780
+ source: "local",
3781
+ currentVersion,
3782
+ availableVersion: newVersion,
3783
+ updateAvailable: newVersion !== currentVersion,
3784
+ newVersion,
3785
+ humanHint: `Built and linked from local source: v${newVersion}`
3786
+ })
3787
+ };
3788
+ }
3789
+ let latestVersion;
3790
+ try {
3791
+ latestVersion = execSync3("npm view skillwiki@beta version", {
3792
+ encoding: "utf8",
3793
+ timeout: 15e3
3794
+ }).trim();
3795
+ } catch (e) {
3796
+ return {
3797
+ exitCode: ExitCode.INTERNAL_ERROR,
3798
+ result: err("PREFLIGHT_FAILED", { message: `Failed to query npm registry: ${String(e)}` })
3799
+ };
3800
+ }
3801
+ if (latestVersion === currentVersion) {
3802
+ return {
3803
+ exitCode: ExitCode.OK,
3804
+ result: ok({
3805
+ source: "npm",
3806
+ currentVersion,
3807
+ availableVersion: latestVersion,
3808
+ updateAvailable: false,
3809
+ humanHint: `Already on latest beta: v${currentVersion}`
3810
+ })
3811
+ };
3812
+ }
3813
+ try {
3814
+ execSync3("npm install -g skillwiki@beta", {
3815
+ stdio: "pipe",
3816
+ timeout: 6e4
3817
+ });
3818
+ } catch (e) {
3819
+ return {
3820
+ exitCode: ExitCode.INTERNAL_ERROR,
3821
+ result: err("INSTALL_FAILED", { message: `npm install failed: ${String(e)}` })
3822
+ };
3823
+ }
3824
+ return {
3825
+ exitCode: ExitCode.OK,
3826
+ result: ok({
3827
+ source: "npm",
3828
+ currentVersion,
3829
+ availableVersion: latestVersion,
3830
+ updateAvailable: true,
3831
+ newVersion: latestVersion,
3832
+ humanHint: `Updated skillwiki ${currentVersion} \u2192 ${latestVersion} via npm@beta`
3833
+ })
3834
+ };
3835
+ }
3836
+
3837
+ // src/commands/transcripts.ts
3838
+ import { readdir as readdir5, stat as stat6, readFile as readFile16 } from "fs/promises";
3839
+ import { join as join25 } from "path";
3840
+ async function runTranscripts(input) {
3841
+ const dir = join25(input.vault, "raw", "transcripts");
3842
+ let entries;
3843
+ try {
3844
+ entries = await readdir5(dir, { withFileTypes: true });
3845
+ } catch {
3846
+ return { exitCode: ExitCode.VAULT_PATH_INVALID, result: { ok: false, error: "VAULT_PATH_INVALID", detail: `raw/transcripts/ not found: ${dir}` } };
3847
+ }
3848
+ const transcripts = [];
3849
+ for (const entry of entries) {
3850
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
3851
+ const filePath = join25(dir, entry.name);
3852
+ const content = await readFile16(filePath, "utf8");
3853
+ const fm = extractFrontmatter(content);
3854
+ if (!fm.ok) continue;
3855
+ const ingested = typeof fm.data.ingested === "string" ? fm.data.ingested : "";
3856
+ if (input.since && ingested && ingested < input.since) continue;
3857
+ const s = await stat6(filePath);
3858
+ transcripts.push({
3859
+ file: `raw/transcripts/${entry.name}`,
3860
+ ingested,
3861
+ size: s.size
3862
+ });
3863
+ }
3864
+ const hint = transcripts.length > 0 ? transcripts.map((t) => `${t.file} (ingested: ${t.ingested || "unknown"}, ${t.size}B)`).join("\n") : "no transcript files found";
3865
+ return { exitCode: ExitCode.OK, result: ok({ transcripts, humanHint: hint }) };
3866
+ }
3867
+
3868
+ // src/commands/project-index.ts
3869
+ import { readdir as readdir6, readFile as readFile17, writeFile as writeFile12, mkdir as mkdir8 } from "fs/promises";
3870
+ import { join as join26, dirname as dirname10 } from "path";
3871
+ var LAYER2_DIRS = ["entities", "concepts", "comparisons", "queries", "meta"];
3872
+ async function runProjectIndex(input) {
3873
+ const slug = input.slug;
3874
+ const projectDir = join26(input.vault, "projects", slug);
3875
+ try {
3876
+ await readdir6(projectDir);
3877
+ } catch {
3878
+ return {
3879
+ exitCode: ExitCode.PROJECT_NOT_FOUND,
3880
+ result: err("PROJECT_NOT_FOUND", { slug, path: projectDir })
3881
+ };
3882
+ }
3883
+ const wikilinkPattern = `[[${slug}]]`;
3884
+ const entries = [];
3885
+ const compoundDir = join26(input.vault, "projects", slug, "compound");
3886
+ try {
3887
+ const compoundFiles = await readdir6(compoundDir, { withFileTypes: true });
3888
+ for (const entry of compoundFiles) {
3889
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
3890
+ const filePath = join26(compoundDir, entry.name);
3891
+ let text;
3892
+ try {
3893
+ text = await readFile17(filePath, "utf8");
3894
+ } catch {
3895
+ continue;
3896
+ }
3897
+ const fm = extractFrontmatter(text);
3898
+ if (!fm.ok) continue;
3899
+ entries.push({
3900
+ page: `projects/${slug}/compound/${entry.name}`,
3901
+ type: typeof fm.data.type === "string" ? fm.data.type : "compound",
3902
+ title: typeof fm.data.title === "string" ? fm.data.title : entry.name.replace(/\.md$/, "")
3903
+ });
3904
+ }
3905
+ } catch {
3906
+ }
3907
+ for (const dir of LAYER2_DIRS) {
3908
+ let files;
3909
+ try {
3910
+ files = await readdir6(join26(input.vault, dir), { withFileTypes: true });
3911
+ } catch {
3912
+ continue;
3913
+ }
3914
+ for (const entry of files) {
3915
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
3916
+ const filePath = join26(input.vault, dir, entry.name);
3917
+ let text;
3918
+ try {
3919
+ text = await readFile17(filePath, "utf8");
3920
+ } catch {
3921
+ continue;
3922
+ }
3923
+ const fm = extractFrontmatter(text);
3924
+ if (!fm.ok) continue;
3925
+ const pp = fm.data.provenance_projects;
3926
+ if (!Array.isArray(pp) || !pp.some((p) => String(p) === wikilinkPattern)) continue;
3927
+ entries.push({
3928
+ page: `${dir}/${entry.name}`,
3929
+ type: typeof fm.data.type === "string" ? fm.data.type : dir.slice(0, -1),
3930
+ title: typeof fm.data.title === "string" ? fm.data.title : entry.name.replace(/\.md$/, "")
3931
+ });
3932
+ }
3933
+ }
3934
+ const typeOrder = { entity: 0, concept: 1, comparison: 2, query: 3, summary: 4, meta: 5, pattern: 6, gotcha: 7, lesson: 8, antipattern: 9, compound: 10 };
3935
+ entries.sort((a, b) => {
3936
+ const ta = typeOrder[a.type] ?? 99;
3937
+ const tb = typeOrder[b.type] ?? 99;
3938
+ return ta !== tb ? ta - tb : a.title.localeCompare(b.title);
3939
+ });
3940
+ const indexPath = join26(projectDir, "knowledge.md");
3941
+ let existing = false;
3942
+ let stale = false;
3943
+ try {
3944
+ const existingText = await readFile17(indexPath, "utf8");
3945
+ existing = true;
3946
+ const existingEntries = existingText.split("\n").filter((l) => l.startsWith("- [["));
3947
+ const existingPages = new Set(existingEntries.map((l) => {
3948
+ const m = l.match(/\[\[([^\]]+)\]\]/);
3949
+ return m ? m[1] : "";
3950
+ }));
3951
+ const currentPages = new Set(entries.map((e) => e.page.replace(/\.md$/, "")));
3952
+ stale = existingPages.size !== currentPages.size || [...currentPages].some((p) => !existingPages.has(p));
3953
+ } catch {
3954
+ }
3955
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
3956
+ const grouped = /* @__PURE__ */ new Map();
3957
+ for (const e of entries) {
3958
+ const group = e.type;
3959
+ if (!grouped.has(group)) grouped.set(group, []);
3960
+ grouped.get(group).push(e);
3961
+ }
3962
+ let body = `# Knowledge Index: ${slug}
3963
+
3964
+ Autogenerated by \`skillwiki project-index\` on ${today}.
3965
+
3966
+ `;
3967
+ for (const [type, items] of grouped) {
3968
+ body += `## ${type}
3969
+
3970
+ `;
3971
+ for (const item of items) {
3972
+ const pageRef = item.page.replace(/\.md$/, "");
3973
+ body += `- [[${pageRef}]] \u2014 ${item.title}
3974
+ `;
3975
+ }
3976
+ body += "\n";
3977
+ }
3978
+ if (entries.length === 0) {
3979
+ body += `No Layer 2 pages reference \`[[${slug}]]\` in provenance_projects.
3980
+ `;
3981
+ }
3982
+ if (input.apply) {
3983
+ try {
3984
+ await mkdir8(dirname10(indexPath), { recursive: true });
3985
+ await writeFile12(indexPath, body, "utf8");
3986
+ } catch (e) {
3987
+ return {
3988
+ exitCode: ExitCode.WRITE_FAILED,
3989
+ result: err("WRITE_FAILED", { file: indexPath, message: String(e) })
3990
+ };
3991
+ }
3992
+ }
3993
+ const action = input.apply ? `written ${entries.length} entries to ${indexPath}` : `${entries.length} entries found (use --apply to write)`;
3994
+ const staleHint = stale ? " (STALE \u2014 existing index outdated)" : existing ? " (up to date)" : "";
3995
+ return {
3996
+ exitCode: ExitCode.OK,
3997
+ result: ok({
3998
+ slug,
3999
+ entries,
4000
+ existing,
4001
+ stale,
4002
+ index_path: `projects/${slug}/knowledge.md`,
4003
+ humanHint: `project: ${slug}
4004
+ entries: ${entries.length}${staleHint}
4005
+ ${action}
4006
+
4007
+ ${entries.map((e) => ` ${e.type}: [[${e.page.replace(/\.md$/, "")}]] \u2014 ${e.title}`).join("\n")}`
4008
+ })
4009
+ };
4010
+ }
4011
+
4012
+ // src/commands/compound.ts
4013
+ import { writeFile as writeFile13, mkdir as mkdir9, readdir as readdir7, unlink as unlink2 } from "fs/promises";
4014
+ import { join as join27 } from "path";
4015
+ import { existsSync as existsSync7 } from "fs";
4016
+ import { readFile as readFile18 } from "fs/promises";
4017
+ var RETRO_HEADING_RE = /^## \[(\d{4}-\d{2}-\d{2})(?:\s+[^\]]+)?\] retro \| loop cycle(?: (\d+))?: (.+)$/;
4018
+ var FIELD_RE = {
4019
+ improve: /^-\s+\*?\*?Improve:?\*?\*?\s*(.+)$/m,
4020
+ friction: /^-\s+\*?\*?Friction:?\*?\*?\s*(.+)$/m,
4021
+ generalize: /^-\s+\*?\*?Generalize\?:?\*?\*?\s*(.+)$/m
4022
+ };
4023
+ function slugify(name) {
4024
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-+$/g, "");
4025
+ }
4026
+ function inferType(improve, friction) {
4027
+ if (/\bshould\b/i.test(improve)) return "pattern";
4028
+ if (/\bbug\b|\berror\b/i.test(friction)) return "gotcha";
4029
+ return "lesson";
4030
+ }
4031
+ function extractTags(generalize) {
4032
+ const tags = [];
4033
+ const parenRe = /\(([^)]+)\)/g;
4034
+ let match;
4035
+ while ((match = parenRe.exec(generalize)) !== null) {
4036
+ const words = match[1].trim().split(/\s+/);
4037
+ for (const w of words) {
4038
+ const cleaned = w.toLowerCase().replace(/[^a-z0-9-]/g, "").trim();
4039
+ if (cleaned.length > 0) tags.push(cleaned);
4040
+ }
4041
+ }
4042
+ const appliesRe = /applies to any\s+(.+?)(?:\.|,|$)/i;
4043
+ const appliesMatch = generalize.match(appliesRe);
4044
+ if (appliesMatch) {
4045
+ const words = appliesMatch[1].trim().split(/\s+/);
4046
+ for (const w of words) {
4047
+ const cleaned = w.toLowerCase().replace(/[^a-z0-9-]/g, "").trim();
4048
+ if (cleaned.length > 0) tags.push(cleaned);
4049
+ }
4050
+ }
4051
+ if (tags.length === 0) {
4052
+ tags.push("dev-loop");
4053
+ }
4054
+ return [...new Set(tags)];
4055
+ }
4056
+ function parseRationale(generalize) {
4057
+ const yesMatch = generalize.match(/^yes[,:]\s*(.+)$/i);
4058
+ if (yesMatch) return yesMatch[1].trim();
4059
+ if (/^yes$/i.test(generalize.trim())) return "";
4060
+ return generalize.trim();
4061
+ }
4062
+ function parseRetroEntries(logText) {
4063
+ const entries = [];
4064
+ const lines = logText.split("\n");
4065
+ let currentDate = "";
4066
+ let currentCycleName = "";
4067
+ let currentBlock = [];
4068
+ let foundHeading = false;
4069
+ for (const line of lines) {
4070
+ const headingMatch = line.match(RETRO_HEADING_RE);
4071
+ if (headingMatch) {
4072
+ if (foundHeading && currentBlock.length > 0) {
4073
+ const entry = extractRetroFields(currentDate, currentCycleName, currentBlock);
4074
+ if (entry) entries.push(entry);
4075
+ }
4076
+ currentDate = headingMatch[1];
4077
+ currentCycleName = headingMatch[3];
4078
+ currentBlock = [];
4079
+ foundHeading = true;
4080
+ continue;
4081
+ }
4082
+ if (foundHeading && /^## /.test(line)) {
4083
+ const entry = extractRetroFields(currentDate, currentCycleName, currentBlock);
4084
+ if (entry) entries.push(entry);
4085
+ foundHeading = false;
4086
+ currentBlock = [];
4087
+ continue;
4088
+ }
4089
+ if (foundHeading) {
4090
+ currentBlock.push(line);
4091
+ }
4092
+ }
4093
+ if (foundHeading && currentBlock.length > 0) {
4094
+ const entry = extractRetroFields(currentDate, currentCycleName, currentBlock);
4095
+ if (entry) entries.push(entry);
4096
+ }
4097
+ return entries;
4098
+ }
4099
+ function extractRetroFields(date, cycleName, block) {
4100
+ const text = block.join("\n");
4101
+ const improveMatch = text.match(FIELD_RE.improve);
4102
+ const frictionMatch = text.match(FIELD_RE.friction);
4103
+ const generalizeMatch = text.match(FIELD_RE.generalize);
4104
+ if (!generalizeMatch) return null;
4105
+ return {
4106
+ date,
4107
+ cycleName,
4108
+ improve: improveMatch?.[1]?.trim() ?? "",
4109
+ friction: frictionMatch?.[1]?.trim() ?? "",
4110
+ generalize: generalizeMatch[1].trim()
4111
+ };
4112
+ }
4113
+ async function runCompound(input) {
4114
+ const logPath = join27(input.vault, "log.md");
4115
+ let logText;
4116
+ try {
4117
+ logText = await readFile18(logPath, "utf8");
4118
+ } catch {
4119
+ return { exitCode: ExitCode.FILE_NOT_FOUND, result: err("FILE_NOT_FOUND", { path: logPath }) };
4120
+ }
4121
+ const entries = parseRetroEntries(logText);
4122
+ const promoted = [];
4123
+ const skipped = [];
4124
+ const compoundDir = join27(input.vault, "projects", input.project, "compound");
4125
+ for (const entry of entries) {
4126
+ const generalizeValue = entry.generalize.trim();
4127
+ if (!/^yes/i.test(generalizeValue)) {
4128
+ skipped.push(entry.date);
4129
+ continue;
4130
+ }
4131
+ const slug = slugify(entry.cycleName);
4132
+ const compoundPath = join27(compoundDir, `${slug}.md`);
4133
+ if (existsSync7(compoundPath)) {
4134
+ skipped.push(entry.date);
4135
+ continue;
4136
+ }
4137
+ const type = inferType(entry.improve, entry.friction);
4138
+ const rationale = parseRationale(generalizeValue);
4139
+ const tags = extractTags(generalizeValue);
4140
+ const tagsYaml = tags.map((t) => t).join(", ");
4141
+ const title = entry.cycleName;
4142
+ const typeLabel = type.charAt(0).toUpperCase() + type.slice(1);
4143
+ const frontmatter = [
4144
+ "---",
4145
+ `title: ${title}`,
4146
+ `created: ${entry.date}`,
4147
+ `updated: ${entry.date}`,
4148
+ `type: ${type}`,
4149
+ `tags: [${tagsYaml}]`,
4150
+ `confidence: medium`,
4151
+ `project: "[[${input.project}]]"`,
4152
+ `work_items: []`,
4153
+ "---"
4154
+ ].join("\n");
4155
+ const body = [
4156
+ `## ${typeLabel}`,
4157
+ "",
4158
+ entry.improve,
4159
+ "",
4160
+ "## Evidence",
4161
+ "",
4162
+ entry.friction,
4163
+ "",
4164
+ "## Source",
4165
+ "",
4166
+ `Retro from ${entry.date} | ${entry.cycleName}. Generalize rationale: ${rationale}`,
4167
+ ""
4168
+ ].join("\n");
4169
+ const content = frontmatter + "\n" + body;
4170
+ if (!input.dryRun) {
4171
+ if (!existsSync7(compoundDir)) {
4172
+ await mkdir9(compoundDir, { recursive: true });
4173
+ }
4174
+ await writeFile13(compoundPath, content, "utf8");
4175
+ }
4176
+ promoted.push(`${slug}.md`);
4177
+ }
4178
+ const exitCode = promoted.length > 0 ? ExitCode.COMPOUND_PROMOTED : ExitCode.OK;
4179
+ const hintLines = [`scanned: ${entries.length}`];
4180
+ if (promoted.length > 0) hintLines.push(`promoted: ${promoted.length}`);
4181
+ if (skipped.length > 0) hintLines.push(`skipped (Generalize?: no): ${skipped.length}`);
4182
+ return {
4183
+ exitCode,
4184
+ result: ok({
4185
+ scanned: entries.length,
4186
+ promoted,
4187
+ skipped,
4188
+ humanHint: hintLines.join("\n")
4189
+ })
4190
+ };
4191
+ }
4192
+ async function runCompoundDelete(input) {
4193
+ const projectDir = join27(input.vault, "projects", input.project);
4194
+ if (!existsSync7(projectDir)) {
4195
+ return {
4196
+ exitCode: ExitCode.PROJECT_NOT_FOUND,
4197
+ result: err("PROJECT_NOT_FOUND", { slug: input.project, path: projectDir })
4198
+ };
4199
+ }
4200
+ const entryName = input.entry.replace(/\.md$/, "");
4201
+ const compoundPath = join27(projectDir, "compound", `${entryName}.md`);
4202
+ if (!existsSync7(compoundPath)) {
4203
+ return {
4204
+ exitCode: ExitCode.FILE_NOT_FOUND,
4205
+ result: err("FILE_NOT_FOUND", { path: compoundPath })
4206
+ };
4207
+ }
4208
+ try {
4209
+ await unlink2(compoundPath);
4210
+ } catch (e) {
4211
+ return {
4212
+ exitCode: ExitCode.WRITE_FAILED,
4213
+ result: err("WRITE_FAILED", { file: compoundPath, message: String(e) })
4214
+ };
4215
+ }
4216
+ const indexResult = await runProjectIndex({ vault: input.vault, slug: input.project, apply: true });
4217
+ if (!indexResult.result.ok) {
4218
+ return {
4219
+ exitCode: indexResult.exitCode,
4220
+ result: err("INDEX_REGEN_FAILED", { detail: indexResult.result })
4221
+ };
4222
+ }
4223
+ return {
4224
+ exitCode: ExitCode.OK,
4225
+ result: ok({
4226
+ deleted: compoundPath,
4227
+ project: input.project,
4228
+ humanHint: `deleted: ${entryName}.md
4229
+ project: ${input.project}
4230
+ knowledge.md regenerated`
4231
+ })
4232
+ };
4233
+ }
4234
+ async function runCompoundList(input) {
4235
+ const compoundDir = join27(input.vault, "projects", input.project, "compound");
4236
+ if (!existsSync7(compoundDir)) {
4237
+ return {
4238
+ exitCode: ExitCode.OK,
4239
+ result: ok({
4240
+ project: input.project,
4241
+ entries: [],
4242
+ humanHint: `project: ${input.project}
4243
+ entries: 0
4244
+ no compound directory found`
4245
+ })
4246
+ };
4247
+ }
4248
+ let dirents;
4249
+ try {
4250
+ dirents = await readdir7(compoundDir, { withFileTypes: true });
4251
+ } catch {
4252
+ return {
4253
+ exitCode: ExitCode.OK,
4254
+ result: ok({
4255
+ project: input.project,
4256
+ entries: [],
4257
+ humanHint: `project: ${input.project}
4258
+ entries: 0
4259
+ could not read compound directory`
4260
+ })
4261
+ };
4262
+ }
4263
+ const entries = [];
4264
+ for (const dirent of dirents) {
4265
+ if (!dirent.isFile() || !dirent.name.endsWith(".md")) continue;
4266
+ const filePath = join27(compoundDir, dirent.name);
4267
+ let text;
4268
+ try {
4269
+ text = await readFile18(filePath, "utf8");
4270
+ } catch {
4271
+ continue;
4272
+ }
4273
+ const fm = extractFrontmatter(text);
4274
+ if (!fm.ok) continue;
4275
+ const tags = Array.isArray(fm.data.tags) ? fm.data.tags.map((t) => String(t)) : typeof fm.data.tags === "string" ? fm.data.tags.split(",").map((s) => s.trim()) : [];
4276
+ entries.push({
4277
+ file: dirent.name,
4278
+ title: typeof fm.data.title === "string" ? fm.data.title : dirent.name.replace(/\.md$/, ""),
4279
+ type: typeof fm.data.type === "string" ? fm.data.type : "lesson",
4280
+ created: typeof fm.data.created === "string" ? fm.data.created : "",
4281
+ tags
4282
+ });
4283
+ }
4284
+ const hint = entries.length > 0 ? [`project: ${input.project}`, `entries: ${entries.length}`, "", ...entries.map((e) => ` ${e.file}: ${e.title} (${e.type}, created: ${e.created || "unknown"}, tags: ${e.tags.join(", ") || "none"})`)].join("\n") : `project: ${input.project}
4285
+ entries: 0
4286
+ no compound entries found`;
4287
+ return {
4288
+ exitCode: ExitCode.OK,
4289
+ result: ok({
4290
+ project: input.project,
4291
+ entries,
4292
+ humanHint: hint
4293
+ })
4294
+ };
4295
+ }
4296
+
4297
+ // src/commands/observe.ts
4298
+ import { mkdir as mkdir10, writeFile as writeFile14 } from "fs/promises";
4299
+ import { existsSync as existsSync8, statSync as statSync2 } from "fs";
4300
+ import { join as join28 } from "path";
4301
+ import { createHash as createHash3 } from "crypto";
4302
+ var ALLOWED_KINDS = /* @__PURE__ */ new Set(["note", "bug", "task", "idea", "session-log"]);
4303
+ function slugify2(text) {
4304
+ const words = text.trim().split(/\s+/).slice(0, 6).join("-").toLowerCase().replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "");
4305
+ return words || "untitled";
4306
+ }
4307
+ async function runObserve(input) {
4308
+ const kind = input.kind || "note";
4309
+ if (!ALLOWED_KINDS.has(kind)) {
4310
+ return {
4311
+ exitCode: ExitCode.SCHEME_REJECTED,
4312
+ result: err("SCHEME_REJECTED", {
4313
+ message: `Invalid kind "${kind}". Allowed: ${[...ALLOWED_KINDS].join(", ")}`
4314
+ })
4315
+ };
4316
+ }
4317
+ if (!input.text || input.text.trim().length === 0) {
4318
+ return {
4319
+ exitCode: ExitCode.SCHEME_REJECTED,
4320
+ result: err("SCHEME_REJECTED", { message: "Text must not be empty" })
4321
+ };
4322
+ }
4323
+ if (!existsSync8(input.vault) || !statSync2(input.vault).isDirectory()) {
4324
+ return {
4325
+ exitCode: ExitCode.VAULT_PATH_INVALID,
4326
+ result: err("VAULT_PATH_INVALID", { path: input.vault })
4327
+ };
4328
+ }
4329
+ const transcriptsDir = join28(input.vault, "raw", "transcripts");
4330
+ try {
4331
+ await mkdir10(transcriptsDir, { recursive: true });
4332
+ } catch {
4333
+ return {
4334
+ exitCode: ExitCode.VAULT_PATH_INVALID,
4335
+ result: err("VAULT_PATH_INVALID", { path: transcriptsDir })
4336
+ };
4337
+ }
4338
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
4339
+ const slug = slugify2(input.text);
4340
+ const fileName = `${today}-observation-${slug}.md`;
4341
+ const filePath = join28(transcriptsDir, fileName);
4342
+ const body = `
4343
+ ${input.text.trim()}
4344
+ `;
4345
+ const sha256 = createHash3("sha256").update(Buffer.from(body, "utf8")).digest("hex");
4346
+ const frontmatterLines = [
4347
+ "---",
4348
+ "source_url:",
4349
+ `ingested: ${today}`,
4350
+ `sha256: ${sha256}`,
4351
+ `kind: ${kind}`
4352
+ ];
4353
+ if (input.project) {
4354
+ frontmatterLines.push(`project: "[[${input.project}]]"`);
4355
+ }
4356
+ frontmatterLines.push("---");
4357
+ const content = frontmatterLines.join("\n") + body;
4358
+ try {
4359
+ await writeFile14(filePath, content, "utf8");
4360
+ } catch (e) {
4361
+ return {
4362
+ exitCode: ExitCode.WRITE_FAILED,
4363
+ result: err("WRITE_FAILED", { path: filePath, message: String(e) })
4364
+ };
4365
+ }
4366
+ appendLastOp(input.vault, {
4367
+ operation: "observe",
4368
+ summary: `created observation: ${slug}`,
4369
+ files: [`raw/transcripts/${fileName}`],
4370
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4371
+ });
4372
+ const relPath = `raw/transcripts/${fileName}`;
4373
+ const humanHint = `created ${relPath} (${sha256.slice(0, 12)}...)`;
4374
+ return {
4375
+ exitCode: ExitCode.OK,
4376
+ result: ok({ path: relPath, sha256, humanHint })
4377
+ };
4378
+ }
4379
+
4380
+ // src/commands/ingest.ts
4381
+ import { readFile as readFile19, writeFile as writeFile15, mkdir as mkdir11 } from "fs/promises";
4382
+ import { join as join29 } from "path";
4383
+ import { createHash as createHash4 } from "crypto";
4384
+ var ALLOWED_TYPES = /* @__PURE__ */ new Set(["entity", "concept", "comparison", "query"]);
4385
+ var TYPE_DIR = {
4386
+ entity: "entities",
4387
+ concept: "concepts",
4388
+ comparison: "comparisons",
4389
+ query: "queries"
4390
+ };
4391
+ var ALLOWED_PROVENANCE = /* @__PURE__ */ new Set(["research", "project"]);
4392
+ function slugify3(text) {
4393
+ return text.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 80) || "untitled";
4394
+ }
4395
+ function isUrl(source) {
4396
+ try {
4397
+ const u = new URL(source);
4398
+ return u.protocol === "https:" || u.protocol === "http:";
4399
+ } catch {
4400
+ return false;
4401
+ }
4402
+ }
4403
+ function todayIso() {
4404
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
4405
+ }
4406
+ function buildRawContent(sourceUrl, ingested, sha256, body) {
4407
+ const lines = [
4408
+ "---",
4409
+ sourceUrl !== null ? `source_url: "${sourceUrl}"` : "source_url:",
4410
+ `ingested: ${ingested}`,
4411
+ `sha256: ${sha256}`,
4412
+ `ingested_by: wiki-ingest`,
4413
+ "---",
4414
+ "",
4415
+ body
4416
+ ];
4417
+ return lines.join("\n");
4418
+ }
4419
+ function buildTypedContent(title, ingested, type, tags, rawRelPath, provenance) {
4420
+ const aliases = [];
4421
+ const sourcesYaml = ` - ${rawRelPath}`;
4422
+ const tagsYaml = tags.length > 0 ? tags.map((t) => ` - ${t}`).join("\n") : " []";
4423
+ const fm = {
4424
+ title,
4425
+ aliases,
4426
+ created: ingested,
4427
+ updated: ingested,
4428
+ type,
4429
+ tags,
4430
+ sources: [rawRelPath],
4431
+ confidence: "medium"
4432
+ };
4433
+ if (provenance) {
4434
+ fm.provenance = provenance;
4435
+ }
4436
+ const fmLines = ["---"];
4437
+ fmLines.push(`title: "${title}"`);
4438
+ if (aliases.length > 0) {
4439
+ fmLines.push("aliases:");
4440
+ for (const a of aliases) fmLines.push(` - ${a}`);
4441
+ } else {
4442
+ fmLines.push("aliases: []");
4443
+ }
4444
+ fmLines.push(`created: ${ingested}`);
4445
+ fmLines.push(`updated: ${ingested}`);
4446
+ fmLines.push(`type: ${type}`);
4447
+ fmLines.push("tags:");
4448
+ fmLines.push(tagsYaml);
4449
+ fmLines.push("sources:");
4450
+ fmLines.push(sourcesYaml);
4451
+ fmLines.push("confidence: medium");
4452
+ if (provenance) {
4453
+ fmLines.push(`provenance: ${provenance}`);
4454
+ }
4455
+ fmLines.push("---");
4456
+ fmLines.push("");
4457
+ const body = [
4458
+ `# ${title}`,
4459
+ "",
4460
+ "## Overview",
4461
+ "",
4462
+ "## See also",
4463
+ "",
4464
+ "## Sources",
4465
+ "",
4466
+ `^[${rawRelPath}]`,
4467
+ ""
4468
+ ].join("\n");
4469
+ return fmLines.join("\n") + body;
4470
+ }
4471
+ async function runIngest(input) {
4472
+ if (!input.source || input.source.trim().length === 0) {
4473
+ return {
4474
+ exitCode: ExitCode.SCHEME_REJECTED,
4475
+ result: err("SCHEME_REJECTED", { message: "source is required" })
4476
+ };
4477
+ }
4478
+ if (!input.vault || input.vault.trim().length === 0) {
4479
+ return {
4480
+ exitCode: ExitCode.VAULT_PATH_INVALID,
4481
+ result: err("VAULT_PATH_INVALID", { message: "vault path is required" })
4482
+ };
4483
+ }
4484
+ if (!input.type || !ALLOWED_TYPES.has(input.type)) {
4485
+ return {
4486
+ exitCode: ExitCode.SCHEME_REJECTED,
4487
+ result: err("SCHEME_REJECTED", {
4488
+ message: `Invalid type "${input.type}". Allowed: ${[...ALLOWED_TYPES].join(", ")}`
4489
+ })
4490
+ };
4491
+ }
4492
+ if (!input.title || input.title.trim().length === 0) {
4493
+ return {
4494
+ exitCode: ExitCode.SCHEME_REJECTED,
4495
+ result: err("SCHEME_REJECTED", { message: "title is required" })
4496
+ };
4497
+ }
4498
+ if (input.provenance && !ALLOWED_PROVENANCE.has(input.provenance)) {
4499
+ return {
4500
+ exitCode: ExitCode.SCHEME_REJECTED,
4501
+ result: err("SCHEME_REJECTED", {
4502
+ message: `Invalid provenance "${input.provenance}". Allowed: ${[...ALLOWED_PROVENANCE].join(", ")}`
4503
+ })
4504
+ };
4505
+ }
4506
+ let sourceContent;
4507
+ let sourceUrl = null;
4508
+ if (isUrl(input.source)) {
4509
+ sourceUrl = input.source;
4510
+ const guardResult = runFetchGuardSync({ url: input.source });
4511
+ if (!guardResult.result.ok) {
4512
+ return {
4513
+ exitCode: ExitCode.INGEST_VALIDATION_FAILED,
4514
+ result: err("INGEST_VALIDATION_FAILED", {
4515
+ message: "source URL blocked by fetch-guard",
4516
+ guardError: guardResult.result.error,
4517
+ guardDetail: guardResult.result.detail
4518
+ })
4519
+ };
4520
+ }
4521
+ const fetchResult = await controlledFetch(input.source, {
4522
+ timeoutMs: 15e3,
4523
+ maxBytes: 1024 * 1024,
4524
+ // 1 MB
4525
+ maxRedirects: 5
4526
+ });
4527
+ if (!fetchResult.ok) {
4528
+ return {
4529
+ exitCode: ExitCode.INGEST_VALIDATION_FAILED,
4530
+ result: err("INGEST_VALIDATION_FAILED", {
4531
+ message: "failed to fetch source URL",
4532
+ fetchError: fetchResult.error,
4533
+ fetchDetail: fetchResult.detail
4534
+ })
4535
+ };
4536
+ }
4537
+ sourceContent = fetchResult.data.body;
4538
+ } else {
4539
+ try {
4540
+ sourceContent = await readFile19(input.source, "utf8");
4541
+ } catch {
4542
+ return {
4543
+ exitCode: ExitCode.FILE_NOT_FOUND,
4544
+ result: err("FILE_NOT_FOUND", { path: input.source })
4545
+ };
4546
+ }
4547
+ }
4548
+ const sha256 = createHash4("sha256").update(Buffer.from(sourceContent, "utf8")).digest("hex");
4549
+ const today = todayIso();
4550
+ const slug = slugify3(input.title);
4551
+ const tags = input.tags && input.tags.length > 0 ? input.tags : [];
4552
+ const rawRelPath = `raw/articles/${slug}.md`;
4553
+ const typedDir = TYPE_DIR[input.type] ?? `${input.type}s`;
4554
+ const typedRelPath = `${typedDir}/${slug}.md`;
4555
+ const rawAbsPath = join29(input.vault, rawRelPath);
4556
+ const typedAbsPath = join29(input.vault, typedRelPath);
4557
+ const rawContent = buildRawContent(sourceUrl, today, sha256, sourceContent);
4558
+ const typedContent = buildTypedContent(
4559
+ input.title,
4560
+ today,
4561
+ input.type,
4562
+ tags,
4563
+ rawRelPath,
4564
+ input.provenance
4565
+ );
4566
+ if (input.dryRun) {
4567
+ return {
4568
+ exitCode: ExitCode.OK,
4569
+ result: ok({
4570
+ raw_path: rawRelPath,
4571
+ typed_path: typedRelPath,
4572
+ sha256,
4573
+ dry_run: true,
4574
+ humanHint: [
4575
+ `DRY RUN \u2014 would create:`,
4576
+ ` ${rawRelPath} (sha256: ${sha256.slice(0, 12)}...)`,
4577
+ ` ${typedRelPath}`,
4578
+ ` type: ${input.type}, tags: [${tags.join(", ")}]`,
4579
+ input.provenance ? ` provenance: ${input.provenance}` : ""
4580
+ ].filter(Boolean).join("\n")
4581
+ })
4582
+ };
4583
+ }
4584
+ const typedFm = {
4585
+ title: input.title,
4586
+ aliases: [],
4587
+ created: today,
4588
+ updated: today,
4589
+ type: input.type,
4590
+ tags,
4591
+ sources: [rawRelPath],
4592
+ confidence: "medium",
4593
+ ...input.provenance ? { provenance: input.provenance } : {}
4594
+ };
4595
+ const det = detectSchema(typedFm);
4596
+ if (!det.schema) {
4597
+ return {
4598
+ exitCode: ExitCode.INGEST_VALIDATION_FAILED,
4599
+ result: err("INGEST_VALIDATION_FAILED", {
4600
+ message: "generated typed-knowledge page could not be detected as a valid schema"
4601
+ })
4602
+ };
4603
+ }
4604
+ const parsed = TypedKnowledgeSchema.safeParse(typedFm);
4605
+ if (!parsed.success) {
4606
+ const errors = parsed.error.issues.map((i) => ({
4607
+ path: i.path.join("."),
4608
+ message: i.message
4609
+ }));
4610
+ return {
4611
+ exitCode: ExitCode.INGEST_VALIDATION_FAILED,
4612
+ result: err("INGEST_VALIDATION_FAILED", {
4613
+ message: "generated typed-knowledge page failed schema validation",
4614
+ errors
4615
+ })
4616
+ };
4617
+ }
4618
+ try {
4619
+ await mkdir11(join29(input.vault, "raw", "articles"), { recursive: true });
4620
+ await writeFile15(rawAbsPath, rawContent, "utf8");
4621
+ } catch (e) {
4622
+ return {
4623
+ exitCode: ExitCode.WRITE_FAILED,
4624
+ result: err("WRITE_FAILED", { path: rawAbsPath, message: String(e) })
4625
+ };
4626
+ }
4627
+ try {
4628
+ await mkdir11(join29(input.vault, typedDir), { recursive: true });
4629
+ await writeFile15(typedAbsPath, typedContent, "utf8");
4630
+ } catch (e) {
4631
+ return {
4632
+ exitCode: ExitCode.WRITE_FAILED,
4633
+ result: err("WRITE_FAILED", { path: typedAbsPath, message: String(e) })
4634
+ };
4635
+ }
4636
+ const humanHint = [
4637
+ `created:`,
4638
+ ` ${rawRelPath} (sha256: ${sha256.slice(0, 12)}...)`,
4639
+ ` ${typedRelPath}`
4640
+ ].join("\n");
4641
+ appendLastOp(input.vault, {
4642
+ operation: "ingest",
4643
+ summary: `added ${slug}`,
4644
+ files: [rawRelPath, typedRelPath],
4645
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4646
+ });
4647
+ return {
4648
+ exitCode: ExitCode.OK,
4649
+ result: ok({
4650
+ raw_path: rawRelPath,
4651
+ typed_path: typedRelPath,
4652
+ sha256,
4653
+ dry_run: false,
4654
+ humanHint
4655
+ })
4656
+ };
4657
+ }
4658
+
4659
+ // src/commands/tag-sync.ts
4660
+ import { writeFile as writeFile16 } from "fs/promises";
4661
+ var ENUM_MIRRORS = {
4662
+ provenance: ["research", "project", "mixed"],
4663
+ confidence: ["high", "medium", "low"]
4664
+ };
4665
+ function toNestedTag(field, value) {
4666
+ return `${field}/${value}`;
4667
+ }
4668
+ function expectedNestedTags(fm) {
4669
+ const expected = /* @__PURE__ */ new Set();
4670
+ for (const [field, allowedValues] of Object.entries(ENUM_MIRRORS)) {
4671
+ const value = fm[field];
4672
+ if (typeof value === "string" && allowedValues.includes(value)) {
4673
+ expected.add(toNestedTag(field, value));
4674
+ }
4675
+ }
4676
+ return expected;
4677
+ }
4678
+ function parseTagsFromYaml(rawFm) {
4679
+ const inlineMatch = rawFm.match(/^tags:\s*\[([^\]]*)\]/m);
4680
+ if (inlineMatch) {
4681
+ return inlineMatch[1].split(",").map((t) => t.trim().replace(/^['"]|['"]$/g, "")).filter((t) => t.length > 0);
4682
+ }
4683
+ const lines = rawFm.split("\n");
4684
+ const tagItems = [];
4685
+ let inTags = false;
4686
+ for (const line of lines) {
4687
+ if (/^tags:\s*$/.test(line)) {
4688
+ inTags = true;
4689
+ continue;
4690
+ }
4691
+ if (inTags) {
4692
+ if (/^\s+-\s+/.test(line) && !/^\s+-\s+\[\[/.test(line)) {
4693
+ const value = line.replace(/^\s+-\s+/, "").trim().replace(/^['"]|['"]$/g, "");
4694
+ if (value.length > 0) tagItems.push(value);
4695
+ } else {
4696
+ break;
4697
+ }
4698
+ }
4699
+ }
4700
+ return tagItems;
4701
+ }
4702
+ function rebuildTagsSection(rawFm, existingTags, toAdd) {
4703
+ const allTags = [...existingTags, ...toAdd];
4704
+ const tagsLine = `tags: [${allTags.join(", ")}]`;
4705
+ if (/^tags:\s*\[/m.test(rawFm)) {
4706
+ return rawFm.replace(/^tags:\s*\[[^\]]*\]/m, tagsLine);
4707
+ }
4708
+ const lines = rawFm.split("\n");
4709
+ const out = [];
4710
+ let inTags = false;
4711
+ let tagsReplaced = false;
4712
+ for (const line of lines) {
4713
+ if (/^tags:\s*$/.test(line)) {
4714
+ inTags = true;
4715
+ if (!tagsReplaced) {
4716
+ out.push(tagsLine);
4717
+ tagsReplaced = true;
4718
+ }
4719
+ continue;
4720
+ }
4721
+ if (inTags) {
4722
+ if (/^\s+-\s+/.test(line) && !/^\s+-\s+\[\[/.test(line)) {
4723
+ continue;
4724
+ } else {
4725
+ inTags = false;
4726
+ }
4727
+ }
4728
+ out.push(line);
4729
+ }
4730
+ if (!tagsReplaced) {
4731
+ out.push(tagsLine);
4732
+ }
4733
+ return out.join("\n");
4734
+ }
4735
+ async function runTagSync(input) {
4736
+ const scan = await scanVault(input.vault);
4737
+ if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
4738
+ const synced = [];
4739
+ let unchanged = 0;
4740
+ for (const page of scan.data.typedKnowledge) {
4741
+ const text = await readPage(page);
4742
+ const split = splitFrontmatter(text);
4743
+ if (!split.ok) {
4744
+ unchanged++;
4745
+ continue;
4746
+ }
4747
+ const { rawFrontmatter, body } = split.data;
4748
+ const fm = {};
4749
+ for (const [field, allowedValues] of Object.entries(ENUM_MIRRORS)) {
4750
+ for (const v of allowedValues) {
4751
+ if (rawFrontmatter.includes(`${field}: ${v}`)) {
4752
+ fm[field] = v;
4753
+ break;
4754
+ }
4755
+ }
4756
+ }
4757
+ const expected = expectedNestedTags(fm);
4758
+ if (expected.size === 0) {
4759
+ unchanged++;
4760
+ continue;
4761
+ }
4762
+ const existingTags = parseTagsFromYaml(rawFrontmatter);
4763
+ const existingSet = new Set(existingTags);
4764
+ const toAdd = [...expected].filter((t) => !existingSet.has(t));
4765
+ if (toAdd.length === 0) {
4766
+ unchanged++;
4767
+ continue;
4768
+ }
4769
+ const newFm = rebuildTagsSection(rawFrontmatter, existingTags, toAdd);
4770
+ const newText = `---
4771
+ ${newFm}
4772
+ ---
4773
+ ${body}`;
4774
+ if (!input.dryRun) {
4775
+ await writeFile16(page.absPath, newText, "utf8");
4776
+ }
4777
+ synced.push(page.relPath);
4778
+ }
4779
+ if (!input.dryRun && synced.length > 0) {
4780
+ appendLastOp(input.vault, {
4781
+ operation: "tag-sync",
4782
+ summary: `synced tags on ${synced.length} pages`,
4783
+ files: synced,
4784
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4785
+ });
4786
+ }
4787
+ const exitCode = synced.length > 0 ? ExitCode.MIGRATION_APPLIED : ExitCode.OK;
4788
+ const hintLines = [`scanned: ${synced.length + unchanged}`];
4789
+ if (synced.length > 0) hintLines.push(`synced: ${synced.length}`);
4790
+ if (unchanged > 0) hintLines.push(`unchanged: ${unchanged}`);
4791
+ if (input.dryRun && synced.length > 0) hintLines.push("(dry run \u2014 no files written)");
4792
+ return {
4793
+ exitCode,
4794
+ result: ok({
4795
+ scanned: synced.length + unchanged,
4796
+ synced,
4797
+ unchanged,
4798
+ humanHint: hintLines.join("\n")
4799
+ })
4800
+ };
4801
+ }
4802
+
4803
+ // src/commands/sync.ts
4804
+ import { existsSync as existsSync9 } from "fs";
4805
+ import { join as join30 } from "path";
4806
+ function runSyncStatus(input) {
4807
+ const vault = input.vault;
4808
+ if (!existsSync9(join30(vault, ".git"))) {
4809
+ return {
4810
+ exitCode: ExitCode.VAULT_PATH_INVALID,
4811
+ result: ok({
4812
+ is_git_repo: false,
4813
+ dirty: 0,
4814
+ ahead: 0,
4815
+ behind: 0,
4816
+ last_commit: "never",
4817
+ status: "not_a_repo",
4818
+ humanHint: "not a git repository"
4819
+ })
4820
+ };
4821
+ }
4822
+ const porcelain = git(vault, ["status", "--porcelain"]);
4823
+ const dirty = porcelain ? porcelain.split("\n").filter((l) => l.trim().length > 0).length : 0;
4824
+ const revOutput = git(vault, ["rev-list", "--left-right", "--count", "origin/HEAD...HEAD"]);
4825
+ let ahead = 0;
4826
+ let behind = 0;
4827
+ if (revOutput) {
4828
+ const parts = revOutput.split(/\s+/);
4829
+ behind = parseInt(parts[0], 10) || 0;
4830
+ ahead = parseInt(parts[1], 10) || 0;
4831
+ }
4832
+ const tsRaw = git(vault, ["log", "-1", "--format=%ct"]);
4833
+ let last_commit;
4834
+ if (tsRaw) {
4835
+ const ts = parseInt(tsRaw, 10);
4836
+ if (!isNaN(ts) && ts > 0) {
4837
+ last_commit = new Date(ts * 1e3).toISOString();
4838
+ } else {
4839
+ last_commit = "never";
4840
+ }
4841
+ } else {
4842
+ last_commit = "never";
4843
+ }
4844
+ let status;
4845
+ if (dirty > 0) {
4846
+ status = "dirty";
4847
+ } else if (ahead > 0) {
4848
+ status = "ahead";
4849
+ } else if (behind > 0) {
4850
+ status = "behind";
4851
+ } else {
4852
+ status = "clean";
4853
+ }
4854
+ const hintLines = [
4855
+ `status: ${status}`,
4856
+ `dirty: ${dirty}`,
4857
+ `ahead: ${ahead}`,
4858
+ `behind: ${behind}`,
4859
+ `last_commit: ${last_commit}`
4860
+ ];
4861
+ const exitCode = status === "clean" ? ExitCode.OK : ExitCode.LINT_HAS_WARNINGS;
4862
+ return {
4863
+ exitCode,
4864
+ result: ok({
4865
+ is_git_repo: true,
4866
+ dirty,
4867
+ ahead,
4868
+ behind,
4869
+ last_commit,
4870
+ status,
4871
+ humanHint: hintLines.join("\n")
4872
+ })
4873
+ };
4874
+ }
4875
+ async function runSyncPush(input) {
4876
+ const vault = input.vault;
4877
+ if (!existsSync9(join30(vault, ".git"))) {
4878
+ return {
4879
+ exitCode: ExitCode.VAULT_PATH_INVALID,
4880
+ result: err("NOT_A_GIT_REPO", { path: vault })
4881
+ };
4882
+ }
4883
+ const porcelain = git(vault, ["status", "--porcelain"]);
4884
+ const dirtyFiles = porcelain ? porcelain.split("\n").filter((l) => l.trim().length > 0) : [];
4885
+ if (dirtyFiles.length === 0) {
4886
+ return {
4887
+ exitCode: ExitCode.OK,
4888
+ result: ok({
4889
+ files_committed: 0,
4890
+ commit_message: "",
4891
+ pushed: false,
4892
+ humanHint: "nothing to commit, working tree clean"
4893
+ })
4894
+ };
4895
+ }
4896
+ const lintResult = await runLint({ vault, days: 90, lines: 200, logThreshold: 500 });
4897
+ if (lintResult.result.ok && lintResult.result.data.summary.errors > 0) {
4898
+ return {
4899
+ exitCode: ExitCode.LINT_HAS_ERRORS,
4900
+ result: err("LINT_ERRORS_BLOCK_PUSH", {
4901
+ errors: lintResult.result.data.summary.errors,
4902
+ buckets: lintResult.result.data.by_severity.error
4903
+ })
4904
+ };
4905
+ }
4906
+ try {
4907
+ gitStrict(vault, ["add", "-A"]);
4908
+ try {
4909
+ gitStrict(vault, ["reset", "HEAD", "--", ".skillwiki/last-op.json"]);
4910
+ } catch {
4911
+ }
4912
+ } catch (e) {
4913
+ return {
4914
+ exitCode: ExitCode.SYNC_PUSH_FAILED,
4915
+ result: err("GIT_ADD_FAILED", { message: String(e) })
4916
+ };
4917
+ }
4918
+ const lastOps = readLastOp(vault);
4919
+ let commitMessage;
4920
+ if (lastOps.length > 0) {
4921
+ commitMessage = lastOps.map((op) => `${op.operation}: ${op.summary} (${op.files.length} files)`).join("; ");
4922
+ } else {
4923
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z");
4924
+ commitMessage = `sync: vault update ${timestamp}`;
4925
+ }
4926
+ try {
4927
+ gitStrict(vault, ["commit", "-m", commitMessage]);
4928
+ } catch (e) {
4929
+ return {
4930
+ exitCode: ExitCode.SYNC_PUSH_FAILED,
4931
+ result: err("GIT_COMMIT_FAILED", { message: String(e) })
4932
+ };
4933
+ }
4934
+ clearLastOp(vault);
4935
+ let pushed = false;
4936
+ try {
4937
+ gitStrict(vault, ["push", "origin", "HEAD"]);
4938
+ pushed = true;
4939
+ } catch (e) {
4940
+ return {
4941
+ exitCode: ExitCode.SYNC_PUSH_FAILED,
4942
+ result: ok({
4943
+ files_committed: dirtyFiles.length,
4944
+ commit_message: commitMessage,
4945
+ pushed: false,
4946
+ humanHint: `committed ${dirtyFiles.length} file(s) but push failed: ${String(e)}`
4947
+ })
4948
+ };
4949
+ }
4950
+ return {
4951
+ exitCode: ExitCode.OK,
4952
+ result: ok({
4953
+ files_committed: dirtyFiles.length,
4954
+ commit_message: commitMessage,
4955
+ pushed,
4956
+ humanHint: `committed and pushed ${dirtyFiles.length} file(s)`
4957
+ })
4958
+ };
4959
+ }
4960
+ async function runSyncPull(input) {
4961
+ const vault = input.vault;
4962
+ if (!existsSync9(join30(vault, ".git"))) {
4963
+ return {
4964
+ exitCode: ExitCode.VAULT_PATH_INVALID,
4965
+ result: err("NOT_A_GIT_REPO", { path: vault })
4966
+ };
4967
+ }
4968
+ let fetched = false;
4969
+ try {
4970
+ gitStrict(vault, ["fetch", "origin"]);
4971
+ fetched = true;
4972
+ } catch (e) {
4973
+ return {
4974
+ exitCode: ExitCode.SYNC_PULL_FAILED,
4975
+ result: err("GIT_FETCH_FAILED", { message: String(e) })
4976
+ };
4977
+ }
4978
+ let pulled = false;
4979
+ let conflicts = 0;
4980
+ let filesUpdated = 0;
4981
+ try {
4982
+ const pullOutput = gitStrict(vault, ["pull", "--rebase", "origin", "HEAD"]);
4983
+ pulled = true;
4984
+ const fileMatch = pullOutput.match(/(\d+) file[s]? changed/);
4985
+ if (fileMatch) filesUpdated = parseInt(fileMatch[1], 10);
4986
+ } catch (e) {
4987
+ const errString = String(e);
4988
+ if (errString.includes("conflict")) {
4989
+ const porcelain = git(vault, ["diff", "--name-only", "--diff-filter=U"]);
4990
+ conflicts = porcelain ? porcelain.split("\n").filter((l) => l.trim().length > 0).length : 0;
4991
+ return {
4992
+ exitCode: ExitCode.SYNC_PULL_FAILED,
4993
+ result: ok({
4994
+ fetched,
4995
+ pulled: false,
4996
+ files_updated: 0,
4997
+ conflicts,
4998
+ lint_errors: 0,
4999
+ lint_warnings: 0,
5000
+ humanHint: `pull failed with ${conflicts} conflict(s) \u2014 resolve manually`
5001
+ })
5002
+ };
5003
+ }
5004
+ return {
5005
+ exitCode: ExitCode.SYNC_PULL_FAILED,
5006
+ result: err("GIT_PULL_FAILED", { message: errString })
5007
+ };
5008
+ }
5009
+ let lintErrors = 0;
5010
+ let lintWarnings = 0;
5011
+ const lintResult = await runLint({ vault, days: 90, lines: 200, logThreshold: 500 });
5012
+ if (lintResult.result.ok) {
5013
+ lintErrors = lintResult.result.data.summary.errors;
5014
+ lintWarnings = lintResult.result.data.summary.warnings;
5015
+ }
5016
+ const hintParts = [];
5017
+ if (filesUpdated > 0) hintParts.push(`updated ${filesUpdated} file(s)`);
5018
+ else hintParts.push("already up to date");
5019
+ if (lintErrors > 0) hintParts.push(`${lintErrors} lint error(s)`);
5020
+ if (lintWarnings > 0) hintParts.push(`${lintWarnings} lint warning(s)`);
5021
+ const exitCode = lintErrors > 0 ? ExitCode.LINT_HAS_ERRORS : lintWarnings > 0 ? ExitCode.LINT_HAS_WARNINGS : ExitCode.OK;
5022
+ return {
5023
+ exitCode,
5024
+ result: ok({
5025
+ fetched,
5026
+ pulled,
5027
+ files_updated: filesUpdated,
5028
+ conflicts,
5029
+ lint_errors: lintErrors,
5030
+ lint_warnings: lintWarnings,
5031
+ humanHint: hintParts.join(", ")
5032
+ })
5033
+ };
5034
+ }
5035
+
5036
+ // src/commands/backup.ts
5037
+ import { statSync as statSync3, readdirSync as readdirSync2, readFileSync as readFileSync8, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
5038
+ import { join as join31, relative as relative3, dirname as dirname11 } from "path";
5039
+ import { PutObjectCommand, HeadObjectCommand, ListObjectsV2Command, GetObjectCommand, DeleteObjectsCommand } from "@aws-sdk/client-s3";
5040
+
5041
+ // src/utils/s3-client.ts
5042
+ import { S3Client } from "@aws-sdk/client-s3";
5043
+ function createS3Client(config) {
5044
+ const clientConfig = {
5045
+ endpoint: config.endpoint,
5046
+ region: config.region,
5047
+ credentials: {
5048
+ accessKeyId: config.accessKeyId,
5049
+ secretAccessKey: config.secretAccessKey
5050
+ },
5051
+ forcePathStyle: true
5052
+ // Required for SeaweedFS / MinIO
5053
+ };
5054
+ return new S3Client(clientConfig);
5055
+ }
5056
+
5057
+ // src/commands/backup.ts
5058
+ var SKIP_DIRS = /* @__PURE__ */ new Set([".git", ".obsidian", "_archive", "node_modules", ".skillwiki"]);
5059
+ function* walkMarkdown(dir, base) {
5060
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
5061
+ if (SKIP_DIRS.has(entry.name)) continue;
5062
+ const full = join31(dir, entry.name);
5063
+ if (entry.isDirectory()) {
5064
+ yield* walkMarkdown(full, base);
5065
+ } else if (entry.name.endsWith(".md")) {
5066
+ yield relative3(base, full).replace(/\\/g, "/");
5067
+ }
5068
+ }
5069
+ }
5070
+ async function runBackupSync(input) {
5071
+ if (!input.accessKeyId || !input.secretAccessKey) {
5072
+ return {
5073
+ exitCode: ExitCode.BACKUP_SYNC_FAILED,
5074
+ result: err("BACKUP_SYNC_FAILED", {
5075
+ message: "Backup credentials not configured. Run: skillwiki config set BACKUP_ACCESS_KEY_ID <key>"
5076
+ })
5077
+ };
5078
+ }
5079
+ const client = createS3Client(input);
5080
+ let uploaded = 0;
5081
+ let skipped = 0;
5082
+ let failed = 0;
5083
+ const files = [...walkMarkdown(input.vault, input.vault)];
5084
+ for (const relPath of files) {
5085
+ const absPath = join31(input.vault, relPath);
5086
+ const localStat = statSync3(absPath);
5087
+ let needsUpload = true;
5088
+ try {
5089
+ const head = await client.send(new HeadObjectCommand({ Bucket: input.bucket, Key: relPath }));
5090
+ if (head.LastModified && head.LastModified >= localStat.mtime) {
5091
+ needsUpload = false;
5092
+ }
5093
+ } catch {
5094
+ }
5095
+ if (!needsUpload) {
5096
+ skipped++;
5097
+ continue;
5098
+ }
5099
+ if (input.dryRun) {
5100
+ uploaded++;
5101
+ continue;
5102
+ }
5103
+ try {
5104
+ const body = readFileSync8(absPath);
5105
+ await client.send(new PutObjectCommand({ Bucket: input.bucket, Key: relPath, Body: body }));
5106
+ uploaded++;
5107
+ } catch {
5108
+ failed++;
5109
+ }
5110
+ }
5111
+ let pruned = 0;
5112
+ if (input.prune && !input.dryRun) {
5113
+ try {
5114
+ const localSet = new Set(files);
5115
+ const list = await client.send(new ListObjectsV2Command({ Bucket: input.bucket }));
5116
+ const toDelete = (list.Contents ?? []).filter((obj) => obj.Key && !localSet.has(obj.Key)).map((obj) => ({ Key: obj.Key }));
5117
+ if (toDelete.length > 0) {
5118
+ await client.send(new DeleteObjectsCommand({ Bucket: input.bucket, Delete: { Objects: toDelete } }));
5119
+ pruned = toDelete.length;
5120
+ }
5121
+ } catch {
5122
+ }
5123
+ }
5124
+ const hintParts = [];
5125
+ if (input.dryRun) hintParts.push("DRY RUN \u2014");
5126
+ hintParts.push(`scanned: ${files.length}, uploaded: ${uploaded}, skipped: ${skipped}`);
5127
+ if (failed > 0) hintParts.push(`failed: ${failed}`);
5128
+ if (pruned > 0) hintParts.push(`pruned: ${pruned}`);
5129
+ return {
5130
+ exitCode: failed > 0 ? ExitCode.BACKUP_SYNC_FAILED : ExitCode.OK,
5131
+ result: ok({
5132
+ scanned: files.length,
5133
+ uploaded,
5134
+ skipped,
5135
+ failed,
5136
+ pruned,
5137
+ dry_run: input.dryRun ?? false,
5138
+ humanHint: hintParts.join(", ")
5139
+ })
5140
+ };
5141
+ }
5142
+ async function runBackupRestore(input) {
5143
+ if (!input.accessKeyId || !input.secretAccessKey) {
5144
+ return {
5145
+ exitCode: ExitCode.BACKUP_SYNC_FAILED,
5146
+ result: err("BACKUP_SYNC_FAILED", {
5147
+ message: "Backup credentials not configured. Run: skillwiki config set BACKUP_ACCESS_KEY_ID <key>"
5148
+ })
5149
+ };
5150
+ }
5151
+ const client = createS3Client(input);
5152
+ const target = input.target ?? input.vault;
5153
+ let downloaded = 0;
5154
+ let skipped = 0;
5155
+ let conflicts = 0;
5156
+ try {
5157
+ const list = await client.send(new ListObjectsV2Command({ Bucket: input.bucket }));
5158
+ const objects = list.Contents ?? [];
5159
+ for (const obj of objects) {
5160
+ if (!obj.Key) continue;
5161
+ const localPath = join31(target, obj.Key);
5162
+ try {
5163
+ const localStat = statSync3(localPath);
5164
+ if (obj.LastModified && localStat.mtime > obj.LastModified) {
5165
+ conflicts++;
5166
+ continue;
5167
+ }
5168
+ } catch {
5169
+ }
5170
+ try {
5171
+ const resp = await client.send(new GetObjectCommand({ Bucket: input.bucket, Key: obj.Key }));
5172
+ const body = await resp.Body?.transformToByteArray();
5173
+ if (body) {
5174
+ mkdirSync3(dirname11(localPath), { recursive: true });
5175
+ writeFileSync4(localPath, Buffer.from(body));
5176
+ downloaded++;
5177
+ }
5178
+ } catch {
5179
+ skipped++;
5180
+ }
5181
+ }
5182
+ } catch (e) {
5183
+ return {
5184
+ exitCode: ExitCode.BACKUP_SYNC_FAILED,
5185
+ result: err("BACKUP_SYNC_FAILED", { message: `Failed to list bucket: ${String(e)}` })
5186
+ };
5187
+ }
5188
+ const hintParts = [`downloaded: ${downloaded}`];
5189
+ if (skipped > 0) hintParts.push(`skipped: ${skipped}`);
5190
+ if (conflicts > 0) hintParts.push(`conflicts: ${conflicts} (local is newer)`);
5191
+ if (downloaded > 0) {
5192
+ appendLastOp(target, {
5193
+ operation: "backup-restore",
5194
+ summary: `restored ${downloaded} files from S3`,
5195
+ files: [],
5196
+ // Don't enumerate potentially hundreds of files
5197
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
5198
+ });
5199
+ }
5200
+ return {
5201
+ exitCode: conflicts > 0 ? ExitCode.BACKUP_RESTORE_CONFLICTS : ExitCode.OK,
5202
+ result: ok({ downloaded, skipped, conflicts, humanHint: hintParts.join(", ") })
5203
+ };
5204
+ }
5205
+
5206
+ // src/commands/status.ts
5207
+ import { existsSync as existsSync10, statSync as statSync4 } from "fs";
5208
+ import { readFile as readFile20 } from "fs/promises";
5209
+ import { join as join32 } from "path";
5210
+ async function runStatus(input) {
5211
+ if (!existsSync10(input.vault)) {
5212
+ return { exitCode: ExitCode.VAULT_PATH_INVALID, result: err("VAULT_PATH_INVALID", { vault: input.vault }) };
5213
+ }
5214
+ const scan = await scanVault(input.vault);
5215
+ if (!scan.ok) {
5216
+ return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
5217
+ }
5218
+ const typedCounts = { entities: 0, concepts: 0, comparisons: 0, queries: 0, meta: 0 };
5219
+ for (const page of scan.data.typedKnowledge) {
5220
+ const segment = page.relPath.split("/")[0];
5221
+ if (segment in typedCounts) {
5222
+ typedCounts[segment]++;
5223
+ }
5224
+ }
5225
+ let rawArticles = 0;
5226
+ let rawTranscripts = 0;
5227
+ for (const page of scan.data.raw) {
5228
+ const parts = page.relPath.split("/");
5229
+ if (parts[1] === "transcripts") rawTranscripts++;
5230
+ else rawArticles++;
5231
+ }
5232
+ const workItems = scan.data.workItems.length;
5233
+ const compound = scan.data.compound.length;
5234
+ let schemaVersion = "v1";
5235
+ try {
5236
+ const schemaContent = await readFile20(join32(input.vault, "SCHEMA.md"), "utf8");
5237
+ const versionMatch = schemaContent.match(/version:\s*["']?([^"'\s\n]+)/i);
5238
+ if (versionMatch) schemaVersion = versionMatch[1];
5239
+ } catch {
5240
+ }
5241
+ const langResult = await resolveLang({ flag: void 0, envValue: input.langEnvValue, home: input.home });
5242
+ const allPages = [
5243
+ ...scan.data.typedKnowledge,
5244
+ ...scan.data.raw,
5245
+ ...scan.data.workItems,
5246
+ ...scan.data.compound
5247
+ ];
5248
+ let lastModified = "";
5249
+ let maxTime = 0;
5250
+ for (const page of allPages) {
5251
+ try {
5252
+ const st = statSync4(page.absPath);
5253
+ if (st.mtimeMs > maxTime) {
5254
+ maxTime = st.mtimeMs;
5255
+ lastModified = st.mtime.toISOString();
5256
+ }
5257
+ } catch {
5258
+ }
5259
+ }
5260
+ const pageCounts = {
5261
+ entities: typedCounts.entities,
5262
+ concepts: typedCounts.concepts,
5263
+ comparisons: typedCounts.comparisons,
5264
+ queries: typedCounts.queries,
5265
+ meta: typedCounts.meta,
5266
+ raw_articles: rawArticles,
5267
+ raw_transcripts: rawTranscripts,
5268
+ work_items: workItems,
5269
+ compound
5270
+ };
5271
+ const totalPages = Object.values(pageCounts).reduce((a, b) => a + b, 0);
5272
+ const rawTotal = rawArticles + rawTranscripts;
5273
+ const humanHint = [
5274
+ `vault: ${input.vault}`,
5275
+ `lang: ${langResult.value}`,
5276
+ `total: ${totalPages} pages`,
5277
+ ` entities: ${pageCounts.entities} concepts: ${pageCounts.concepts} comparisons: ${pageCounts.comparisons} queries: ${pageCounts.queries} meta: ${pageCounts.meta}`,
5278
+ ` raw: ${rawTotal} work_items: ${workItems} compound: ${compound}`,
5279
+ `last modified: ${lastModified.slice(0, 10)}`
5280
+ ].join("\n");
5281
+ return {
5282
+ exitCode: ExitCode.OK,
5283
+ result: ok({
5284
+ vault_path: input.vault,
5285
+ schema_version: schemaVersion,
5286
+ lang: langResult.canonical,
5287
+ page_counts: pageCounts,
5288
+ total_pages: totalPages,
5289
+ last_modified: lastModified,
5290
+ humanHint
5291
+ })
5292
+ };
5293
+ }
5294
+
5295
+ // src/commands/seed.ts
5296
+ import { mkdir as mkdir12, writeFile as writeFile17, stat as stat7 } from "fs/promises";
5297
+ import { join as join33 } from "path";
5298
+ var TODAY = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
5299
+ var EXAMPLE_PAGES = {
5300
+ "entities/example-project.md": `---
5301
+ title: Example Project
5302
+ aliases: [example-project]
5303
+ created: ${TODAY}
5304
+ updated: ${TODAY}
5305
+ type: entity
5306
+ tags: [research]
5307
+ sources: []
5308
+ confidence: medium
5309
+ provenance: research
5310
+ ---
5311
+
5312
+ # Example Project
5313
+
5314
+ ## Overview
5315
+
5316
+ This is a seed entity page demonstrating the typed-knowledge format. Replace it with a real entity from your research.
5317
+
5318
+ ## Key Facts
5319
+
5320
+ - This vault was seeded on ${TODAY}
5321
+ - Entity pages describe people, organizations, products, or projects
5322
+ - Each page should cite sources from the \`raw/\` directory
5323
+ `,
5324
+ "concepts/example-concept.md": `---
5325
+ title: Example Concept
5326
+ aliases: [example-concept]
5327
+ created: ${TODAY}
5328
+ updated: ${TODAY}
5329
+ type: concept
5330
+ tags: [concept]
5331
+ sources: []
5332
+ confidence: medium
5333
+ provenance: research
5334
+ ---
5335
+
5336
+ # Example Concept
5337
+
5338
+ ## Overview
5339
+
5340
+ This is a seed concept page. Concept pages capture topics, patterns, and ideas that span multiple sources.
5341
+
5342
+ ## Related
5343
+
5344
+ - [[example-project]]
5345
+
5346
+ ## Sources
5347
+
5348
+ (Add source citations here after ingesting raw material with \`wiki-ingest\`)
5349
+ `
5350
+ };
5351
+ var EXAMPLE_RAW = `---
5352
+ source_url: https://example.com
5353
+ ingested: ${TODAY}
5354
+ sha256: 0000000000000000000000000000000000000000000000000000000000000000
5355
+ ---
5356
+
5357
+ # Example Source Article
5358
+
5359
+ This is a placeholder raw source. Replace it with real content ingested via \`skillwiki hash\` and the wiki-ingest skill.
5360
+
5361
+ Real sources are immutable after ingestion \u2014 never edit them.
5362
+ `;
5363
+ async function runSeed(input) {
5364
+ try {
5365
+ await stat7(join33(input.vault, "SCHEMA.md"));
5366
+ } catch {
5367
+ return { exitCode: ExitCode.VAULT_PATH_INVALID, result: err("VAULT_PATH_INVALID", { root: input.vault, reason: "SCHEMA.md missing \u2014 run `skillwiki init` first" }) };
5368
+ }
5369
+ const created = [];
5370
+ const skipped = [];
5371
+ for (const [relPath, content] of Object.entries(EXAMPLE_PAGES)) {
5372
+ const absPath = join33(input.vault, relPath);
5373
+ try {
5374
+ await stat7(absPath);
5375
+ skipped.push(relPath);
5376
+ } catch {
5377
+ await mkdir12(join33(absPath, ".."), { recursive: true });
5378
+ await writeFile17(absPath, content, "utf8");
5379
+ created.push(relPath);
5380
+ }
5381
+ }
5382
+ const rawPath = join33(input.vault, "raw", "articles", "example-source.md");
5383
+ try {
5384
+ await stat7(rawPath);
5385
+ skipped.push("raw/articles/example-source.md");
5386
+ } catch {
5387
+ await mkdir12(join33(rawPath, ".."), { recursive: true });
5388
+ await writeFile17(rawPath, EXAMPLE_RAW, "utf8");
5389
+ created.push("raw/articles/example-source.md");
5390
+ }
5391
+ if (created.length > 0) {
5392
+ appendLastOp(input.vault, {
5393
+ operation: "seed",
5394
+ summary: `seeded ${created.length} example pages`,
5395
+ files: created,
5396
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
5397
+ });
5398
+ }
5399
+ const hintLines = [`seeded: ${created.length}`, `skipped (already exist): ${skipped.length}`];
5400
+ if (created.length > 0) {
5401
+ hintLines.push("next steps: ingest real sources with wiki-ingest, then cite them in concept/entity pages");
5402
+ }
5403
+ return {
5404
+ exitCode: ExitCode.OK,
5405
+ result: ok({ created, skipped, humanHint: hintLines.join("\n") })
5406
+ };
5407
+ }
5408
+
5409
+ // src/commands/canvas.ts
5410
+ import { readFile as readFile21, writeFile as writeFile18 } from "fs/promises";
5411
+ import { existsSync as existsSync11 } from "fs";
5412
+ import { join as join34 } from "path";
5413
+ var NODE_WIDTH = 240;
5414
+ var NODE_HEIGHT = 60;
5415
+ var COLUMN_SPACING = 400;
5416
+ var ROW_SPACING = 80;
5417
+ var TYPE_COLUMNS = {
5418
+ entities: 0,
5419
+ concepts: 1,
5420
+ comparisons: 2,
5421
+ queries: 3,
5422
+ meta: 3
5423
+ };
5424
+ var TYPE_COLORS = {
5425
+ entities: "1",
5426
+ // red
5427
+ concepts: "4",
5428
+ // green
5429
+ comparisons: "2",
5430
+ // orange
5431
+ queries: "5",
5432
+ // cyan
5433
+ meta: "6"
5434
+ // purple
5435
+ };
5436
+ var DEFAULT_COLOR = "3";
5437
+ var DEFAULT_COLUMN = 2;
5438
+ function inferNodeType(relPath) {
5439
+ const segment = relPath.split("/")[0] ?? "";
5440
+ return TYPE_COLUMNS[segment] !== void 0 ? segment : "";
5441
+ }
5442
+ function getColumnForType(nodeType) {
5443
+ return TYPE_COLUMNS[nodeType] ?? DEFAULT_COLUMN;
5444
+ }
5445
+ function getColorForType(nodeType) {
5446
+ return TYPE_COLORS[nodeType] ?? DEFAULT_COLOR;
5447
+ }
5448
+ function buildCanvasNodes(paths) {
5449
+ const columnY = {};
5450
+ const nodes = [];
5451
+ for (const relPath of paths) {
5452
+ const nodeType = inferNodeType(relPath);
5453
+ const col = getColumnForType(nodeType);
5454
+ const y = columnY[col] ?? 0;
5455
+ columnY[col] = y + ROW_SPACING;
5456
+ nodes.push({
5457
+ id: relPath,
5458
+ type: "file",
5459
+ file: relPath,
5460
+ x: col * COLUMN_SPACING,
5461
+ y,
5462
+ width: NODE_WIDTH,
5463
+ height: NODE_HEIGHT,
5464
+ color: getColorForType(nodeType)
5465
+ });
5466
+ }
5467
+ return nodes;
5468
+ }
5469
+ function buildCanvasEdges(adjacency) {
5470
+ const edges = [];
5471
+ let edgeIndex = 0;
5472
+ const seen = /* @__PURE__ */ new Set();
5473
+ for (const [source, targets] of Object.entries(adjacency)) {
5474
+ for (const target of targets) {
5475
+ const key = `${source}->${target}`;
5476
+ if (seen.has(key)) continue;
5477
+ seen.add(key);
5478
+ edges.push({
5479
+ id: `edge-${edgeIndex++}`,
5480
+ fromNode: source,
5481
+ toNode: target,
5482
+ fromSide: "right",
5483
+ toSide: "left"
5484
+ });
5485
+ }
5486
+ }
5487
+ return edges;
5488
+ }
5489
+ async function runCanvasGenerate(input) {
5490
+ const graphPath = input.graphPath ?? join34(input.vault, ".skillwiki", "graph.json");
5491
+ if (!existsSync11(graphPath)) {
5492
+ return {
5493
+ exitCode: ExitCode.FILE_NOT_FOUND,
5494
+ result: err("FILE_NOT_FOUND", {
5495
+ path: graphPath,
5496
+ hint: "Run `skillwiki graph build` first to generate graph.json"
5497
+ })
5498
+ };
5499
+ }
5500
+ let raw;
5501
+ try {
5502
+ raw = await readFile21(graphPath, "utf8");
5503
+ } catch (e) {
5504
+ return {
5505
+ exitCode: ExitCode.FILE_NOT_FOUND,
5506
+ result: err("FILE_NOT_FOUND", { path: graphPath, message: String(e) })
5507
+ };
5508
+ }
5509
+ let graph;
5510
+ try {
5511
+ graph = JSON.parse(raw);
5512
+ } catch {
5513
+ return {
5514
+ exitCode: ExitCode.SCHEMA_NOT_DETECTED,
5515
+ result: err("SCHEMA_NOT_DETECTED", { path: graphPath, reason: "Invalid JSON in graph.json" })
5516
+ };
5517
+ }
5518
+ if (!graph.adjacency || typeof graph.adjacency !== "object") {
5519
+ return {
5520
+ exitCode: ExitCode.SCHEMA_NOT_DETECTED,
5521
+ result: err("SCHEMA_NOT_DETECTED", { path: graphPath, reason: "graph.json missing adjacency field" })
5522
+ };
5523
+ }
5524
+ const paths = Object.keys(graph.adjacency);
5525
+ const nodes = buildCanvasNodes(paths);
5526
+ const edges = buildCanvasEdges(graph.adjacency);
5527
+ const canvas = { nodes, edges };
5528
+ const outPath = join34(input.vault, "vault-graph.canvas");
5529
+ try {
5530
+ await writeFile18(outPath, JSON.stringify(canvas, null, 2));
5531
+ } catch (e) {
5532
+ return {
5533
+ exitCode: ExitCode.WRITE_FAILED,
5534
+ result: err("WRITE_FAILED", { message: String(e), path: outPath })
5535
+ };
5536
+ }
5537
+ return {
5538
+ exitCode: ExitCode.OK,
5539
+ result: ok({
5540
+ out_path: outPath,
5541
+ node_count: nodes.length,
5542
+ edge_count: edges.length,
5543
+ humanHint: `nodes: ${nodes.length}, edges: ${edges.length}
5544
+ written: ${outPath}`
5545
+ })
5546
+ };
5547
+ }
5548
+
5549
+ // src/commands/query.ts
5550
+ import { readFile as readFile22, stat as stat8 } from "fs/promises";
5551
+ import { join as join35 } from "path";
5552
+ var W_KEYWORD = 2;
5553
+ var W_SOURCE_OVERLAP = 4;
5554
+ var W_WIKILINK = 3;
5555
+ var W_ADAMIC_ADAR = 1.5;
5556
+ var W_TYPE_AFFINITY = 1;
5557
+ var NON_SEED_FACTOR = 0.4;
5558
+ var CONCEPT_INDICATORS = /* @__PURE__ */ new Set([
5559
+ "what",
5560
+ "how",
5561
+ "why",
5562
+ "concept",
5563
+ "idea",
5564
+ "pattern",
5565
+ "principle",
5566
+ "theory",
5567
+ "approach",
5568
+ "method",
5569
+ "framework",
5570
+ "model",
5571
+ "definition"
5572
+ ]);
5573
+ async function runQuery(input) {
5574
+ const scan = await scanVault(input.vault);
5575
+ if (!scan.ok) return { exitCode: ExitCode.VAULT_PATH_INVALID, result: scan };
5576
+ const limit = input.limit ?? 10;
5577
+ const queryTerms = tokenize(input.text);
5578
+ if (queryTerms.length === 0) {
5579
+ return {
5580
+ exitCode: ExitCode.OK,
5581
+ result: ok({ results: [], humanHint: "no query terms" })
5582
+ };
5583
+ }
5584
+ const graph = await loadOrBuildGraph(input.vault);
5585
+ const pages = [];
5586
+ for (const p of scan.data.typedKnowledge) {
5587
+ const text = await readPage(p);
5588
+ const fm = extractFrontmatter(text);
5589
+ if (!fm.ok) continue;
5590
+ const title = String(fm.data.title ?? "");
5591
+ const type = String(fm.data.type ?? "");
5592
+ const tags = Array.isArray(fm.data.tags) ? fm.data.tags.map(String) : [];
5593
+ const sources = Array.isArray(fm.data.sources) ? fm.data.sources.map(String) : [];
5594
+ const split = splitFrontmatter(text);
5595
+ const body = split.ok ? split.data.body : text;
5596
+ const keywordScore = computeKeywordScore(queryTerms, title, tags, body);
5597
+ pages.push({ relPath: p.relPath, title, type, tags, sources, keywordScore });
5598
+ }
5599
+ const seedPaths = new Set(
5600
+ pages.filter((p) => p.keywordScore > 0).map((p) => p.relPath)
5601
+ );
5602
+ const results = pages.map((page) => {
5603
+ const sourceOverlap = scoreSourceOverlap(page, pages, seedPaths);
5604
+ const wikilink2 = scoreWikilink(page.relPath, seedPaths, graph);
5605
+ const aa = scoreAdamicAdar(page.relPath, seedPaths, graph);
5606
+ const typeAffinity = scoreTypeAffinity(page.type, queryTerms);
5607
+ const isSeed = page.keywordScore > 0;
5608
+ const structuralBoost = sourceOverlap * W_SOURCE_OVERLAP + wikilink2 * W_WIKILINK + aa * W_ADAMIC_ADAR;
5609
+ const composite = isSeed ? page.keywordScore * W_KEYWORD + structuralBoost + typeAffinity * W_TYPE_AFFINITY : structuralBoost * NON_SEED_FACTOR + typeAffinity * W_TYPE_AFFINITY;
5610
+ return {
5611
+ path: page.relPath,
5612
+ score: Math.round(composite * 1e3) / 1e3,
5613
+ title: page.title,
5614
+ type: page.type
5615
+ };
5616
+ }).filter((r) => r.score > 0).sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, limit);
5617
+ const humanHint = results.length === 0 ? "no matching pages found" : results.map((r) => `${r.path} (score: ${r.score})`).join("\n");
5618
+ return { exitCode: ExitCode.OK, result: ok({ results, humanHint }) };
5619
+ }
5620
+ function scoreSourceOverlap(page, allPages, seedPaths) {
5621
+ if (page.sources.length === 0) return 0;
5622
+ let total = 0;
5623
+ for (const seed of allPages) {
5624
+ if (seed.relPath === page.relPath || !seedPaths.has(seed.relPath)) continue;
5625
+ const shared = page.sources.filter((s) => seed.sources.includes(s)).length;
5626
+ total += shared;
5627
+ }
5628
+ return total;
5629
+ }
5630
+ function scoreWikilink(candidatePath, seedPaths, graph) {
5631
+ if (!graph) return 0;
5632
+ let count = 0;
5633
+ for (const seedPath of seedPaths) {
5634
+ const neighbors = graph.adjacency[seedPath];
5635
+ if (neighbors && neighbors.includes(candidatePath)) count++;
5636
+ }
5637
+ return count;
5638
+ }
5639
+ function scoreAdamicAdar(candidatePath, seedPaths, graph) {
5640
+ if (!graph) return 0;
5641
+ let maxScore = 0;
5642
+ const aaForCandidate = graph.adamicAdar[candidatePath];
5643
+ if (!aaForCandidate) return 0;
5644
+ for (const seedPath of seedPaths) {
5645
+ const val = aaForCandidate[seedPath];
5646
+ if (val !== void 0 && val > maxScore) maxScore = val;
5647
+ }
5648
+ return maxScore;
5649
+ }
5650
+ function scoreTypeAffinity(pageType, queryTerms) {
5651
+ const hasConceptIntent = queryTerms.some((t) => CONCEPT_INDICATORS.has(t));
5652
+ if (hasConceptIntent && pageType === "concept") return 1;
5653
+ if (!hasConceptIntent && pageType === "entity") return 0.5;
5654
+ return 0;
5655
+ }
5656
+ function tokenize(text) {
5657
+ return text.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
5658
+ }
5659
+ function computeKeywordScore(terms, title, tags, body) {
5660
+ const lowerTitle = title.toLowerCase();
5661
+ const lowerTags = tags.map((t) => t.toLowerCase());
5662
+ const lowerBody = body.toLowerCase();
5663
+ let score = 0;
5664
+ for (const term of terms) {
5665
+ if (lowerTitle.includes(term)) score += 3;
5666
+ if (lowerTags.some((t) => t.includes(term))) score += 2;
5667
+ if (lowerBody.includes(term)) score += 1;
5668
+ }
5669
+ return score;
5670
+ }
5671
+ async function loadOrBuildGraph(vault) {
5672
+ const graphPath = join35(vault, ".skillwiki", "graph.json");
5673
+ let needsBuild = false;
5674
+ try {
5675
+ const fileStat = await stat8(graphPath);
5676
+ const ageHours = (Date.now() - fileStat.mtimeMs) / (1e3 * 60 * 60);
5677
+ if (ageHours > 24) needsBuild = true;
5678
+ } catch {
5679
+ needsBuild = true;
5680
+ }
5681
+ if (needsBuild) {
5682
+ const buildResult = await runGraphBuild({ vault, out: graphPath });
5683
+ if (buildResult.exitCode !== 0) return null;
5684
+ }
5685
+ try {
5686
+ const raw = await readFile22(graphPath, "utf8");
5687
+ return JSON.parse(raw);
5688
+ } catch {
5689
+ return null;
5690
+ }
5691
+ }
5692
+
5693
+ // src/utils/auto-commit.ts
5694
+ import { existsSync as existsSync12 } from "fs";
5695
+ import { join as join36 } from "path";
5696
+ async function postCommit(vault, exitCode) {
5697
+ if (exitCode !== 0) return;
5698
+ const home = process.env.HOME ?? "";
5699
+ const dotenv = await parseDotenvFile(configPath(home));
5700
+ if (dotenv["AUTO_COMMIT"] === "false") return;
5701
+ if (!existsSync12(join36(vault, ".git"))) return;
5702
+ const lastOps = readLastOp(vault);
5703
+ if (lastOps.length === 0) return;
5704
+ const porcelain = git(vault, ["status", "--porcelain"]);
5705
+ if (!porcelain || porcelain.trim().length === 0) return;
5706
+ const { gitStrict: gitStrict2 } = await import("./git-M4WGJ5G3.js");
5707
+ try {
5708
+ gitStrict2(vault, ["add", "-A"]);
5709
+ try {
5710
+ gitStrict2(vault, ["reset", "HEAD", "--", ".skillwiki/last-op.json"]);
5711
+ } catch {
5712
+ }
5713
+ } catch (e) {
5714
+ process.stderr.write(`auto-commit: git add failed: ${String(e)}
5715
+ `);
5716
+ return;
5717
+ }
5718
+ const commitMessage = lastOps.map((op) => `${op.operation}: ${op.summary} (${op.files.length} files)`).join("; ");
5719
+ try {
5720
+ gitStrict2(vault, ["commit", "-m", commitMessage]);
5721
+ } catch (e) {
5722
+ process.stderr.write(`auto-commit: git commit failed: ${String(e)}
5723
+ `);
5724
+ return;
5725
+ }
5726
+ clearLastOp(vault);
5727
+ }
5728
+
5729
+ // src/cli.ts
5730
+ var pkg = JSON.parse(readFileSync9(new URL("../package.json", import.meta.url), "utf8"));
5731
+ var program = new Command();
5732
+ program.name("skillwiki").description("Deterministic helpers for CodeWiki skills").version(pkg.version);
5733
+ program.option("--human", "render terminal-readable output instead of JSON");
5734
+ async function emit(r, vault) {
5735
+ if (program.opts().human) printHuman(r.result);
5736
+ else printJson(r.result);
5737
+ if (vault) await postCommit(vault, r.exitCode);
5738
+ process.exit(r.exitCode);
5739
+ }
5740
+ program.command("hash <file>").description("compute SHA-256 hash of a vault page body").action(async (file) => emit(await runHash({ file })));
5741
+ program.command("fetch-guard <url>").description("check if a URL passes fetch guard rules and sanitize secrets").action(async (url) => emit(await runFetchGuard({ url })));
5742
+ program.command("validate <file>").description("validate vault page frontmatter against its detected schema").option("--apply", "auto-update vault index.md and log.md after successful validation", false).option("--vault <dir>", "vault root directory (required with --apply)").option("--wiki <name>", "wiki profile name").action(async (file, opts) => {
5743
+ let vault;
5744
+ if (opts.apply) {
5745
+ const v = await resolveVaultArg(opts.vault, opts.wiki);
5746
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5747
+ else vault = v.vault;
5748
+ }
5749
+ emit(await runValidate({ file, apply: !!opts.apply, vault }), vault);
5750
+ });
5751
+ program.command("graph").description("graph subcommands").command("build <vault>").option("--out <path>", "graph output path (default: <vault>/.skillwiki/graph.json)").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5752
+ const out = opts.out ?? join37(vault, ".skillwiki", "graph.json");
5753
+ emit(await runGraphBuild({ vault, out }), vault);
5754
+ });
5755
+ var canvasCmd = program.command("canvas").description("manage Obsidian canvas files");
5756
+ canvasCmd.command("generate [vault]").description("generate .canvas from graph.json").option("--graph-path <path>", "explicit path to graph.json").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5757
+ const v = await resolveVaultArg(vault, opts.wiki);
5758
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5759
+ else emit(await runCanvasGenerate({ vault: v.vault, graphPath: opts.graphPath }), v.vault);
2676
5760
  });
2677
- program.command("stale [vault]").option("--days <n>", "staleness threshold in days", (s) => parseInt(s, 10), 90).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5761
+ program.command("overlap [vault]").description("detect typed-knowledge pages that share the same raw sources").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2678
5762
  const v = await resolveVaultArg(vault, opts.wiki);
2679
5763
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2680
- else emit(await runStale({ vault: v.vault, days: opts.days }));
5764
+ else emit(await runOverlap({ vault: v.vault }), v.vault);
2681
5765
  });
2682
- program.command("pagesize [vault]").option("--lines <n>", "max body lines", (s) => parseInt(s, 10), 200).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5766
+ program.command("query <text> [vault]").description("score and rank vault pages by relevance to a query").option("--limit <n>", "max results to return", (s) => parseInt(s, 10), 10).option("--wiki <name>", "wiki profile name").action(async (text, vault, opts) => {
2683
5767
  const v = await resolveVaultArg(vault, opts.wiki);
2684
5768
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2685
- else emit(await runPagesize({ vault: v.vault, lines: opts.lines }));
5769
+ else emit(await runQuery({ text, vault: v.vault, limit: opts.limit }), v.vault);
2686
5770
  });
2687
- program.command("log-rotate [vault]").option("--threshold <n>", "entry count threshold", (s) => parseInt(s, 10), 500).option("--apply", "actually rotate", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5771
+ program.command("orphans [vault]").description("find pages not referenced by any other page").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => emit(await runOrphans({
5772
+ vault,
5773
+ envValue: process.env.WIKI_PATH,
5774
+ home: process.env.HOME ?? "",
5775
+ wiki: opts.wiki
5776
+ })));
5777
+ program.command("audit <file>").description("audit citation markers and source provenance for a vault page").action(async (file) => emit(await runAudit({ file })));
5778
+ program.command("install").description("install skillwiki SKILL.md files into ~/.claude/skills/").option("--target <dir>", "target install directory", `${process.env.HOME ?? ""}/.claude/skills/`).option("--dry-run", "preview only", false).option("--skills-root <dir>", "source skills directory (defaults to packaged)").option("--symlink", "create symlinks instead of copies (dev mode \u2014 edits to source are immediately visible)", false).action(async (opts) => {
5779
+ const skillsRoot = opts.skillsRoot ?? new URL("../skills/", import.meta.url).pathname;
5780
+ emit(await runInstall({ skillsRoot, target: opts.target, dryRun: !!opts.dryRun, symlink: !!opts.symlink }));
5781
+ });
5782
+ program.command("path").description("show the resolved vault path").option("--vault <dir>", "explicit vault override (runtime)").option("--target <dir>", "explicit target override (init-time)").option("--wiki <name>", "wiki profile name").option("--init-time", "use init-time chain instead of runtime", false).option("--explain", "include resolution chain in output", false).action(async (opts) => {
5783
+ const initTime = !!opts.initTime;
5784
+ const flag = initTime ? opts.target : opts.vault;
5785
+ emit(await runPath({
5786
+ flag,
5787
+ envValue: process.env.WIKI_PATH,
5788
+ home: process.env.HOME ?? "",
5789
+ initTime,
5790
+ wiki: opts.wiki,
5791
+ explain: !!opts.explain
5792
+ }));
5793
+ });
5794
+ program.command("lang").description("get or set the vault language").option("--lang <code>", "explicit language override").option("--explain", "include resolution chain in output", false).action(async (opts) => {
5795
+ emit(await runLang({
5796
+ flag: opts.lang,
5797
+ envValue: process.env.WIKI_LANG,
5798
+ home: process.env.HOME ?? "",
5799
+ explain: !!opts.explain
5800
+ }));
5801
+ });
5802
+ program.command("init").description("bootstrap a new vault with SCHEMA.md, index.md, log.md").option("--target <dir>", "explicit target directory").requiredOption("--domain <text>", "knowledge domain seed").option("--taxonomy <csv>", "comma-separated tag list").option("--lang <code>", "output language (BCP 47 or alias)").option("--force", "override existing target / env conflict", false).option("--no-env", "skip writing ~/.skillwiki/.env").option("--profile <name>", "write as named wiki profile instead of WIKI_PATH").action(async (opts) => {
5803
+ const templates = new URL("../templates/", import.meta.url).pathname;
5804
+ const taxonomy = typeof opts.taxonomy === "string" ? opts.taxonomy.split(",").map((s) => s.trim()).filter((s) => s.length > 0) : void 0;
5805
+ emit(await runInit({
5806
+ flag: opts.target,
5807
+ envValue: process.env.WIKI_PATH,
5808
+ home: process.env.HOME ?? "",
5809
+ templates,
5810
+ domain: opts.domain,
5811
+ taxonomy,
5812
+ lang: opts.lang,
5813
+ force: !!opts.force,
5814
+ noEnv: opts.env === false,
5815
+ profile: opts.profile
5816
+ }));
5817
+ });
5818
+ async function resolveVaultArg(arg, wiki) {
5819
+ if (arg) return { ok: true, vault: arg };
5820
+ const r = await resolveRuntimePath({
5821
+ flag: void 0,
5822
+ envValue: process.env.WIKI_PATH,
5823
+ wikiEnv: process.env.WIKI,
5824
+ home: process.env.HOME ?? "",
5825
+ wiki
5826
+ });
5827
+ if (!r.ok) {
5828
+ const exitCode = r.error === "UNKNOWN_WIKI_PROFILE" ? 35 : 25;
5829
+ return { ok: false, exitCode, payload: r };
5830
+ }
5831
+ return { ok: true, vault: r.data.path };
5832
+ }
5833
+ program.command("links [vault]").description("check wikilink integrity across the vault").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5834
+ const v = await resolveVaultArg(vault, opts.wiki);
5835
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5836
+ else emit(await runLinks({ vault: v.vault }), v.vault);
5837
+ });
5838
+ program.command("tag-audit [vault]").description("audit tag taxonomy consistency").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5839
+ const v = await resolveVaultArg(vault, opts.wiki);
5840
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5841
+ else emit(await runTagAudit({ vault: v.vault }), v.vault);
5842
+ });
5843
+ program.command("index-check [vault]").description("verify index.md entries match actual vault pages").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5844
+ const v = await resolveVaultArg(vault, opts.wiki);
5845
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5846
+ else emit(await runIndexCheck({ vault: v.vault }), v.vault);
5847
+ });
5848
+ program.command("index-link-format [vault]").description("check index.md for markdown links that should be wikilinks").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2688
5849
  const v = await resolveVaultArg(vault, opts.wiki);
2689
5850
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2690
- else emit(await runLogRotate({ vault: v.vault, threshold: opts.threshold, apply: !!opts.apply }));
5851
+ else emit(await runIndexLinkFormat({ vault: v.vault }), v.vault);
2691
5852
  });
2692
- program.command("lint [vault]").option("--days <n>", "stale threshold", (s) => parseInt(s, 10), 90).option("--lines <n>", "pagesize threshold", (s) => parseInt(s, 10), 200).option("--log-threshold <n>", "log rotation threshold", (s) => parseInt(s, 10), 500).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5853
+ program.command("topic-map-check [vault]").description("check whether a topic map page is recommended based on page count").option("--threshold <n>", "page count threshold", (s) => parseInt(s, 10), 200).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5854
+ const v = await resolveVaultArg(vault, opts.wiki);
5855
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5856
+ else emit(await runTopicMapCheck({ vault: v.vault, threshold: opts.threshold }), v.vault);
5857
+ });
5858
+ program.command("stale [vault]").description("identify stale transcripts and incomplete work items").option("--archive", "move stale items to _archive/", false).option("--days <n>", "staleness threshold in days", (s) => parseInt(s, 10), 3).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5859
+ const v = await resolveVaultArg(vault, opts.wiki);
5860
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5861
+ else emit(await runStale({ vault: v.vault, days: opts.days, archive: !!opts.archive }), v.vault);
5862
+ });
5863
+ program.command("pagesize [vault]").description("report page sizes and flag oversized pages").option("--lines <n>", "max body lines", (s) => parseInt(s, 10), 200).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5864
+ const v = await resolveVaultArg(vault, opts.wiki);
5865
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5866
+ else emit(await runPagesize({ vault: v.vault, lines: opts.lines }), v.vault);
5867
+ });
5868
+ program.command("log-rotate [vault]").description("rotate or trim the vault log file").option("--threshold <n>", "entry count threshold", (s) => parseInt(s, 10), 500).option("--apply", "actually rotate", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5869
+ const v = await resolveVaultArg(vault, opts.wiki);
5870
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5871
+ else emit(await runLogRotate({ vault: v.vault, threshold: opts.threshold, apply: !!opts.apply }), v.vault);
5872
+ });
5873
+ program.command("lint [vault]").description("run all vault health checks").option("--days <n>", "stale threshold", (s) => parseInt(s, 10), 90).option("--lines <n>", "pagesize threshold", (s) => parseInt(s, 10), 200).option("--log-threshold <n>", "log rotation threshold", (s) => parseInt(s, 10), 500).option("--fix", "auto-fix legacy_citation_style violations").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2693
5874
  const v = await resolveVaultArg(vault, opts.wiki);
2694
5875
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2695
5876
  else emit(await runLint({
@@ -2697,8 +5878,9 @@ program.command("lint [vault]").option("--days <n>", "stale threshold", (s) => p
2697
5878
  source: vault ? "flag" : void 0,
2698
5879
  days: opts.days,
2699
5880
  lines: opts.lines,
2700
- logThreshold: opts.logThreshold
2701
- }));
5881
+ logThreshold: opts.logThreshold,
5882
+ fix: opts.fix ?? false
5883
+ }), v.vault);
2702
5884
  });
2703
5885
  var configCmd = program.command("config").description("manage skillwiki configuration");
2704
5886
  configCmd.command("get <key>").description("print the value of a config key").action(async (key) => emit(await runConfigGet({ key, home: process.env.HOME ?? "" })));
@@ -2712,37 +5894,159 @@ program.command("doctor").description("diagnose skillwiki setup issues").action(
2712
5894
  currentVersion: pkg.version,
2713
5895
  cwd: process.cwd()
2714
5896
  })));
2715
- program.command("archive <page> [vault]").description("archive a typed-knowledge page").option("--wiki <name>", "wiki profile name").action(async (page, vault, opts) => {
5897
+ program.command("status [vault]").description("output vault diagnostics").option("--human", "render terminal-readable output instead of JSON").option("--json", "output as JSON (default)").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5898
+ const v = await resolveVaultArg(vault, opts.wiki);
5899
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5900
+ else emit(await runStatus({
5901
+ vault: v.vault,
5902
+ home: process.env.HOME ?? "",
5903
+ langEnvValue: process.env.WIKI_LANG
5904
+ }), v.vault);
5905
+ });
5906
+ program.command("archive <page> [vault]").description("archive a typed-knowledge or raw page").option("--wiki <name>", "wiki profile name").action(async (page, vault, opts) => {
2716
5907
  const v = await resolveVaultArg(vault, opts.wiki);
2717
5908
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2718
- else emit(await runArchive({ vault: v.vault, page }));
5909
+ else emit(await runArchive({ vault: v.vault, page }), v.vault);
2719
5910
  });
2720
- program.command("drift [vault]").description("detect content drift in raw sources").option("--apply", "update sha256 in drifted sources").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5911
+ program.command("drift [vault]").description("detect content drift in raw sources").option("--apply", "update sha256 in drifted sources").option("--new <date>", "list raw files ingested on/after this date (YYYY-MM-DD)").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2721
5912
  const v = await resolveVaultArg(vault, opts.wiki);
2722
5913
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2723
- else emit(await runDrift({ vault: v.vault, apply: opts.apply }));
5914
+ else emit(await runDrift({ vault: v.vault, apply: opts.apply, newSince: opts.new }), v.vault);
2724
5915
  });
2725
5916
  program.command("dedup [vault]").description("detect duplicate raw sources by sha256").option("--apply", "rewire citations and remove duplicate raw files", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2726
5917
  const v = await resolveVaultArg(vault, opts.wiki);
2727
5918
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2728
- else emit(await runDedup({ vault: v.vault, apply: opts.apply }));
5919
+ else emit(await runDedup({ vault: v.vault, apply: opts.apply }), v.vault);
2729
5920
  });
2730
5921
  program.command("migrate-citations [vault]").description("migrate ^[raw/...] markers to paragraph-end citations").option("--dry-run", "preview changes without writing", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2731
5922
  const v = await resolveVaultArg(vault, opts.wiki);
2732
5923
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2733
- else emit(await runMigrateCitations({ vault: v.vault, dryRun: !!opts.dryRun }));
5924
+ else emit(await runMigrateCitations({ vault: v.vault, dryRun: !!opts.dryRun }), v.vault);
2734
5925
  });
2735
5926
  program.command("frontmatter-fix [vault]").description("fix common frontmatter issues on typed-knowledge pages").option("--dry-run", "preview changes without writing", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
2736
5927
  const v = await resolveVaultArg(vault, opts.wiki);
2737
5928
  if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
2738
- else emit(await runFrontmatterFix({ vault: v.vault, dryRun: !!opts.dryRun }));
5929
+ else emit(await runFrontmatterFix({ vault: v.vault, dryRun: !!opts.dryRun }), v.vault);
2739
5930
  });
2740
5931
  program.command("update").description("update skillwiki CLI to the latest version").option("--tag <tag>", "npm dist-tag", "beta").action(async (opts) => emit(await runUpdate({
2741
5932
  home: process.env.HOME ?? "",
2742
5933
  distTag: opts.tag
2743
5934
  })));
5935
+ program.command("self-update").description("update skillwiki CLI from local source or npm@beta").option("--check", "check for updates without installing", false).action(async (opts) => emit(await runSelfUpdate({
5936
+ home: process.env.HOME ?? "",
5937
+ check: !!opts.check
5938
+ })));
5939
+ program.command("transcripts [vault]").description("list transcript files in raw/transcripts/").option("--since <date>", "only files ingested on or after this date (YYYY-MM-DD)").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5940
+ const v = await resolveVaultArg(vault, opts.wiki);
5941
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5942
+ else emit(await runTranscripts({ vault: v.vault, since: opts.since }), v.vault);
5943
+ });
5944
+ program.command("project-index <slug> [vault]").description("generate a knowledge index for a project workspace").option("--apply", "write knowledge.md to the project directory", false).option("--wiki <name>", "wiki profile name").action(async (slug, vault, opts) => {
5945
+ const v = await resolveVaultArg(vault, opts.wiki);
5946
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5947
+ else emit(await runProjectIndex({ vault: v.vault, slug, apply: !!opts.apply }), v.vault);
5948
+ });
5949
+ var compoundCmd = program.command("compound").description("manage project compound entries");
5950
+ compoundCmd.command("promote [vault]").description("promote retros with Generalize?: yes to compound entries").requiredOption("--project <slug>", "project slug (e.g., llm-wiki)").option("--dry-run", "preview promotions without writing files", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5951
+ const v = await resolveVaultArg(vault, opts.wiki);
5952
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5953
+ else emit(await runCompound({ vault: v.vault, project: opts.project, dryRun: !!opts.dryRun }), v.vault);
5954
+ });
5955
+ compoundCmd.command("list [vault]").description("list compound entries for a project").requiredOption("--project <slug>", "project slug (e.g., llm-wiki)").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5956
+ const v = await resolveVaultArg(vault, opts.wiki);
5957
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5958
+ else emit(await runCompoundList({ vault: v.vault, project: opts.project }));
5959
+ });
5960
+ compoundCmd.command("delete <entry> [vault]").description("delete a compound entry and regenerate knowledge index").requiredOption("--project <slug>", "project slug (e.g., llm-wiki)").option("--wiki <name>", "wiki profile name").action(async (entry, vault, opts) => {
5961
+ const v = await resolveVaultArg(vault, opts.wiki);
5962
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5963
+ else emit(await runCompoundDelete({ vault: v.vault, project: opts.project, entry }), v.vault);
5964
+ });
5965
+ program.command("tag-sync [vault]").description("mirror frontmatter enum values to nested Obsidian tags").option("--dry-run", "preview changes without writing", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5966
+ const v = await resolveVaultArg(vault, opts.wiki);
5967
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5968
+ else emit(await runTagSync({ vault: v.vault, dryRun: !!opts.dryRun }), v.vault);
5969
+ });
5970
+ var syncCmd = program.command("sync").description("manage vault sync");
5971
+ syncCmd.command("status [vault]").description("check vault git sync status").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5972
+ const v = await resolveVaultArg(vault, opts.wiki);
5973
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5974
+ else emit(runSyncStatus({ vault: v.vault }));
5975
+ });
5976
+ syncCmd.command("push [vault]").description("lint, commit, and push vault changes to remote").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5977
+ const v = await resolveVaultArg(vault, opts.wiki);
5978
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5979
+ else emit(await runSyncPush({ vault: v.vault }));
5980
+ });
5981
+ syncCmd.command("pull [vault]").description("pull remote vault changes and lint").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5982
+ const v = await resolveVaultArg(vault, opts.wiki);
5983
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5984
+ else emit(await runSyncPull({ vault: v.vault }), v.vault);
5985
+ });
5986
+ var backupCmd = program.command("backup").description("manage S3-compatible remote backup");
5987
+ backupCmd.command("sync [vault]").description("sync vault to S3-compatible remote backup").option("--dry-run", "list actions without executing").option("--bucket <name>", "S3 bucket name").option("--endpoint <url>", "S3 endpoint URL").option("--region <region>", "S3 region", "us-east-1").option("--prune", "delete orphaned S3 objects not in vault", false).option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
5988
+ const v = await resolveVaultArg(vault, opts.wiki);
5989
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
5990
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
5991
+ const dotenv = await parseDotenvFile(configPath(home));
5992
+ emit(await runBackupSync({
5993
+ vault: v.vault,
5994
+ bucket: opts.bucket ?? dotenv["BACKUP_BUCKET"] ?? "",
5995
+ endpoint: opts.endpoint ?? dotenv["BACKUP_ENDPOINT"] ?? "",
5996
+ region: opts.region ?? dotenv["BACKUP_REGION"] ?? "us-east-1",
5997
+ accessKeyId: dotenv["BACKUP_ACCESS_KEY_ID"] ?? "",
5998
+ secretAccessKey: dotenv["BACKUP_SECRET_ACCESS_KEY"] ?? "",
5999
+ dryRun: opts.dryRun,
6000
+ prune: opts.prune
6001
+ }), v.vault);
6002
+ });
6003
+ backupCmd.command("restore [vault]").description("restore vault from S3-compatible remote backup").option("--bucket <name>", "S3 bucket name").option("--endpoint <url>", "S3 endpoint URL").option("--region <region>", "S3 region", "us-east-1").option("--target <dir>", "restore target directory (defaults to vault)").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
6004
+ const v = await resolveVaultArg(vault, opts.wiki);
6005
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
6006
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
6007
+ const dotenv = await parseDotenvFile(configPath(home));
6008
+ emit(await runBackupRestore({
6009
+ vault: v.vault,
6010
+ bucket: opts.bucket ?? dotenv["BACKUP_BUCKET"] ?? "",
6011
+ endpoint: opts.endpoint ?? dotenv["BACKUP_ENDPOINT"] ?? "",
6012
+ region: opts.region ?? dotenv["BACKUP_REGION"] ?? "us-east-1",
6013
+ accessKeyId: dotenv["BACKUP_ACCESS_KEY_ID"] ?? "",
6014
+ secretAccessKey: dotenv["BACKUP_SECRET_ACCESS_KEY"] ?? "",
6015
+ target: opts.target
6016
+ }), v.vault);
6017
+ });
6018
+ program.command("seed [vault]").description("populate a vault with example content").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
6019
+ const v = await resolveVaultArg(vault, opts.wiki);
6020
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
6021
+ else emit(await runSeed({ vault: v.vault }), v.vault);
6022
+ });
6023
+ program.command("observe [vault]").description("create a raw transcript observation entry").requiredOption("--text <text>", "observation text").option("--kind <kind>", "observation kind (note|bug|task|idea|session-log)", "note").option("--project <slug>", "associated project slug").option("--wiki <name>", "wiki profile name").action(async (vault, opts) => {
6024
+ const v = await resolveVaultArg(vault, opts.wiki);
6025
+ if (!v.ok) emit({ exitCode: v.exitCode, result: v.payload });
6026
+ else emit(await runObserve({
6027
+ vault: v.vault,
6028
+ text: opts.text,
6029
+ kind: opts.kind,
6030
+ project: opts.project
6031
+ }), v.vault);
6032
+ });
6033
+ program.command("ingest <source>").description("ingest a source URL or local file into the vault").requiredOption("--vault <path>", "vault root directory").requiredOption("--type <type>", "typed-knowledge type (entity|concept|comparison|query)").requiredOption("--title <title>", "page title").option("--tags <csv>", "comma-separated tags").option("--provenance <provenance>", "provenance (research|project)").option("--dry-run", "preview without writing files", false).action(async (source, opts) => {
6034
+ const tags = typeof opts.tags === "string" ? opts.tags.split(",").map((s) => s.trim()).filter((s) => s.length > 0) : [];
6035
+ emit(await runIngest({
6036
+ source,
6037
+ vault: opts.vault,
6038
+ type: opts.type,
6039
+ title: opts.title,
6040
+ tags,
6041
+ provenance: opts.provenance,
6042
+ dryRun: !!opts.dryRun
6043
+ }), opts.vault);
6044
+ });
6045
+ for (const w of getDeprecatedWarnings(process.env.HOME ?? "")) {
6046
+ process.stderr.write(w + "\n");
6047
+ }
2744
6048
  triggerAutoUpdate(process.env.HOME ?? "", pkg.version);
2745
6049
  program.parseAsync(process.argv).catch((e) => {
2746
6050
  process.stdout.write(JSON.stringify({ ok: false, error: "INTERNAL", detail: { message: String(e) } }) + "\n");
2747
- process.exit(1);
6051
+ process.exit(ExitCode.INTERNAL_ERROR);
2748
6052
  });