@tangle-network/agent-app 0.45.21 → 0.45.23

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 (118) hide show
  1. package/dist/DesignCanvas-ZG7DJS7C.js +10 -0
  2. package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/assistant/index.d.ts +1 -1
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
  7. package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
  8. package/dist/chat-react/index.js +2 -2
  9. package/dist/chat-routes/index.d.ts +8 -4
  10. package/dist/chat-routes/index.js +21 -4
  11. package/dist/chat-routes/index.js.map +1 -1
  12. package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
  13. package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
  14. package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
  15. package/dist/{chunk-AH3IOSWF.js → chunk-7PFFFRVU.js} +2077 -341
  16. package/dist/chunk-7PFFFRVU.js.map +1 -0
  17. package/dist/chunk-CCVG2TL6.js +327 -0
  18. package/dist/chunk-CCVG2TL6.js.map +1 -0
  19. package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
  20. package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
  21. package/dist/chunk-F7VH4G5C.js +283 -0
  22. package/dist/chunk-F7VH4G5C.js.map +1 -0
  23. package/dist/chunk-I24YIKHO.js +183 -0
  24. package/dist/chunk-I24YIKHO.js.map +1 -0
  25. package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
  26. package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
  27. package/dist/chunk-PC2WYTK7.js +405 -0
  28. package/dist/chunk-PC2WYTK7.js.map +1 -0
  29. package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
  30. package/dist/chunk-TX6S7XXU.js.map +1 -0
  31. package/dist/chunk-UGWQLQDS.js +35 -0
  32. package/dist/chunk-UGWQLQDS.js.map +1 -0
  33. package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
  34. package/dist/chunk-XEA5EG6P.js +1478 -0
  35. package/dist/chunk-XEA5EG6P.js.map +1 -0
  36. package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
  37. package/dist/design-canvas/index.d.ts +3 -3
  38. package/dist/design-canvas/index.js +2 -2
  39. package/dist/design-canvas-react/engine.js +4 -4
  40. package/dist/design-canvas-react/index.js +7 -7
  41. package/dist/design-canvas-react/lazy.js +1 -1
  42. package/dist/documents/index.d.ts +233 -0
  43. package/dist/documents/index.js +495 -0
  44. package/dist/documents/index.js.map +1 -0
  45. package/dist/documents/pdf-inspector.d.ts +60 -0
  46. package/dist/documents/pdf-inspector.js +100 -0
  47. package/dist/documents/pdf-inspector.js.map +1 -0
  48. package/dist/eval/index.d.ts +1 -1
  49. package/dist/fold-DACU7gtf.d.ts +320 -0
  50. package/dist/legibility/cli.d.ts +1 -0
  51. package/dist/legibility/cli.js +143 -0
  52. package/dist/legibility/cli.js.map +1 -0
  53. package/dist/legibility/index.d.ts +572 -0
  54. package/dist/legibility/index.js +33 -0
  55. package/dist/legibility/index.js.map +1 -0
  56. package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
  57. package/dist/openui/index.d.ts +208 -0
  58. package/dist/openui/index.js +350 -0
  59. package/dist/openui/index.js.map +1 -0
  60. package/dist/openui-react/index.d.ts +119 -0
  61. package/dist/openui-react/index.js +149 -0
  62. package/dist/openui-react/index.js.map +1 -0
  63. package/dist/platform/index.js +2 -2
  64. package/dist/preset-cloudflare/index.d.ts +2 -2
  65. package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
  66. package/dist/record/drizzle.d.ts +682 -0
  67. package/dist/record/drizzle.js +579 -0
  68. package/dist/record/drizzle.js.map +1 -0
  69. package/dist/record/index.d.ts +16 -0
  70. package/dist/record/index.js +35 -0
  71. package/dist/record/index.js.map +1 -0
  72. package/dist/runtime/index.d.ts +3 -3
  73. package/dist/sandbox/index.d.ts +2 -2
  74. package/dist/sandbox/index.js +3 -2
  75. package/dist/sequences/index.d.ts +3 -3
  76. package/dist/sequences/index.js +1 -1
  77. package/dist/session-shell/index.d.ts +173 -1
  78. package/dist/session-shell/index.js +13 -1
  79. package/dist/teams/index.js +9 -9
  80. package/dist/teams/invitations-api.js +3 -3
  81. package/dist/tools/index.d.ts +5 -5
  82. package/dist/tools/index.js +3 -2
  83. package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
  84. package/dist/types-DrBidf3O.d.ts +123 -0
  85. package/dist/values-C7RidJuI.d.ts +156 -0
  86. package/dist/web/index.d.ts +197 -31
  87. package/dist/web/index.js +15 -3
  88. package/dist/web-react/async/index.d.ts +309 -0
  89. package/dist/web-react/async/index.js +327 -0
  90. package/dist/web-react/async/index.js.map +1 -0
  91. package/dist/web-react/index.d.ts +586 -2
  92. package/dist/web-react/index.js +84 -6
  93. package/dist/work-product/index.d.ts +1 -1
  94. package/dist/work-product/index.js +2 -1
  95. package/dist/work-product/index.js.map +1 -1
  96. package/dist/workspace-react/index.js +1 -1
  97. package/package.json +49 -3
  98. package/dist/DesignCanvas-NEIW3AER.js +0 -10
  99. package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
  100. package/dist/chunk-AH3IOSWF.js.map +0 -1
  101. package/dist/chunk-GINKOZFD.js +0 -214
  102. package/dist/chunk-GINKOZFD.js.map +0 -1
  103. package/dist/chunk-J25RST7G.js +0 -126
  104. package/dist/chunk-J25RST7G.js.map +0 -1
  105. package/dist/chunk-WBHPN5DY.js +0 -158
  106. package/dist/chunk-WBHPN5DY.js.map +0 -1
  107. package/dist/chunk-YEFFHORB.js.map +0 -1
  108. /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
  109. /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
  110. /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
  111. /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
  112. /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
  113. /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
  114. /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
  115. /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
  116. /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
  117. /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
  118. /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
@@ -0,0 +1,100 @@
1
+ // src/documents/pdf-inspector.ts
2
+ import { detectPdf, initSync, processPdf, extractText, version } from "@firecrawl/pdf-inspector-wasm";
3
+ var initialized = false;
4
+ function detail(error) {
5
+ return error instanceof Error ? error.message : String(error);
6
+ }
7
+ function fail(code, stage, message) {
8
+ return { succeeded: false, error: { code, stage, message, mediaType: "application/pdf" } };
9
+ }
10
+ var KINDS = {
11
+ TextBased: "text-based",
12
+ Scanned: "scanned",
13
+ ImageBased: "image-based",
14
+ Mixed: "mixed"
15
+ };
16
+ function initPdfInspector(wasm) {
17
+ try {
18
+ if (!initialized) {
19
+ initSync({ module: typeof wasm === "function" ? wasm() : wasm });
20
+ initialized = true;
21
+ }
22
+ return { succeeded: true, value: { version: version() } };
23
+ } catch (error) {
24
+ initialized = false;
25
+ return {
26
+ succeeded: false,
27
+ error: {
28
+ code: "classification-failed",
29
+ stage: "classify",
30
+ mediaType: "application/pdf",
31
+ message: `The PDF engine's wasm failed to instantiate \u2014 ${detail(error)}. Check that the .wasm asset reaches the runtime as a compiled module (see the documents module docs).`
32
+ }
33
+ };
34
+ }
35
+ }
36
+ function isPdfInspectorReady() {
37
+ return initialized;
38
+ }
39
+ function toClassification(result) {
40
+ const kind = KINDS[result.pdfType] ?? "mixed";
41
+ const needing = new Set(result.pagesNeedingOcr);
42
+ const reasons = new Map(result.ocrReasonsByPage.map((entry) => [entry.page, entry.reasons]));
43
+ const tables = new Set(result.layout.pagesWithTables);
44
+ const columns = new Set(result.layout.pagesWithColumns);
45
+ const pages = [];
46
+ for (let pageNumber = 1; pageNumber <= result.pageCount; pageNumber++) {
47
+ pages.push({
48
+ pageNumber,
49
+ index: pageNumber - 1,
50
+ needsOcr: needing.has(pageNumber),
51
+ ocrReasons: reasons.get(pageNumber) ?? [],
52
+ hasTable: tables.has(pageNumber),
53
+ hasColumns: columns.has(pageNumber)
54
+ });
55
+ }
56
+ const pagesNeedingOcr = pages.filter((page) => page.needsOcr).map((page) => page.pageNumber);
57
+ const noTextAnywhere = result.pageCount > 0 && pagesNeedingOcr.length === result.pageCount;
58
+ return {
59
+ kind,
60
+ pageCount: result.pageCount,
61
+ confidence: result.confidence,
62
+ pages,
63
+ pagesNeedingOcr,
64
+ needsOcr: noTextAnywhere || (kind === "scanned" || kind === "image-based") && pagesNeedingOcr.length === 0,
65
+ partiallyScanned: pagesNeedingOcr.length > 0 && !noTextAnywhere,
66
+ complexLayout: result.layout.isComplex,
67
+ hasEncodingIssues: result.hasEncodingIssues
68
+ };
69
+ }
70
+ function createPdfInspectorEngine(wasm) {
71
+ const ready = () => initPdfInspector(wasm);
72
+ return {
73
+ classify(bytes) {
74
+ const init = ready();
75
+ if (!init.succeeded) return init;
76
+ try {
77
+ return { succeeded: true, value: toClassification(detectPdf(bytes)) };
78
+ } catch (error) {
79
+ return fail("classification-failed", "classify", `The PDF could not be read \u2014 ${detail(error)}.`);
80
+ }
81
+ },
82
+ extract(bytes, format) {
83
+ const init = ready();
84
+ if (!init.succeeded) return { succeeded: false, error: { ...init.error, code: "extraction-failed", stage: "extract" } };
85
+ try {
86
+ if (format === "text") return { succeeded: true, value: extractText(bytes) };
87
+ const processed = processPdf(bytes, { profile: "fidelity", includePageMarkers: true });
88
+ return { succeeded: true, value: processed.markdown ?? "" };
89
+ } catch (error) {
90
+ return fail("extraction-failed", "extract", `The PDF's text could not be extracted \u2014 ${detail(error)}.`);
91
+ }
92
+ }
93
+ };
94
+ }
95
+ export {
96
+ createPdfInspectorEngine,
97
+ initPdfInspector,
98
+ isPdfInspectorReady
99
+ };
100
+ //# sourceMappingURL=pdf-inspector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/documents/pdf-inspector.ts"],"sourcesContent":["/**\n * The wasm-backed {@link PdfEngine}, binding `@firecrawl/pdf-inspector-wasm`\n * (MIT, Rust→wasm).\n *\n * **Why this is its own subpath.** The engine's `.wasm` must reach the runtime\n * as a build-time module asset produced by the CONSUMER's bundler — workerd\n * forbids compiling wasm from bytes at request time — so a shared library\n * cannot import it. This file therefore imports only the JS glue and takes the\n * compiled module as an argument. Keeping it out of\n * `@tangle-network/agent-app/documents` also means a product that only handles\n * DOCX and text never needs the package installed at all.\n *\n * **Why this engine.** It is the one PDF extractor proven to run under real\n * workerd: the wasm imports nothing but its own JS glue (no WASI), and\n * `initSync` instantiates an already-compiled `WebAssembly.Module`, which is\n * exactly the case workerd permits. The napi build does not run there, and\n * pdfjs-based extractors need DOM globals workerd does not have.\n *\n * **Engine behaviour this wrapper is built around, measured on real fixture\n * PDFs (`tests/documents/pdf.test.ts` re-measures all of it):**\n * - `extractText` PANICS (`RuntimeError: unreachable`, an out-of-bounds index\n * in the engine's layout table) on any document with a page that has no text\n * layer — including a `mixed` document whose other pages are fine. The\n * instance survives the panic, but nothing recovers the text.\n * - `detectPdf` and `processPdf` do NOT panic on those documents; `processPdf`\n * returns the readable pages' markdown, which is why `extract` uses it for\n * markdown and for anything partially scanned.\n * - `detectPdf` reports OCR pages 1-INDEXED, while `classifyPdf` reports the\n * same pages 0-indexed. This wrapper uses `detectPdf` (it carries per-page\n * reasons and layout that `classifyPdf` does not) and publishes 1-indexed.\n * - `processPdf`'s own `pagesNeedingOcr` is unreliable — it reported both pages\n * of a fully text-based 2-page PDF as needing OCR — so the classification a\n * caller sees always comes from `detectPdf`.\n */\n\nimport { detectPdf, initSync, processPdf, extractText, version } from '@firecrawl/pdf-inspector-wasm'\n\nimport type {\n DocumentOutcome,\n PdfClassification,\n PdfContentKind,\n PdfEngine,\n PdfPageClassification,\n PdfTextFormat,\n} from './types'\n\n/**\n * The compiled wasm, or a thunk that produces it on first use.\n *\n * A Worker passes the `.wasm` module import (a `WebAssembly.Module`); Node\n * passes raw bytes. A thunk defers reading either until a PDF actually arrives.\n */\nexport type PdfInspectorWasm =\n | WebAssembly.Module\n | BufferSource\n | (() => WebAssembly.Module | BufferSource)\n\n// `initSync` binds a module-global inside the engine's glue, so readiness is\n// per-isolate, not per-engine-instance: two engines built from the same wasm\n// must not each re-instantiate it.\nlet initialized = false\n\nfunction detail(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction fail(\n code: 'classification-failed' | 'extraction-failed',\n stage: 'classify' | 'extract',\n message: string,\n): { succeeded: false; error: { code: 'classification-failed' | 'extraction-failed'; stage: 'classify' | 'extract'; message: string; mediaType: string } } {\n return { succeeded: false, error: { code, stage, message, mediaType: 'application/pdf' } }\n}\n\nconst KINDS: Readonly<Record<string, PdfContentKind>> = {\n TextBased: 'text-based',\n Scanned: 'scanned',\n ImageBased: 'image-based',\n Mixed: 'mixed',\n}\n\n/** Instantiate the engine for this isolate. Idempotent; safe to call per\n * request. Exported so a product can warm the wasm at startup instead of\n * paying instantiation on a user's first upload. */\nexport function initPdfInspector(wasm: PdfInspectorWasm): DocumentOutcome<{ version: string }> {\n try {\n if (!initialized) {\n initSync({ module: typeof wasm === 'function' ? wasm() : wasm })\n initialized = true\n }\n return { succeeded: true, value: { version: version() } }\n } catch (error) {\n initialized = false\n return {\n succeeded: false,\n error: {\n code: 'classification-failed',\n stage: 'classify',\n mediaType: 'application/pdf',\n message: `The PDF engine's wasm failed to instantiate — ${detail(error)}. Check that the .wasm asset reaches the runtime as a compiled module (see the documents module docs).`,\n },\n }\n }\n}\n\n/** Whether the engine has been instantiated in this isolate. */\nexport function isPdfInspectorReady(): boolean {\n return initialized\n}\n\nfunction toClassification(result: {\n pdfType: string\n pageCount: number\n pagesNeedingOcr: number[]\n ocrReasonsByPage: { page: number; reasons: string[] }[]\n confidence: number\n layout: { isComplex: boolean; pagesWithTables: number[]; pagesWithColumns: number[] }\n hasEncodingIssues: boolean\n}): PdfClassification {\n const kind = KINDS[result.pdfType] ?? 'mixed'\n const needing = new Set(result.pagesNeedingOcr)\n const reasons = new Map(result.ocrReasonsByPage.map((entry) => [entry.page, entry.reasons]))\n const tables = new Set(result.layout.pagesWithTables)\n const columns = new Set(result.layout.pagesWithColumns)\n\n const pages: PdfPageClassification[] = []\n for (let pageNumber = 1; pageNumber <= result.pageCount; pageNumber++) {\n pages.push({\n pageNumber,\n index: pageNumber - 1,\n needsOcr: needing.has(pageNumber),\n ocrReasons: reasons.get(pageNumber) ?? [],\n hasTable: tables.has(pageNumber),\n hasColumns: columns.has(pageNumber),\n })\n }\n\n const pagesNeedingOcr = pages.filter((page) => page.needsOcr).map((page) => page.pageNumber)\n // `kind` alone cannot decide this: a 1-page scan and a 40-page document with\n // one scanned exhibit can both come back `Scanned`/`Mixed` depending on the\n // engine's confidence, so the page count is what separates \"no text at all\"\n // from \"text on most pages\".\n const noTextAnywhere = result.pageCount > 0 && pagesNeedingOcr.length === result.pageCount\n return {\n kind,\n pageCount: result.pageCount,\n confidence: result.confidence,\n pages,\n pagesNeedingOcr,\n needsOcr: noTextAnywhere || ((kind === 'scanned' || kind === 'image-based') && pagesNeedingOcr.length === 0),\n partiallyScanned: pagesNeedingOcr.length > 0 && !noTextAnywhere,\n complexLayout: result.layout.isComplex,\n hasEncodingIssues: result.hasEncodingIssues,\n }\n}\n\n/**\n * Build the wasm-backed engine. Instantiation is lazy — the first classify or\n * extract call initializes it — so importing this costs nothing until a PDF\n * arrives.\n */\nexport function createPdfInspectorEngine(wasm: PdfInspectorWasm): PdfEngine {\n const ready = (): DocumentOutcome<{ version: string }> => initPdfInspector(wasm)\n\n return {\n classify(bytes: Uint8Array) {\n const init = ready()\n if (!init.succeeded) return init\n try {\n return { succeeded: true, value: toClassification(detectPdf(bytes)) }\n } catch (error) {\n return fail('classification-failed', 'classify', `The PDF could not be read — ${detail(error)}.`)\n }\n },\n extract(bytes: Uint8Array, format: PdfTextFormat) {\n const init = ready()\n if (!init.succeeded) return { succeeded: false, error: { ...init.error, code: 'extraction-failed', stage: 'extract' } }\n try {\n if (format === 'text') return { succeeded: true, value: extractText(bytes) }\n const processed = processPdf(bytes, { profile: 'fidelity', includePageMarkers: true })\n return { succeeded: true, value: processed.markdown ?? '' }\n } catch (error) {\n return fail('extraction-failed', 'extract', `The PDF's text could not be extracted — ${detail(error)}.`)\n }\n },\n }\n}\n"],"mappings":";AAmCA,SAAS,WAAW,UAAU,YAAY,aAAa,eAAe;AAyBtE,IAAI,cAAc;AAElB,SAAS,OAAO,OAAwB;AACtC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAAS,KACP,MACA,OACA,SACyJ;AACzJ,SAAO,EAAE,WAAW,OAAO,OAAO,EAAE,MAAM,OAAO,SAAS,WAAW,kBAAkB,EAAE;AAC3F;AAEA,IAAM,QAAkD;AAAA,EACtD,WAAW;AAAA,EACX,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,OAAO;AACT;AAKO,SAAS,iBAAiB,MAA8D;AAC7F,MAAI;AACF,QAAI,CAAC,aAAa;AAChB,eAAS,EAAE,QAAQ,OA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AAY,OAAO;AAAA,IACnB;AAAA,IACA;AAAA,IACA,UAAU,mBAAoB,SAAS,aAAa,SAAS,kBAAkB,gBAAgB,WAAW;AAAA,IAC1G,kBAAkB,gBAAgB,SAAS,KAAK,CAAC;AAAA,IACjD,eAAe,OAAO,OAAO;AAAA,IAC7B,mBAAmB,OAAO;AAAA,EAC5B;AACF;AAOO,SAAS,yBAAyB,MAAmC;AAC1E,QAAM,QAAQ,MAA4C,iBAAiB,IAAI;AAE/E,SAAO;AAAA,IACL,SAAS,OAAmB;AAC1B,YAAM,OAAO,MAAM;AACnB,UAAI,CAAC,KAAK,UAAW,QAAO;AAC5B,UAAI;AACF,eAAO,EAAE,WAAW,MAAM,OAAO,iBAAiB,UAAU,KAAK,CAAC,EAAE;AAAA,MACtE,SAAS,OAAO;AACd,eAAO,KAAK,yBAAyB,YAAY,oCAA+B,OAAO,KAAK,CAAC,GAAG;AAAA,MAClG;AAAA,IACF;AAAA,IACA,QAAQ,OAAmB,QAAuB;AAChD,YAAM,OAAO,MAAM;AACnB,UAAI,CAAC,KAAK,UAAW,QAAO,EAAE,WAAW,OAAO,OAAO,EAAE,GAAG,KAAK,OAAO,MAAM,qBAAqB,OAAO,UAAU,EAAE;AACtH,UAAI;AACF,YAAI,WAAW,OAAQ,QAAO,EAAE,WAAW,MAAM,OAAO,YAAY,KAAK,EAAE;AAC3E,cAAM,YAAY,WAAW,OAAO,EAAE,SAAS,YAAY,oBAAoB,KAAK,CAAC;AACrF,eAAO,EAAE,WAAW,MAAM,OAAO,UAAU,YAAY,GAAG;AAAA,MAC5D,SAAS,OAAO;AACd,eAAO,KAAK,qBAAqB,WAAW,gDAA2C,OAAO,KAAK,CAAC,GAAG;AAAA,MACzG;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import { CompletionRequirement, RuntimeEventLike } from '@tangle-network/agent-eval';
2
2
  export { CompletionRequirement, CompletionVerdict, CorrectnessChecker, ProducedState, RuntimeEventLike, SatisfiedBy, TaskGold, createLlmCorrectnessChecker, extractProducedState, verifyCompletion, weightedComposite } from '@tangle-network/agent-eval';
3
- import { c as AppToolProducedEvent } from '../types-DbU-oO5h.js';
3
+ import { c as AppToolProducedEvent } from '../types-B25Mib1r.js';
4
4
 
5
5
  /**
6
6
  * Calibration — prove a gate can FAIL before believing that it PASSED, and
@@ -0,0 +1,320 @@
1
+ /**
2
+ * The pure core of the record module: the entry vocabulary, the key sentinels,
3
+ * canonical value encoding, consumer-supplied validation, and the conflict
4
+ * rule. Zero imports — a product can fold and validate entries in a browser,
5
+ * an eval process, or a worker without touching a database driver.
6
+ *
7
+ * A record entry is one source-cited assertion: "at `path` (optionally for
8
+ * `itemKey`, in `dimension`, for `period`), the value is X, and here is where
9
+ * that came from". Entries are append-only. An entry becomes the live head of
10
+ * its key by being `accepted` with no `supersededById`; the previous head is
11
+ * marked superseded in the same atomic write, so the history stays readable.
12
+ *
13
+ * Every domain word — what a path means, what an item key identifies, what a
14
+ * dimension or period is, which source kinds exist — is a parameter supplied
15
+ * by the consumer. This module knows none of them.
16
+ */
17
+ /** Error classes a caller maps to a status code or a retry decision. */
18
+ type RecordErrorCode =
19
+ /** The path is not a key of the consumer's schema map. */
20
+ 'unknown-path'
21
+ /** The value failed the consumer's schema for its path. */
22
+ | 'invalid-value'
23
+ /** The input is structurally wrong (bad period, missing source ref, …). */
24
+ | 'invalid-input'
25
+ /** The source kind is not a key of the consumer's review policy. */
26
+ | 'unknown-source-kind'
27
+ /** No such entry in this scope. */
28
+ | 'not-found'
29
+ /** The entry is not in a state this operation accepts. */
30
+ | 'not-reviewable'
31
+ /** A competing writer took the live head; the caller may re-read and retry. */
32
+ | 'supersede-race'
33
+ /** The fold rejected an entry — the record cannot be materialized. */
34
+ | 'fold-failed'
35
+ /** The driver raised. */
36
+ | 'storage-failed'
37
+ /** The driver exposes no atomic multi-statement primitive. */
38
+ | 'unsupported-driver';
39
+ /**
40
+ * Typed outcome for every record operation. Callers MUST inspect `succeeded`
41
+ * before reading `value`; nothing here throws past its own boundary except a
42
+ * programming error in the consumer's own callbacks.
43
+ */
44
+ type RecordOutcome<T> = {
45
+ succeeded: true;
46
+ value: T;
47
+ } | {
48
+ succeeded: false;
49
+ error: string;
50
+ code: RecordErrorCode;
51
+ };
52
+ /** Build a success outcome. */
53
+ declare function recordOk<T>(value: T): RecordOutcome<T>;
54
+ /** Build a failure outcome carrying its error class. */
55
+ declare function recordFail(code: RecordErrorCode, error: string): RecordOutcome<never>;
56
+ /**
57
+ * Sentinel for an unused key column.
58
+ *
59
+ * SQLite treats NULLs as distinct in a unique index, so a nullable key column
60
+ * would let two live heads coexist on the same logical key. Every key column
61
+ * is therefore NOT NULL with a sentinel, and this is the sentinel for the two
62
+ * text ones (`dimension`, `itemKey`).
63
+ */
64
+ declare const RECORD_KEY_SENTINEL = "";
65
+ /**
66
+ * Sentinel period for a record with no time dimension. Same reason as
67
+ * {@link RECORD_KEY_SENTINEL}: the column is NOT NULL so the unique index over
68
+ * the live head actually dedupes. A consumer with no period concept writes
69
+ * every entry at `0` and materializes at `0`.
70
+ */
71
+ declare const RECORD_PERIOD_SENTINEL = 0;
72
+ /** Lifecycle of one entry. `accepted` requires a structured act — a source
73
+ * kind the policy trusts, or an explicit review. */
74
+ type RecordReviewState = 'proposed' | 'accepted' | 'rejected';
75
+ /** Every review state, for iteration and validation. */
76
+ declare const RECORD_REVIEW_STATES: readonly RecordReviewState[];
77
+ /** Position of the assertion inside its source. All fields optional — a chat
78
+ * message has no page, a scraped row has no character span. */
79
+ interface RecordSourceLocator {
80
+ page?: number;
81
+ charStart?: number;
82
+ charEnd?: number;
83
+ }
84
+ /** The columns that identify which assertion an entry supersedes. Two entries
85
+ * with the same key compete for the same live head. */
86
+ interface RecordEntryKey {
87
+ /** Consumer-defined partition inside a scope — whatever second axis the
88
+ * product folds along. {@link RECORD_KEY_SENTINEL} when unused. */
89
+ dimension: string;
90
+ /** The field this entry asserts. Must be a key of the schema map. */
91
+ path: string;
92
+ /** Identifies which element of a collection the path belongs to, when the
93
+ * path addresses a repeated thing. {@link RECORD_KEY_SENTINEL} when unused. */
94
+ itemKey: string;
95
+ /** The period the assertion became true in. {@link RECORD_PERIOD_SENTINEL}
96
+ * when the consumer has no time dimension. */
97
+ period: number;
98
+ }
99
+ /** Join an entry key into one comparable string, for grouping in memory. */
100
+ declare function recordKeyString(key: RecordEntryKey): string;
101
+ /**
102
+ * Deterministic JSON with object keys sorted at every depth. Two values that
103
+ * differ only in key order encode identically, so the conflict rule never
104
+ * fires on serialization noise and the fold's stored value is stable.
105
+ */
106
+ declare function canonicalRecordJson(value: unknown): string;
107
+ /** The result shape a `safeParse`-style validator returns. `zod`'s schemas
108
+ * satisfy this structurally, so a consumer passes its zod schema directly and
109
+ * this module takes no schema-library dependency. */
110
+ type RecordParseResult = {
111
+ success: true;
112
+ data: unknown;
113
+ } | {
114
+ success: false;
115
+ error: unknown;
116
+ };
117
+ /** Something that can validate one value for one path: a `safeParse` object
118
+ * (zod and friends) or a plain function returning a typed outcome. */
119
+ type RecordValueValidator = {
120
+ safeParse(value: unknown): RecordParseResult;
121
+ } | ((value: unknown) => RecordOutcome<unknown>);
122
+ /**
123
+ * Path → validator. The KEY SET is the write allowlist: a path absent from the
124
+ * map is rejected with `unknown-path`, so nothing the consumer's fold cannot
125
+ * type-check ever reaches storage.
126
+ */
127
+ type RecordSchemaMap = Readonly<Record<string, RecordValueValidator>>;
128
+ /** Run one validator, normalizing both forms to a typed outcome and flattening
129
+ * a `safeParse` error into a readable message. */
130
+ declare function validateRecordValue(validator: RecordValueValidator, value: unknown): RecordOutcome<unknown>;
131
+ /**
132
+ * How a live accepted head at the same key is compared against an incoming
133
+ * write. Returning `true` means the two assertions genuinely disagree.
134
+ */
135
+ type RecordMaterialDifference = (head: {
136
+ sourceKind: string;
137
+ valueJson: string;
138
+ affirmedEmpty: boolean;
139
+ }, incoming: {
140
+ sourceKind: string;
141
+ valueJson: string;
142
+ affirmedEmpty: boolean;
143
+ }) => boolean;
144
+ /**
145
+ * The default rule, and the one all three hand-rolled stores converged on:
146
+ * two assertions materially differ when they come from DIFFERENT source kinds
147
+ * and encode to different canonical JSON. A restatement from the same source
148
+ * kind is a refresh, not a disagreement; an identical value from another
149
+ * source kind is corroboration.
150
+ */
151
+ declare const defaultRecordMaterialDifference: RecordMaterialDifference;
152
+ /** Canonicalize a key column before it enters the fold key (upper-casing a
153
+ * region code, trimming an identifier). Rejecting is fail-loud, never a
154
+ * silent rewrite to a sentinel. */
155
+ type RecordKeyCanonicalizer = (path: string, raw: string) => RecordOutcome<string>;
156
+ /**
157
+ * Everything domain-specific about writing an entry, supplied by the consumer.
158
+ * The store holds no defaults for any of it except the conflict rule.
159
+ */
160
+ interface RecordWritePolicy {
161
+ /** Path → validator; the key set is the write allowlist. */
162
+ schemas: RecordSchemaMap;
163
+ /**
164
+ * Paths that accept a negative assertion (`affirmedEmpty`) — "there are none
165
+ * of these". These are typically COLLECTION paths that carry no value of
166
+ * their own, so they are deliberately separate from {@link schemas}.
167
+ */
168
+ affirmablePaths?: readonly string[];
169
+ /**
170
+ * Source kind → the review state a write from it lands in. The key set is
171
+ * the source-kind allowlist: an unlisted kind is rejected. This is where a
172
+ * product says "a value the user typed is accepted; anything a model
173
+ * extracted is proposed".
174
+ */
175
+ reviewStateOnWrite: Readonly<Record<string, RecordReviewState>>;
176
+ /** Source kinds whose writes must carry a `sourceRef`. A citation store
177
+ * makes every extracting kind require one. */
178
+ requireSourceRef?: readonly string[];
179
+ /** Source kinds whose writes must carry a `sourceQuote`. */
180
+ requireSourceQuote?: readonly string[];
181
+ /**
182
+ * Source kind → product columns (declared through the table factory's
183
+ * `extraColumns`) whose value a write from that kind must supply.
184
+ *
185
+ * `requireSourceRef` can only require THE one built-in ref, which is not
186
+ * enough for a store whose kinds point at different tables — a chat-sourced
187
+ * row cites a message and a document-sourced row cites a document, each with
188
+ * its own foreign key. Declaring one column per kind and requiring it per
189
+ * kind is how that shape is expressed without the store learning either
190
+ * word.
191
+ */
192
+ requireExtras?: Readonly<Record<string, readonly string[]>>;
193
+ /** Canonicalize `itemKey` before it becomes part of the fold key. */
194
+ canonicalizeItemKey?: RecordKeyCanonicalizer;
195
+ /** Canonicalize `dimension` before it becomes part of the fold key. */
196
+ canonicalizeDimension?: RecordKeyCanonicalizer;
197
+ /** Override the conflict rule. Defaults to
198
+ * {@link defaultRecordMaterialDifference}. */
199
+ isMateriallyDifferent?: RecordMaterialDifference;
200
+ /** Lowest accepted period. Defaults to {@link RECORD_PERIOD_SENTINEL}. */
201
+ minPeriod?: number;
202
+ /** Highest accepted period. Defaults to `Number.MAX_SAFE_INTEGER`. */
203
+ maxPeriod?: number;
204
+ }
205
+ /** Resolve the review state a write from `sourceKind` lands in, failing loud
206
+ * on a kind the policy never declared. */
207
+ declare function resolveWriteReviewState(policy: RecordWritePolicy, sourceKind: string): RecordOutcome<RecordReviewState>;
208
+ /** True when the incoming write disagrees with the live head under the
209
+ * policy's rule (or the default). */
210
+ declare function detectRecordConflict(policy: RecordWritePolicy, head: {
211
+ sourceKind: string;
212
+ valueJson: string;
213
+ affirmedEmpty: boolean;
214
+ } | undefined, incoming: {
215
+ sourceKind: string;
216
+ valueJson: string;
217
+ affirmedEmpty: boolean;
218
+ }): boolean;
219
+
220
+ /**
221
+ * The fold: live entries in, one consumer-shaped object out.
222
+ *
223
+ * Pure and driver-free — the store loads rows and hands them here, and a test
224
+ * or an eval harness can call it with literals. Determinism is the contract:
225
+ * the result depends only on the CONTENT of the entries, never on the order
226
+ * they arrive in, because ordering is `seq` alone (with `id` as an unreachable
227
+ * tie-break — `(scope, seq)` is unique in storage). Nothing here reads a clock
228
+ * or a timestamp column, so two entries written in the same second still fold
229
+ * in a defined order.
230
+ *
231
+ * The consumer supplies the grouping rules: which paths carry forward across
232
+ * periods, how one entry applies to the accumulator, what a negative assertion
233
+ * retracts, and any derived values computed after the last entry.
234
+ */
235
+
236
+ /**
237
+ * How a path's entries resolve against the period being materialized.
238
+ *
239
+ * - `exact` — visible only at their own period. A value that was true for one
240
+ * period is structurally invisible to every other one.
241
+ * - `carry-forward` — visible at any period at or after their own, and only
242
+ * the newest such entry per key wins. Asserting a new value at a later
243
+ * period changes that period onward and can never rewrite an earlier one.
244
+ */
245
+ type RecordPeriodScope = 'exact' | 'carry-forward';
246
+ /** Resolves the period scope of one path. */
247
+ type RecordPeriodScopeResolver = (path: string) => RecordPeriodScope;
248
+ /** The scope assumed for every path when a consumer supplies no resolver. */
249
+ declare const defaultRecordPeriodScope: RecordPeriodScopeResolver;
250
+ /** The slice of a stored row the fold reads. */
251
+ interface FoldableRecordEntry {
252
+ id: string;
253
+ /** Per-scope monotonic write counter — the ONLY ordering key. */
254
+ seq: number;
255
+ dimension: string;
256
+ period: number;
257
+ path: string;
258
+ itemKey: string;
259
+ /** Canonical JSON produced by `canonicalRecordJson` on write. */
260
+ valueJson: string;
261
+ /** True when the entry asserts "there are none of these" at `path`. */
262
+ affirmedEmpty: boolean;
263
+ }
264
+ /** A resolved entry with its value already parsed, handed to the rules. */
265
+ interface DecodedRecordEntry extends FoldableRecordEntry {
266
+ /** `JSON.parse(valueJson)`; `null` on an `affirmedEmpty` entry. */
267
+ value: unknown;
268
+ }
269
+ /**
270
+ * The consumer's grouping rules. `T` is whatever shape the product folds into
271
+ * — a typed profile object, a keyed map, a list.
272
+ */
273
+ interface RecordFoldRules<T> {
274
+ /** Fresh accumulator for one fold. Must return a NEW object each call. */
275
+ init(): T;
276
+ /**
277
+ * Period scope for a path. Called for every entry, including paths that only
278
+ * ever appear as `affirmedEmpty` targets. Defaults to `'exact'` for every
279
+ * path when omitted, which is the narrower rule: an entry never leaks into a
280
+ * period it was not asserted for.
281
+ */
282
+ periodScope?: RecordPeriodScopeResolver;
283
+ /** Apply one entry to the accumulator. Fail loud: an entry the rules cannot
284
+ * place must reject the whole fold, never be skipped — a silently dropped
285
+ * entry shows a wrong number with a straight face. */
286
+ apply(draft: T, entry: DecodedRecordEntry): RecordOutcome<void>;
287
+ /** Apply a negative assertion. Runs at the entry's `seq`, so later entries
288
+ * at the same path repopulate. Omit it to reject `affirmedEmpty` entries. */
289
+ retract?(draft: T, entry: DecodedRecordEntry): RecordOutcome<void>;
290
+ /** Compute derived values after the last entry. */
291
+ finalize?(draft: T): RecordOutcome<void>;
292
+ }
293
+ /** Options for one fold. */
294
+ interface FoldRecordEntriesOptions<T> {
295
+ rules: RecordFoldRules<T>;
296
+ /** The period being materialized. Defaults to
297
+ * {@link RECORD_PERIOD_SENTINEL} for a record with no time dimension. */
298
+ period?: number;
299
+ }
300
+ /** What a fold produced. */
301
+ interface RecordFoldResult<T> {
302
+ value: T;
303
+ /** Entries that survived period resolution and were applied. */
304
+ entryCount: number;
305
+ }
306
+ /**
307
+ * True when an entry at `entryPeriod` is a candidate at `requestedPeriod`
308
+ * under `scope`. Carry-forward candidacy is necessary, not sufficient — only
309
+ * the newest candidate per key survives {@link foldRecordEntries}.
310
+ */
311
+ declare function recordEntryVisibleInPeriod(scope: RecordPeriodScope, entryPeriod: number, requestedPeriod: number): boolean;
312
+ /**
313
+ * Resolve entries against the requested period, then fold them in `seq` order.
314
+ *
315
+ * Callers may pass entries in any order and any mix of periods; the result is
316
+ * a function of their content alone.
317
+ */
318
+ declare function foldRecordEntries<T>(entries: readonly FoldableRecordEntry[], options: FoldRecordEntriesOptions<T>): RecordOutcome<RecordFoldResult<T>>;
319
+
320
+ export { recordOk as A, resolveWriteReviewState as B, validateRecordValue as C, type DecodedRecordEntry as D, type FoldRecordEntriesOptions as F, RECORD_KEY_SENTINEL as R, type FoldableRecordEntry as a, RECORD_PERIOD_SENTINEL as b, RECORD_REVIEW_STATES as c, type RecordEntryKey as d, type RecordErrorCode as e, type RecordFoldResult as f, type RecordFoldRules as g, type RecordKeyCanonicalizer as h, type RecordMaterialDifference as i, type RecordOutcome as j, type RecordParseResult as k, type RecordPeriodScope as l, type RecordPeriodScopeResolver as m, type RecordReviewState as n, type RecordSchemaMap as o, type RecordSourceLocator as p, type RecordValueValidator as q, type RecordWritePolicy as r, canonicalRecordJson as s, defaultRecordMaterialDifference as t, defaultRecordPeriodScope as u, detectRecordConflict as v, foldRecordEntries as w, recordEntryVisibleInPeriod as x, recordFail as y, recordKeyString as z };
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ LEGIBILITY_CHECKS,
4
+ checkLegibility,
5
+ formatLegibilityReport,
6
+ legibilityReportToJson
7
+ } from "../chunk-XEA5EG6P.js";
8
+
9
+ // src/legibility/cli.ts
10
+ import { existsSync } from "fs";
11
+ import { resolve } from "path";
12
+ import { pathToFileURL } from "url";
13
+
14
+ // src/legibility/cli-args.ts
15
+ var DEFAULT_CONFIG_FILE = "legibility.config.mjs";
16
+ var LegibilityUsageError = class extends Error {
17
+ };
18
+ var USAGE = [
19
+ "Usage: agent-app-legibility-check --src <dir> [--src <dir>\u2026] [--routes <file>] [--nav <file>\u2026]",
20
+ " [--ignore <substr>\u2026] [--skip <check>\u2026] [--config <file>]",
21
+ " [--json] [--list-suppressions]",
22
+ `Checks: ${LEGIBILITY_CHECKS.join(", ")}`
23
+ ].join("\n");
24
+ function parseArgs(argv) {
25
+ const out = {
26
+ srcDirs: [],
27
+ navFiles: [],
28
+ ignorePaths: [],
29
+ skip: [],
30
+ json: false,
31
+ listSuppressions: false,
32
+ help: false
33
+ };
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const flag = argv[i];
36
+ const take = () => {
37
+ const value = argv[++i];
38
+ if (value === void 0) throw new LegibilityUsageError(`${flag} needs a value`);
39
+ return value;
40
+ };
41
+ switch (flag) {
42
+ case "--src":
43
+ out.srcDirs.push(take());
44
+ break;
45
+ case "--routes":
46
+ out.routes = take();
47
+ break;
48
+ case "--nav":
49
+ out.navFiles.push(take());
50
+ break;
51
+ case "--ignore":
52
+ out.ignorePaths.push(take());
53
+ break;
54
+ case "--skip": {
55
+ const check = take();
56
+ if (!LEGIBILITY_CHECKS.includes(check)) {
57
+ throw new LegibilityUsageError(`--skip ${check} is not a check. Known: ${LEGIBILITY_CHECKS.join(", ")}`);
58
+ }
59
+ out.skip.push(check);
60
+ break;
61
+ }
62
+ case "--config":
63
+ out.config = take();
64
+ break;
65
+ case "--json":
66
+ out.json = true;
67
+ break;
68
+ case "--list-suppressions":
69
+ out.listSuppressions = true;
70
+ break;
71
+ case "-h":
72
+ case "--help":
73
+ out.help = true;
74
+ break;
75
+ default:
76
+ throw new LegibilityUsageError(`unknown argument: ${flag}`);
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+ function mergeConfig(fromFile, args) {
82
+ const checks = { ...fromFile.checks };
83
+ for (const check of args.skip) checks[check] = false;
84
+ const reachability = {
85
+ ...fromFile.reachability,
86
+ ...args.routes ? { routeConfigFile: args.routes } : {},
87
+ ...args.navFiles.length > 0 ? { navFiles: args.navFiles } : {}
88
+ };
89
+ return {
90
+ ...fromFile,
91
+ srcDirs: args.srcDirs.length > 0 ? args.srcDirs : fromFile.srcDirs ?? [],
92
+ ignorePaths: [...fromFile.ignorePaths ?? [], ...args.ignorePaths],
93
+ ...Object.keys(checks).length > 0 ? { checks } : {},
94
+ ...reachability.routeConfigFile || reachability.routePaths ? { reachability } : {}
95
+ };
96
+ }
97
+
98
+ // src/legibility/cli.ts
99
+ async function loadConfigFile(path) {
100
+ const explicit = path !== void 0;
101
+ const resolved = resolve(process.cwd(), path ?? DEFAULT_CONFIG_FILE);
102
+ if (!existsSync(resolved)) {
103
+ if (explicit) throw new LegibilityUsageError(`no config at ${resolved}`);
104
+ return {};
105
+ }
106
+ const module = await import(pathToFileURL(resolved).href);
107
+ const exported = module.default ?? module.config;
108
+ const value = typeof exported === "function" ? await exported() : exported;
109
+ if (value === null || typeof value !== "object") {
110
+ throw new LegibilityUsageError(`${resolved} must default-export a legibility config object`);
111
+ }
112
+ return value;
113
+ }
114
+ async function main() {
115
+ const args = parseArgs(process.argv.slice(2));
116
+ if (args.help) {
117
+ process.stdout.write(`${USAGE}
118
+ `);
119
+ return 0;
120
+ }
121
+ const config = mergeConfig(await loadConfigFile(args.config), args);
122
+ if (config.srcDirs.length === 0) {
123
+ throw new LegibilityUsageError("at least one --src <dir> is required (or srcDirs in the config file)");
124
+ }
125
+ const report = checkLegibility(config);
126
+ const text = args.json ? legibilityReportToJson(report) : formatLegibilityReport(report, { listSuppressions: args.listSuppressions });
127
+ if (report.ok) process.stdout.write(`${text}
128
+ `);
129
+ else process.stderr.write(`${text}
130
+ `);
131
+ return report.ok ? 0 : 1;
132
+ }
133
+ try {
134
+ process.exit(await main());
135
+ } catch (error) {
136
+ const message = error instanceof Error ? error.message : String(error);
137
+ process.stderr.write(`agent-app-legibility-check: ${message}
138
+ `);
139
+ if (error instanceof LegibilityUsageError) process.stderr.write(`${USAGE}
140
+ `);
141
+ process.exit(2);
142
+ }
143
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/legibility/cli.ts","../../src/legibility/cli-args.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-legibility-check` — fail a product's CI when a screen leaves its\n * reader guessing.\n *\n * Runs in the PRODUCT's repo, over the product's own source, next to typecheck:\n *\n * \"scripts\": {\n * \"legibility\": \"agent-app-legibility-check --src src --routes src/routes.ts --nav src/components/workspace-sidebar.tsx\"\n * }\n *\n * Flags (repeatable where a list makes sense):\n * --src <dir> source directory to scan (required unless the config supplies it)\n * --routes <file> react-router route config, for the unreachable-capability check\n * --nav <file> a file whose path literals are navigation entries\n * --ignore <substr> skip paths containing this substring\n * --skip <check> turn one check off wholesale (prefer a per-line suppression)\n * --config <file> a legibility.config.mjs default-exporting the config\n * (default: ./legibility.config.mjs when present)\n * --json print the report as JSON instead of text\n * --list-suppressions print every honoured suppression with its reason\n *\n * Exit 0 with no findings, 1 with findings, 2 on a usage or config error — the\n * same contract as `agent-app-preflight` and `agent-app-peer-check`.\n */\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { DEFAULT_CONFIG_FILE, LegibilityUsageError, mergeConfig, parseArgs, USAGE } from './cli-args'\nimport { checkLegibility } from './index'\nimport { formatLegibilityReport, legibilityReportToJson } from './report'\nimport type { LegibilityConfig } from './types'\n\nasync function loadConfigFile(path: string | undefined): Promise<Partial<LegibilityConfig>> {\n const explicit = path !== undefined\n const resolved = resolve(process.cwd(), path ?? DEFAULT_CONFIG_FILE)\n if (!existsSync(resolved)) {\n if (explicit) throw new LegibilityUsageError(`no config at ${resolved}`)\n return {}\n }\n const module: unknown = await import(pathToFileURL(resolved).href)\n const exported = (module as { default?: unknown; config?: unknown }).default ?? (module as { config?: unknown }).config\n const value = typeof exported === 'function' ? await (exported as () => Promise<unknown>)() : exported\n if (value === null || typeof value !== 'object') {\n throw new LegibilityUsageError(`${resolved} must default-export a legibility config object`)\n }\n return value as Partial<LegibilityConfig>\n}\n\nasync function main(): Promise<number> {\n const args = parseArgs(process.argv.slice(2))\n if (args.help) {\n process.stdout.write(`${USAGE}\\n`)\n return 0\n }\n\n const config = mergeConfig(await loadConfigFile(args.config), args)\n if (config.srcDirs.length === 0) {\n throw new LegibilityUsageError('at least one --src <dir> is required (or srcDirs in the config file)')\n }\n\n const report = checkLegibility(config)\n const text = args.json\n ? legibilityReportToJson(report)\n : formatLegibilityReport(report, { listSuppressions: args.listSuppressions })\n\n if (report.ok) process.stdout.write(`${text}\\n`)\n else process.stderr.write(`${text}\\n`)\n return report.ok ? 0 : 1\n}\n\ntry {\n process.exit(await main())\n} catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n process.stderr.write(`agent-app-legibility-check: ${message}\\n`)\n if (error instanceof LegibilityUsageError) process.stderr.write(`${USAGE}\\n`)\n process.exit(2)\n}\n","/**\n * The bin's argument and config layer, split from `cli.ts` so it can be tested\n * without executing a `main()` that calls `process.exit`.\n *\n * Errors are thrown as {@link LegibilityUsageError} rather than exiting here:\n * exiting is the bin's job, and a parser that exits cannot be exercised.\n */\n\nimport { LEGIBILITY_CHECKS, type LegibilityCheckId, type LegibilityConfig } from './types'\n\nexport const DEFAULT_CONFIG_FILE = 'legibility.config.mjs'\n\n/** A usage or config problem — exit code 2, never a finding. */\nexport class LegibilityUsageError extends Error {}\n\nexport interface ParsedArgs {\n srcDirs: string[]\n navFiles: string[]\n ignorePaths: string[]\n skip: LegibilityCheckId[]\n routes?: string\n config?: string\n json: boolean\n listSuppressions: boolean\n help: boolean\n}\n\nexport const USAGE = [\n 'Usage: agent-app-legibility-check --src <dir> [--src <dir>…] [--routes <file>] [--nav <file>…]',\n ' [--ignore <substr>…] [--skip <check>…] [--config <file>]',\n ' [--json] [--list-suppressions]',\n `Checks: ${LEGIBILITY_CHECKS.join(', ')}`,\n].join('\\n')\n\nexport function parseArgs(argv: readonly string[]): ParsedArgs {\n const out: ParsedArgs = {\n srcDirs: [],\n navFiles: [],\n ignorePaths: [],\n skip: [],\n json: false,\n listSuppressions: false,\n help: false,\n }\n for (let i = 0; i < argv.length; i++) {\n const flag = argv[i]\n const take = (): string => {\n const value = argv[++i]\n if (value === undefined) throw new LegibilityUsageError(`${flag} needs a value`)\n return value\n }\n switch (flag) {\n case '--src':\n out.srcDirs.push(take())\n break\n case '--routes':\n out.routes = take()\n break\n case '--nav':\n out.navFiles.push(take())\n break\n case '--ignore':\n out.ignorePaths.push(take())\n break\n case '--skip': {\n const check = take()\n if (!LEGIBILITY_CHECKS.includes(check as LegibilityCheckId)) {\n throw new LegibilityUsageError(`--skip ${check} is not a check. Known: ${LEGIBILITY_CHECKS.join(', ')}`)\n }\n out.skip.push(check as LegibilityCheckId)\n break\n }\n case '--config':\n out.config = take()\n break\n case '--json':\n out.json = true\n break\n case '--list-suppressions':\n out.listSuppressions = true\n break\n case '-h':\n case '--help':\n out.help = true\n break\n default:\n throw new LegibilityUsageError(`unknown argument: ${flag}`)\n }\n }\n return out\n}\n\n/**\n * Merge a config file with the flags. Flags WIN, so a one-off CI invocation can\n * narrow a run without editing the committed config.\n */\nexport function mergeConfig(fromFile: Partial<LegibilityConfig>, args: ParsedArgs): LegibilityConfig {\n const checks: Partial<Record<LegibilityCheckId, boolean>> = { ...fromFile.checks }\n for (const check of args.skip) checks[check] = false\n\n const reachability = {\n ...fromFile.reachability,\n ...(args.routes ? { routeConfigFile: args.routes } : {}),\n ...(args.navFiles.length > 0 ? { navFiles: args.navFiles } : {}),\n }\n\n return {\n ...fromFile,\n srcDirs: args.srcDirs.length > 0 ? args.srcDirs : (fromFile.srcDirs ?? []),\n ignorePaths: [...(fromFile.ignorePaths ?? []), ...args.ignorePaths],\n ...(Object.keys(checks).length > 0 ? { checks } : {}),\n ...(reachability.routeConfigFile || reachability.routePaths ? { reachability } : {}),\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;AClBvB,IAAM,sBAAsB;AAG5B,IAAM,uBAAN,cAAmC,MAAM;AAAC;AAc1C,IAAM,QAAQ;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW,kBAAkB,KAAK,IAAI,CAAC;AACzC,EAAE,KAAK,IAAI;AAEJ,SAAS,UAAU,MAAqC;AAC7D,QAAM,MAAkB;AAAA,IACtB,SAAS,CAAC;AAAA,IACV,UAAU,CAAC;AAAA,IACX,aAAa,CAAC;AAAA,IACd,MAAM,CAAC;AAAA,IACP,MAAM;AAAA,IACN,kBAAkB;AAAA,IAClB,MAAM;AAAA,EACR;AACA,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,OAAO,KAAK,CAAC;AACnB,UAAM,OAAO,MAAc;AACzB,YAAM,QAAQ,KAAK,EAAE,CAAC;AACtB,UAAI,UAAU,OAAW,OAAM,IAAI,qBAAqB,GAAG,IAAI,gBAAgB;AAC/E,aAAO;AAAA,IACT;AACA,YAAQ,MAAM;AAAA,MACZ,KAAK;AACH,YAAI,QAAQ,KAAK,KAAK,CAA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