dislop 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.cursor-plugin/plugin.json +1 -1
  5. package/PRODUCT.md +2 -2
  6. package/README.md +34 -33
  7. package/README.zh-CN.md +65 -61
  8. package/gemini-extension.json +1 -1
  9. package/package.json +2 -2
  10. package/packs/common/artifact-qa/scripts/index.mjs +64 -2
  11. package/packs/en/artifact-qa/scripts/index.mjs +1 -1
  12. package/packs/en/prose/scripts/index.mjs +3 -0
  13. package/plugin.json +1 -1
  14. package/server.json +2 -2
  15. package/skills/dislop/SKILL.md +1 -1
  16. package/skills/dislop/agents/openai.yaml +1 -1
  17. package/skills/dislop/references/essay.md +5 -5
  18. package/skills/dislop/references/essay.zh-CN.md +5 -5
  19. package/skills/dislop/references/office.md +4 -4
  20. package/skills/dislop/references/office.zh-CN.md +4 -4
  21. package/skills/dislop/references/web-ui.md +3 -3
  22. package/skills/dislop/references/web-ui.zh-CN.md +3 -3
  23. package/skills/dislop/references/work-docs.md +6 -6
  24. package/skills/dislop/references/work-docs.zh-CN.md +6 -6
  25. package/src/cli-main.mjs +88 -6
  26. package/src/commands/check-fix.mjs +170 -15
  27. package/src/commands/doctor.mjs +23 -1
  28. package/src/commands/init.mjs +24 -18
  29. package/src/commands/packs.mjs +41 -4
  30. package/src/commands/verify.mjs +36 -4
  31. package/src/commands/voice.mjs +1 -1
  32. package/src/commands/worklog.mjs +424 -0
  33. package/src/kernel/config.mjs +546 -19
  34. package/src/kernel/document-model.mjs +30 -10
  35. package/src/kernel/fact-gate.mjs +160 -0
  36. package/src/kernel/file-discovery.mjs +168 -11
  37. package/src/kernel/ooxml-binary.mjs +86 -0
  38. package/src/kernel/pack-loader.mjs +107 -21
  39. package/src/kernel/pack-validator.mjs +491 -0
  40. package/src/kernel/patcher.mjs +177 -47
  41. package/src/kernel/pipeline.mjs +284 -21
  42. package/src/kernel/prompt-assembler.mjs +37 -8
  43. package/src/kernel/version.mjs +7 -0
  44. package/src/kernel/voice-profile.mjs +3 -0
  45. package/src/mcp/stdio-server.mjs +71 -1
  46. package/src/runners/auto-fix.mjs +17 -2
  47. package/src/runners/interactive-tty.mjs +32 -5
  48. package/src/runners/reporters.mjs +18 -2
  49. package/src/runtime/providers/cloud.mjs +4 -2
  50. package/src/runtime/providers/local-model.mjs +8 -0
  51. package/src/runtime/router.mjs +11 -2
  52. package/src/runtime/worklog.mjs +904 -0
@@ -78,7 +78,9 @@ export function detectDocumentLanguage(text) {
78
78
  const cjkMatches = sample.match(/[\u4e00-\u9fff]/g);
79
79
  const cjkCount = cjkMatches ? cjkMatches.length : 0;
80
80
  const nonWs = sample.replace(/\s+/g, "").length;
81
- if (cjkCount >= 6 || (nonWs > 0 && cjkCount / nonWs >= 0.12)) {
81
+ if (nonWs === 0) return "en";
82
+ const ratio = cjkCount / nonWs;
83
+ if (ratio >= 0.12 || (cjkCount >= 6 && ratio >= 0.04)) {
82
84
  return "zh";
83
85
  }
84
86
  return "en";
@@ -921,6 +923,14 @@ function parseMarkupOrStylesheet(rawText, filePath, format) {
921
923
  const proseMask = new Uint8Array(nonUiMask);
922
924
  maskRegexOn(proseMask, /<style\b[^>]*>[\s\S]*?<\/style>/gi);
923
925
 
926
+ // Separate mask for nested inline exclusions inside prose blocks (without masking <code>)
927
+ const inlineIgnoreMask = new Uint8Array(len);
928
+ applySuppressionDirectives(rawText, inlineIgnoreMask);
929
+ maskRegexOn(inlineIgnoreMask, /<!--[\s\S]*?-->/g);
930
+ maskRegexOn(inlineIgnoreMask, /\{\/\*[\s\S]*?\*\/\}/g);
931
+ maskRegexOn(inlineIgnoreMask, /<del\b[^>]*>[\s\S]*?<\/del>/gi);
932
+ maskElementsByAttr(rawText, inlineIgnoreMask, /\bdata-dislop-ignore\b/i);
933
+
924
934
  // Extract <a ... href="..."> links outside masked regions
925
935
  const anchorRe = /<a\b([^>]*)>([\s\S]*?)<\/a>/gi;
926
936
  let am;
@@ -943,7 +953,10 @@ function parseMarkupOrStylesheet(rawText, filePath, format) {
943
953
  let bCounter = 0;
944
954
 
945
955
  for (const blk of blocks) {
946
- const pieces = normalizeHtmlInnerToPieces(blk.rawInner, blk.innerStart);
956
+ const strippedInner = Array.from(blk.rawInner)
957
+ .map((ch, idx) => (inlineIgnoreMask[blk.innerStart + idx] ? (ch === "\n" ? "\n" : " ") : ch))
958
+ .join("");
959
+ const pieces = normalizeHtmlInnerToPieces(strippedInner, blk.innerStart);
947
960
  if (pieces.length === 0) continue;
948
961
 
949
962
  let blockKind = "paragraph";
@@ -1253,21 +1266,19 @@ function parseOoxmlDocument(buffer, filePath, format) {
1253
1266
  }
1254
1267
 
1255
1268
  /**
1256
- * Parse any supported file on disk into a unified `DocumentModel`.
1269
+ * Parse any supported buffer into a unified `DocumentModel` (for both disk reads and binary-safe stdin).
1257
1270
  */
1258
- export function parseDocumentFile(filePath, explicitFormat = null) {
1271
+ export function parseDocumentBuffer(buf, filePath = "untitled.md", explicitFormat = null) {
1259
1272
  const format = explicitFormat || detectFormatFromPath(filePath);
1260
1273
  if (!format) {
1261
1274
  throw new Error(`Unsupported file extension for '${filePath}'`);
1262
1275
  }
1263
1276
 
1264
1277
  if (format === "docx" || format === "pptx") {
1265
- const buf = fs.readFileSync(filePath);
1266
1278
  return parseOoxmlDocument(buf, filePath, format);
1267
1279
  }
1268
1280
 
1269
1281
  if (["png", "jpg", "jpeg", "webp", "gif"].includes(format)) {
1270
- const buf = fs.readFileSync(filePath);
1271
1282
  const mediaSignals = inspectImageBuffer(buf, format);
1272
1283
  return {
1273
1284
  filePath,
@@ -1286,7 +1297,6 @@ export function parseDocumentFile(filePath, explicitFormat = null) {
1286
1297
  }
1287
1298
 
1288
1299
  if (format === "pdf") {
1289
- const buf = fs.readFileSync(filePath);
1290
1300
  const pdfInfo = inspectPdfBuffer(buf);
1291
1301
  const pages = pdfInfo.pages || [];
1292
1302
  const segments = [];
@@ -1359,7 +1369,7 @@ export function parseDocumentFile(filePath, explicitFormat = null) {
1359
1369
  segments,
1360
1370
  paragraphs,
1361
1371
  artifacts: {
1362
- links: [],
1372
+ links: pdfInfo.links || [],
1363
1373
  codeBlocks: [],
1364
1374
  rawFormattingLeaks,
1365
1375
  ...(isSlideDeckPdf
@@ -1386,8 +1396,6 @@ export function parseDocumentFile(filePath, explicitFormat = null) {
1386
1396
  };
1387
1397
  }
1388
1398
 
1389
- const buf = fs.readFileSync(filePath);
1390
- // Reject binary NUL bytes in supposed UTF-8 text files
1391
1399
  if (buf.includes(0)) {
1392
1400
  throw new Error(`Binary or non-UTF-8 file cannot be parsed as ${format}: '${filePath}'`);
1393
1401
  }
@@ -1395,6 +1403,18 @@ export function parseDocumentFile(filePath, explicitFormat = null) {
1395
1403
  return parseDocumentText(rawText, filePath, format);
1396
1404
  }
1397
1405
 
1406
+ /**
1407
+ * Parse any supported file on disk into a unified `DocumentModel`.
1408
+ */
1409
+ export function parseDocumentFile(filePath, explicitFormat = null) {
1410
+ const format = explicitFormat || detectFormatFromPath(filePath);
1411
+ if (!format) {
1412
+ throw new Error(`Unsupported file extension for '${filePath}'`);
1413
+ }
1414
+ const buf = fs.readFileSync(filePath);
1415
+ return parseDocumentBuffer(buf, filePath, format);
1416
+ }
1417
+
1398
1418
  /**
1399
1419
  * Parse an in-memory UTF-8 text document into a `DocumentModel`.
1400
1420
  */
@@ -467,6 +467,8 @@ export async function applyDualFactGate(items, doc, activePacks) {
467
467
  fixSafety: "manual",
468
468
  actionType: item.rewritePrompt ? "prompt" : item.actionType,
469
469
  verificationNote: `Fact Gate withheld replacement (${baseline.summary}).`,
470
+ _factGateDowngraded: true,
471
+ _factGateReasons: baseline.reasons,
470
472
  });
471
473
  continue;
472
474
  }
@@ -498,6 +500,8 @@ export async function applyDualFactGate(items, doc, activePacks) {
498
500
  fixSafety: "manual",
499
501
  actionType: item.rewritePrompt ? "prompt" : item.actionType,
500
502
  verificationNote: `Pack '${pack.name}' withheld replacement (${customRejected.reason || "failed custom verifyFix"}).`,
503
+ _factGateDowngraded: true,
504
+ _factGateReasons: ["pack_verify_fix"],
501
505
  });
502
506
  continue;
503
507
  }
@@ -606,6 +610,162 @@ export function verifyDocumentRevision(beforeText, afterText) {
606
610
  }
607
611
  }
608
612
 
613
+ // Verb / guarantee / bound polarity reversal checks
614
+ const hadEnNoGuarantee = /\b(?:not\s+guaranteed|no\s+guarantee|does\s+not\s+guarantee|without\s+guarantee)\b/i.test(
615
+ beforeText,
616
+ );
617
+ const afterHasEnNoGuarantee =
618
+ /\b(?:not\s+guaranteed|no\s+guarantee|does\s+not\s+guarantee|never\s+guaranteed|without\s+guarantee)\b/i.test(
619
+ afterText,
620
+ );
621
+ if (hadEnNoGuarantee && /\bguarantees?\b|\bguaranteed\b/i.test(afterText) && !afterHasEnNoGuarantee) {
622
+ secondOrderSlopHits.push({
623
+ id: "polarity-guarantee-flipped",
624
+ message: "Flipped non-guarantee disclaimer into an unqualified guarantee.",
625
+ });
626
+ }
627
+
628
+ const hadZhNoGuarantee = /(?:\u4e0d\u4fdd\u8bc1|\u65e0\u6cd5\u4fdd\u8bc1|\u5e76\u975e\u4fdd\u8bc1)/.test(
629
+ beforeText,
630
+ );
631
+ const afterHasZhNoGuarantee = /(?:\u4e0d\u4fdd\u8bc1|\u65e0\u6cd5\u4fdd\u8bc1|\u5e76\u975e\u4fdd\u8bc1)/.test(
632
+ afterText,
633
+ );
634
+ if (hadZhNoGuarantee && /(?:\u4fdd\u8bc1|\u786e\u4fdd)/.test(afterText) && !afterHasZhNoGuarantee) {
635
+ secondOrderSlopHits.push({
636
+ id: "polarity-zh-guarantee-flipped",
637
+ message: "Flipped Chinese non-guarantee hedge into an unqualified guarantee.",
638
+ });
639
+ }
640
+
641
+ // Subject-scoped trend polarity guard (`Revenue rose` -> `Revenue fell`, while allowing `Revenue rose. Expenses fell.`)
642
+ const extractSubjectTrends = (text) => {
643
+ const map = new Map();
644
+ const enTrendRe =
645
+ /\b([A-Za-z][A-Za-z0-9_-]{1,24})\s+(?:have\s+|has\s+)?(rose|increased|grew|gained|climbed|expanded|fell|decreased|dropped|declined|shrank|reduced)\b/gi;
646
+ let tm;
647
+ while ((tm = enTrendRe.exec(text)) !== null) {
648
+ const subj = tm[1].toLowerCase();
649
+ if (["that", "which", "they", "it", "this", "there"].includes(subj)) continue;
650
+ const dir = /^(?:rose|increased|grew|gained|climbed|expanded)$/i.test(tm[2]) ? "up" : "down";
651
+ if (!map.has(subj)) map.set(subj, new Set());
652
+ map.get(subj).add(dir);
653
+ }
654
+ const zhTrendRe =
655
+ /([\u4E00-\u9FFF]{2,12})(?:\u5927\u5e45|\u6301\u7eed|\u660e\u663e)?(\u4e0a\u5347|\u589e\u957f|\u589e\u52a0|\u4e0b\u964d|\u51cf\u5c11|\u964d\u4f4e)/g;
656
+ while ((tm = zhTrendRe.exec(text)) !== null) {
657
+ const subj = tm[1];
658
+ const dir = /^(?:\u4e0a\u5347|\u589e\u957f|\u589e\u52a0)$/.test(tm[2]) ? "up" : "down";
659
+ if (!map.has(subj)) map.set(subj, new Set());
660
+ map.get(subj).add(dir);
661
+ }
662
+ return map;
663
+ };
664
+ const beforeTrends = extractSubjectTrends(beforeText);
665
+ const afterTrends = extractSubjectTrends(afterText);
666
+ let subjectTrendFlipped = false;
667
+ for (const [subj, dirs] of beforeTrends.entries()) {
668
+ const afterDirs = afterTrends.get(subj);
669
+ if (!afterDirs) continue;
670
+ for (const d of dirs) {
671
+ const opp = d === "up" ? "down" : "up";
672
+ if (!dirs.has(opp) && afterDirs.has(opp)) {
673
+ secondOrderSlopHits.push({
674
+ id: /[\u4E00-\u9FFF]/.test(subj) ? "polarity-zh-trend-flipped" : "polarity-trend-flipped",
675
+ message: `Flipped trend verb polarity for '${subj}' (${d} -> ${opp}).`,
676
+ });
677
+ subjectTrendFlipped = true;
678
+ break;
679
+ }
680
+ }
681
+ if (subjectTrendFlipped) break;
682
+ }
683
+
684
+ const polarityPairs = [
685
+ {
686
+ id: "polarity-permission-flipped",
687
+ a: /\b(?:allows|permits|enables|supports)\b/i,
688
+ b: /\b(?:prohibits|forbids|blocks|prevents|disallows)\b/i,
689
+ message: "Flipped permission/prohibition verb polarity.",
690
+ },
691
+ {
692
+ id: "bound-qualifier-flipped",
693
+ a: /\b(?:up\s+to|at\s+most|no\s+more\s+than)\b/i,
694
+ b: /\b(?:at\s+least|more\s+than|always)\b/i,
695
+ message: "Flipped upper bound ('up to' / 'at most') into lower bound or unconditional quantifier.",
696
+ },
697
+ {
698
+ id: "bound-zh-qualifier-flipped",
699
+ a: /(?:\u4e0d\u8d85\u8fc7|\u6700\u591a)/,
700
+ b: /(?:\u81f3\u5c11|\u8d85\u8fc7)/,
701
+ message: "Flipped Chinese bound qualifier between upper and lower limits.",
702
+ },
703
+ ];
704
+ for (const pp of polarityPairs) {
705
+ if (pp.a.test(beforeText) && !pp.b.test(beforeText)) {
706
+ if (pp.b.test(afterText)) {
707
+ secondOrderSlopHits.push({ id: pp.id, message: pp.message });
708
+ }
709
+ } else if (pp.b.test(beforeText) && !pp.a.test(beforeText) && pp.a.test(afterText)) {
710
+ secondOrderSlopHits.push({ id: pp.id, message: pp.message });
711
+ }
712
+ }
713
+
714
+ // Dropped "up to X" / "at most X" / "at least X" upper/lower bound qualifier around preserved numbers
715
+ const enBoundRe = /\b(up\s+to|at\s+most|no\s+more\s+than|at\s+least)\s+([$€¥£]?\d[\d.,]*(?:\s*%|\s*[a-zA-Z]{1,6})?)/gi;
716
+ let bm;
717
+ while ((bm = enBoundRe.exec(beforeText)) !== null) {
718
+ const qual = bm[1].replace(/\s+/g, "\\s+");
719
+ const val = bm[2].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
720
+ const origNumPresent = new RegExp(val, "i").test(afterText);
721
+ const qualStillPresent = new RegExp(`\\b${qual}\\s+${val}`, "i").test(afterText);
722
+ if (origNumPresent && !qualStillPresent) {
723
+ secondOrderSlopHits.push({
724
+ id: "bound-qualifier-dropped",
725
+ message: `Dropped bound qualifier '${bm[1]}' before '${bm[2]}' in revised text.`,
726
+ });
727
+ }
728
+ }
729
+
730
+ // Currency or percentage fabrication check in revised copy
731
+ const moneyOrPctRe = /(?:[$€¥£]\s*\d[\d.,]*|\bHK\$\s*\d[\d.,]*|\b\d+(?:\.\d+)?%)/gi;
732
+ const beforeMoneyOrPct = new Set(
733
+ (String(beforeText || "").match(moneyOrPctRe) || []).map((t) => t.replace(/[,\s]+/g, "").toLowerCase()),
734
+ );
735
+ const afterMoneyOrPct = String(afterText || "").match(moneyOrPctRe) || [];
736
+ for (const tok of afterMoneyOrPct) {
737
+ const norm = tok.replace(/[,\s]+/g, "").toLowerCase();
738
+ if (!beforeMoneyOrPct.has(norm)) {
739
+ secondOrderSlopHits.push({
740
+ id: "fabricated-currency-or-percent",
741
+ message: `Introduced unanchored currency/percentage figure '${tok}' not found in original.`,
742
+ });
743
+ }
744
+ }
745
+
746
+ // Swapped Label: <value> row check (`Alpha: 10 ... Beta: 20` vs `Alpha: 20 ... Beta: 10`)
747
+ const rowPairRe = /(?:^|[\n.;\u3002])\s*([A-Za-z0-9_\u4E00-\u9FFF][A-Za-z0-9_\s\u4E00-\u9FFF/()-]{1,30}?)\s*[:\uff1a]\s*([$€¥£]?\d[\d.,]*(?:\s*(?:%|ms|s|x|k|m|b))?)/gi;
748
+ const beforePairs = new Map();
749
+ let pm;
750
+ while ((pm = rowPairRe.exec(beforeText)) !== null) {
751
+ const key = pm[1].replace(/\s+/g, " ").trim().toLowerCase();
752
+ const val = pm[2].replace(/[,\s]+/g, "").toLowerCase();
753
+ if (!beforePairs.has(key)) beforePairs.set(key, new Set());
754
+ beforePairs.get(key).add(val);
755
+ }
756
+ rowPairRe.lastIndex = 0;
757
+ while ((pm = rowPairRe.exec(afterText)) !== null) {
758
+ const key = pm[1].replace(/\s+/g, " ").trim().toLowerCase();
759
+ const val = pm[2].replace(/[,\s]+/g, "").toLowerCase();
760
+ const expected = beforePairs.get(key);
761
+ if (expected && !expected.has(val)) {
762
+ secondOrderSlopHits.push({
763
+ id: "swapped-labeled-metric",
764
+ message: `Metric value for '${pm[1].trim()}' changed from '${Array.from(expected).join("/")}' to '${pm[2]}'.`,
765
+ });
766
+ }
767
+ }
768
+
609
769
  const ok = factCheck.ok && secondOrderSlopHits.length === 0;
610
770
  return {
611
771
  ok,
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from "node:child_process";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  import { DislopConfigError } from "./config.mjs";
@@ -15,6 +16,18 @@ const DEFAULT_IGNORED_DIRS = new Set([
15
16
  "venv",
16
17
  ]);
17
18
 
19
+ function resolveComparablePath(targetPath) {
20
+ const abs = path.resolve(targetPath);
21
+ if (fs.existsSync(abs)) {
22
+ return fs.realpathSync(abs);
23
+ }
24
+ const parent = path.dirname(abs);
25
+ if (fs.existsSync(parent)) {
26
+ return path.join(fs.realpathSync(parent), path.basename(abs));
27
+ }
28
+ return abs;
29
+ }
30
+
18
31
  function expandBraces(pattern) {
19
32
  const m = String(pattern || "").match(/\{([^{}]+)\}/);
20
33
  if (!m) return [String(pattern || "")];
@@ -52,13 +65,55 @@ function globToRegExp(glob) {
52
65
  return new RegExp(rx);
53
66
  }
54
67
 
55
- function walkDirectorySupportedFiles(rootDir, collector) {
68
+ export function compileIgnoreMatchers(ignorePatterns = []) {
69
+ const fileRegexes = [];
70
+ const dirPrefixes = [];
71
+
72
+ for (const raw of ignorePatterns) {
73
+ const clean = String(raw || "")
74
+ .trim()
75
+ .replace(/\\/g, "/")
76
+ .replace(/^\.\//, "");
77
+ if (!clean) continue;
78
+
79
+ for (const pattern of expandBraces(clean)) {
80
+ if (pattern.endsWith("/**")) {
81
+ const prefix = pattern.slice(0, -3).replace(/\/+$/, "");
82
+ if (prefix) dirPrefixes.push(prefix);
83
+ } else if (pattern.endsWith("/")) {
84
+ const prefix = pattern.slice(0, -1);
85
+ if (prefix) {
86
+ dirPrefixes.push(prefix);
87
+ fileRegexes.push(globToRegExp(`${prefix}/**`));
88
+ continue;
89
+ }
90
+ }
91
+ fileRegexes.push(globToRegExp(pattern));
92
+ }
93
+ }
94
+
95
+ return (relPosix, isDirectory = false) => {
96
+ const norm = String(relPosix || "").replace(/\\/g, "/").replace(/^\.\//, "");
97
+ if (!norm) return false;
98
+ if (dirPrefixes.some((p) => norm === p || norm.startsWith(`${p}/`))) {
99
+ return true;
100
+ }
101
+ if (isDirectory) return false;
102
+ return fileRegexes.some((rx) => rx.test(norm));
103
+ };
104
+ }
105
+
106
+ function walkDirectorySupportedFiles(rootDir, ignoreRoot, isIgnored, collector) {
56
107
  for (const entry of fs.readdirSync(rootDir, { withFileTypes: true })) {
108
+ const full = path.join(rootDir, entry.name);
109
+ const rel = path
110
+ .relative(ignoreRoot, resolveComparablePath(full))
111
+ .replace(/\\/g, "/");
57
112
  if (entry.isDirectory()) {
58
- if (DEFAULT_IGNORED_DIRS.has(entry.name)) continue;
59
- walkDirectorySupportedFiles(path.join(rootDir, entry.name), collector);
113
+ if (DEFAULT_IGNORED_DIRS.has(entry.name) || isIgnored(rel, true)) continue;
114
+ walkDirectorySupportedFiles(full, ignoreRoot, isIgnored, collector);
60
115
  } else if (entry.isFile()) {
61
- const full = path.join(rootDir, entry.name);
116
+ if (isIgnored(rel, false)) continue;
62
117
  if (detectFormatFromPath(full)) {
63
118
  collector.push(full);
64
119
  }
@@ -66,15 +121,19 @@ function walkDirectorySupportedFiles(rootDir, collector) {
66
121
  }
67
122
  }
68
123
 
69
- function walkAllFilesRelative(baseDir, relPrefix, collector) {
124
+ function walkAllFilesRelative(baseDir, relPrefix, ignoreRoot, isIgnored, collector) {
70
125
  if (!fs.existsSync(baseDir)) return;
71
126
  for (const entry of fs.readdirSync(baseDir, { withFileTypes: true })) {
72
127
  const rel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
73
128
  const full = path.join(baseDir, entry.name);
129
+ const relIgnore = path
130
+ .relative(ignoreRoot, resolveComparablePath(full))
131
+ .replace(/\\/g, "/");
74
132
  if (entry.isDirectory()) {
75
- if (DEFAULT_IGNORED_DIRS.has(entry.name)) continue;
76
- walkAllFilesRelative(full, rel, collector);
133
+ if (DEFAULT_IGNORED_DIRS.has(entry.name) || isIgnored(relIgnore, true)) continue;
134
+ walkAllFilesRelative(full, rel, ignoreRoot, isIgnored, collector);
77
135
  } else if (entry.isFile()) {
136
+ if (isIgnored(relIgnore, false)) continue;
78
137
  collector.push({ rel, full });
79
138
  }
80
139
  }
@@ -87,11 +146,16 @@ function hasGlobMagic(input) {
87
146
  /**
88
147
  * Expand positional file, directory, and glob targets into sorted absolute file paths.
89
148
  */
90
- export function expandTargetInputs(inputs, { cwd = process.cwd() } = {}) {
149
+ export function expandTargetInputs(
150
+ inputs,
151
+ { cwd = process.cwd(), ignorePatterns = [], projectRoot = null } = {},
152
+ ) {
91
153
  if (!inputs || inputs.length === 0) {
92
154
  throw new DislopConfigError("Missing target <files/globs...>. Example: dislop check README.md");
93
155
  }
94
156
 
157
+ const ignoreRoot = resolveComparablePath(projectRoot || cwd);
158
+ const isIgnored = compileIgnoreMatchers(ignorePatterns);
95
159
  const found = new Set();
96
160
 
97
161
  for (const rawInput of inputs) {
@@ -106,13 +170,18 @@ export function expandTargetInputs(inputs, { cwd = process.cwd() } = {}) {
106
170
  const stat = fs.statSync(abs);
107
171
  if (stat.isDirectory()) {
108
172
  const dirFiles = [];
109
- walkDirectorySupportedFiles(abs, dirFiles);
173
+ walkDirectorySupportedFiles(abs, ignoreRoot, isIgnored, dirFiles);
110
174
  for (const f of dirFiles) found.add(f);
111
175
  } else if (stat.isFile()) {
112
176
  if (!detectFormatFromPath(abs)) {
113
177
  throw new DislopConfigError(`Unsupported file extension: '${input}'`);
114
178
  }
115
- found.add(abs);
179
+ const relIgnore = path
180
+ .relative(ignoreRoot, resolveComparablePath(abs))
181
+ .replace(/\\/g, "/");
182
+ if (!isIgnored(relIgnore, false)) {
183
+ found.add(abs);
184
+ }
116
185
  }
117
186
  continue;
118
187
  }
@@ -121,7 +190,7 @@ export function expandTargetInputs(inputs, { cwd = process.cwd() } = {}) {
121
190
  const expandedPatterns = expandBraces(input);
122
191
  const regexes = expandedPatterns.map(globToRegExp);
123
192
  const candidates = [];
124
- walkAllFilesRelative(cwd, "", candidates);
193
+ walkAllFilesRelative(cwd, "", ignoreRoot, isIgnored, candidates);
125
194
 
126
195
  let matchedAny = false;
127
196
  for (const cand of candidates) {
@@ -137,3 +206,91 @@ export function expandTargetInputs(inputs, { cwd = process.cwd() } = {}) {
137
206
 
138
207
  return Array.from(found).sort();
139
208
  }
209
+
210
+ function splitNulBuffer(buf) {
211
+ if (!buf || buf.length === 0) return [];
212
+ return buf
213
+ .toString("utf8")
214
+ .split("\0")
215
+ .map((s) => s.trim())
216
+ .filter(Boolean);
217
+ }
218
+
219
+ /**
220
+ * Discover git-changed deliverable files (`--changed` or `--since <ref>`) using NUL-delimited output.
221
+ */
222
+ export function discoverChangedFiles({
223
+ cwd = process.cwd(),
224
+ since = null,
225
+ ignorePatterns = [],
226
+ projectRoot = null,
227
+ } = {}) {
228
+ let gitRoot;
229
+ try {
230
+ gitRoot = execFileSync("git", ["rev-parse", "--show-toplevel"], {
231
+ cwd,
232
+ encoding: "utf8",
233
+ stdio: ["ignore", "pipe", "pipe"],
234
+ }).trim();
235
+ } catch {
236
+ throw new DislopConfigError(
237
+ `'--changed' / '--since' requires a git repository (not found from '${cwd}').`,
238
+ );
239
+ }
240
+
241
+ const relCandidates = new Set();
242
+ const collectGitZ = (args) => {
243
+ const out = execFileSync("git", args, {
244
+ cwd: gitRoot,
245
+ encoding: null,
246
+ stdio: ["ignore", "pipe", "pipe"],
247
+ });
248
+ for (const rel of splitNulBuffer(out)) {
249
+ relCandidates.add(rel);
250
+ }
251
+ };
252
+
253
+ if (since) {
254
+ try {
255
+ collectGitZ(["diff", "-z", "--name-only", "--diff-filter=ACMR", since]);
256
+ } catch (err) {
257
+ throw new DislopConfigError(`Invalid git ref '${since}' for --since: ${err.message}`);
258
+ }
259
+ } else {
260
+ let hasHead = false;
261
+ try {
262
+ execFileSync("git", ["rev-parse", "--verify", "HEAD"], {
263
+ cwd: gitRoot,
264
+ stdio: "ignore",
265
+ });
266
+ hasHead = true;
267
+ } catch {
268
+ hasHead = false;
269
+ }
270
+ if (hasHead) {
271
+ collectGitZ(["diff", "-z", "--name-only", "--diff-filter=ACMR", "HEAD"]);
272
+ } else {
273
+ collectGitZ(["diff", "--cached", "-z", "--name-only", "--diff-filter=ACMR"]);
274
+ }
275
+ }
276
+ collectGitZ(["ls-files", "-z", "--others", "--exclude-standard"]);
277
+
278
+ const realGitRoot = resolveComparablePath(gitRoot);
279
+ const ignoreRoot = resolveComparablePath(projectRoot || gitRoot);
280
+ const isIgnored = compileIgnoreMatchers(ignorePatterns);
281
+ const resolved = new Set();
282
+ for (const rel of relCandidates) {
283
+ const abs = path.resolve(realGitRoot, rel);
284
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) continue;
285
+ const realAbs = resolveComparablePath(abs);
286
+ const relFromRoot = path.relative(realGitRoot, realAbs).replace(/\\/g, "/");
287
+ // Confine symlinked targets inside the canonical git repository root
288
+ if (relFromRoot.startsWith("..") || path.isAbsolute(relFromRoot)) continue;
289
+ if (!detectFormatFromPath(abs)) continue;
290
+ const relFromIgnore = path.relative(ignoreRoot, realAbs).replace(/\\/g, "/");
291
+ if (isIgnored(relFromIgnore, false) || isIgnored(relFromRoot, false)) continue;
292
+ resolved.add(abs);
293
+ }
294
+
295
+ return Array.from(resolved).sort();
296
+ }
@@ -1391,13 +1391,93 @@ export function inspectPdfBuffer(buffer) {
1391
1391
  }
1392
1392
  }
1393
1393
 
1394
+ function extractPdfUriValuesFromText(rawText, pageIndex, seen, out) {
1395
+ if (!rawText || !rawText.includes("/URI")) return;
1396
+ const pushUrl = (url) => {
1397
+ const clean = String(url || "").trim();
1398
+ if (!clean) return;
1399
+ const key = `${pageIndex}:${clean}`;
1400
+ if (seen.has(key)) return;
1401
+ seen.add(key);
1402
+ out.push({
1403
+ url: clean,
1404
+ raw: clean,
1405
+ line: pageIndex,
1406
+ segmentId: null,
1407
+ locator: { kind: "pdf-readonly", page: pageIndex },
1408
+ });
1409
+ };
1410
+
1411
+ // Balanced nested parenthesis scan for `/URI (...)`
1412
+ const keyRe = /\/URI\s*\(/g;
1413
+ let km;
1414
+ while ((km = keyRe.exec(rawText)) !== null) {
1415
+ let i = km.index + km[0].length;
1416
+ let depth = 1;
1417
+ let rawLit = "";
1418
+ while (i < rawText.length && depth > 0) {
1419
+ const ch = rawText[i];
1420
+ if (ch === "\\") {
1421
+ rawLit += ch + (rawText[i + 1] ?? "");
1422
+ i += 2;
1423
+ continue;
1424
+ }
1425
+ if (ch === "(") {
1426
+ depth += 1;
1427
+ rawLit += ch;
1428
+ } else if (ch === ")") {
1429
+ depth -= 1;
1430
+ if (depth > 0) rawLit += ch;
1431
+ } else {
1432
+ rawLit += ch;
1433
+ }
1434
+ i += 1;
1435
+ }
1436
+ if (depth === 0) {
1437
+ pushUrl(decodePdfUnicodeLiteral(rawLit));
1438
+ }
1439
+ }
1440
+
1441
+ const hexRe = /\/URI\s*<([0-9A-Fa-f\s]+)>/g;
1442
+ let m;
1443
+ while ((m = hexRe.exec(rawText)) !== null) {
1444
+ pushUrl(decodePdfHexString(m[1]));
1445
+ }
1446
+ }
1447
+
1394
1448
  const fontCache = new Map();
1449
+ const pdfLinks = [];
1450
+ const seenLinks = new Set();
1451
+ const visitedUriObjNums = new Set();
1452
+
1395
1453
  const pages = orderedPageObjs.map((pageObj, idx) => {
1396
1454
  const [width, height] = inheritedMediaBox.get(pageObj.objNum) || [612, 792];
1397
1455
  const resText = inheritedResources.get(pageObj.objNum) || extractOwnRes(pageObj.dictRaw);
1398
1456
  const fontMap = resolvePageFontMap(resText, objects, fontCache);
1399
1457
  const xObjectMap = resolvePageXObjectMap(resText, objects);
1400
1458
 
1459
+ const annotRefs = [];
1460
+ const annotsArr = pageObj.dictRaw.match(/\/Annots\s*\[([^\]]*)\]/);
1461
+ if (annotsArr) {
1462
+ for (const rm of annotsArr[1].matchAll(/(\d+)\s+\d+\s+R/g)) annotRefs.push(Number(rm[1]));
1463
+ } else {
1464
+ const annotsSingle = pageObj.dictRaw.match(/\/Annots\s+(\d+)\s+\d+\s+R/);
1465
+ if (annotsSingle) annotRefs.push(Number(annotsSingle[1]));
1466
+ }
1467
+ for (const aNum of annotRefs) {
1468
+ visitedUriObjNums.add(aNum);
1469
+ const aObj = objects.get(aNum);
1470
+ if (!aObj) continue;
1471
+ extractPdfUriValuesFromText(aObj.dictRaw, idx + 1, seenLinks, pdfLinks);
1472
+ const actRef = aObj.dictRaw.match(/\/A\s+(\d+)\s+\d+\s+R/);
1473
+ if (actRef) {
1474
+ const actNum = Number(actRef[1]);
1475
+ visitedUriObjNums.add(actNum);
1476
+ const actObj = objects.get(actNum);
1477
+ if (actObj) extractPdfUriValuesFromText(actObj.dictRaw, idx + 1, seenLinks, pdfLinks);
1478
+ }
1479
+ }
1480
+
1401
1481
  const contentRefs = [];
1402
1482
  const arrMatch = pageObj.dictRaw.match(/\/Contents\s*\[([^\]]*)\]/);
1403
1483
  if (arrMatch) {
@@ -1429,11 +1509,17 @@ export function inspectPdfBuffer(buffer) {
1429
1509
  };
1430
1510
  });
1431
1511
 
1512
+ for (const obj of objects.values()) {
1513
+ if (visitedUriObjNums.has(obj.objNum)) continue;
1514
+ extractPdfUriValuesFromText(obj.dictRaw, 1, seenLinks, pdfLinks);
1515
+ }
1516
+
1432
1517
  const fallbackPageCount = pages.length || (latin.match(/\/Type\s*\/Page\b/g) || []).length || 1;
1433
1518
  return {
1434
1519
  encrypted: false,
1435
1520
  pageCount: fallbackPageCount,
1436
1521
  pages,
1522
+ links: pdfLinks,
1437
1523
  extractedText: pages.map((p) => p.text).filter(Boolean).join("\n\n"),
1438
1524
  };
1439
1525
  }