@intentic/fileq 1.430.0 → 1.432.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 (69) hide show
  1. package/NOTICE +58 -1
  2. package/README.md +29 -1
  3. package/bin/fileq-rg-pre +6 -2
  4. package/dist/app.d.ts.map +1 -1
  5. package/dist/app.js +4 -1
  6. package/dist/app.js.map +1 -1
  7. package/dist/commands/check.command.d.ts.map +1 -1
  8. package/dist/commands/check.command.js +12 -5
  9. package/dist/commands/check.command.js.map +1 -1
  10. package/dist/commands/derive.command.d.ts.map +1 -1
  11. package/dist/commands/derive.command.js +3 -2
  12. package/dist/commands/derive.command.js.map +1 -1
  13. package/dist/commands/read.command.d.ts.map +1 -1
  14. package/dist/commands/read.command.js +42 -7
  15. package/dist/commands/read.command.js.map +1 -1
  16. package/dist/commands/render.command.d.ts.map +1 -1
  17. package/dist/commands/render.command.js +23 -10
  18. package/dist/commands/render.command.js.map +1 -1
  19. package/dist/lib/derivers/docx-math-symbols.d.ts +14 -0
  20. package/dist/lib/derivers/docx-math-symbols.d.ts.map +1 -0
  21. package/dist/lib/derivers/docx-math-symbols.js +160 -0
  22. package/dist/lib/derivers/docx-math-symbols.js.map +1 -0
  23. package/dist/lib/derivers/docx-math.d.ts +15 -0
  24. package/dist/lib/derivers/docx-math.d.ts.map +1 -0
  25. package/dist/lib/derivers/docx-math.js +252 -0
  26. package/dist/lib/derivers/docx-math.js.map +1 -0
  27. package/dist/lib/derivers/docx.d.ts.map +1 -1
  28. package/dist/lib/derivers/docx.js +3 -2
  29. package/dist/lib/derivers/docx.js.map +1 -1
  30. package/dist/lib/derivers/pdf-furniture.d.ts.map +1 -1
  31. package/dist/lib/derivers/pdf-furniture.js +3 -0
  32. package/dist/lib/derivers/pdf-furniture.js.map +1 -1
  33. package/dist/lib/derivers/pdf-tables.d.ts +9 -0
  34. package/dist/lib/derivers/pdf-tables.d.ts.map +1 -0
  35. package/dist/lib/derivers/pdf-tables.js +319 -0
  36. package/dist/lib/derivers/pdf-tables.js.map +1 -0
  37. package/dist/lib/derivers/pdf.d.ts.map +1 -1
  38. package/dist/lib/derivers/pdf.js +77 -38
  39. package/dist/lib/derivers/pdf.js.map +1 -1
  40. package/dist/lib/ocr-slots.d.ts +8 -0
  41. package/dist/lib/ocr-slots.d.ts.map +1 -0
  42. package/dist/lib/ocr-slots.js +35 -0
  43. package/dist/lib/ocr-slots.js.map +1 -0
  44. package/dist/skill.d.ts.map +1 -1
  45. package/dist/skill.js +7 -2
  46. package/dist/skill.js.map +1 -1
  47. package/package.json +7 -7
  48. package/src/app.ts +4 -1
  49. package/src/cli.integration.test.ts +30 -8
  50. package/src/commands/check.command.ts +20 -5
  51. package/src/commands/derive.command.ts +3 -2
  52. package/src/commands/read.command.ts +56 -8
  53. package/src/commands/render.command.ts +33 -11
  54. package/src/derivers.integration.test.ts +131 -11
  55. package/src/lib/derivers/docx-math-symbols.ts +197 -0
  56. package/src/lib/derivers/docx-math.test.ts +131 -0
  57. package/src/lib/derivers/docx-math.ts +355 -0
  58. package/src/lib/derivers/docx.ts +5 -3
  59. package/src/lib/derivers/image.ts +2 -2
  60. package/src/lib/derivers/pdf-furniture.test.ts +9 -0
  61. package/src/lib/derivers/pdf-furniture.ts +5 -0
  62. package/src/lib/derivers/pdf-tables.test.ts +292 -0
  63. package/src/lib/derivers/pdf-tables.ts +465 -0
  64. package/src/lib/derivers/pdf.ts +94 -40
  65. package/src/lib/ocr-slots.integration.test.ts +64 -0
  66. package/src/lib/ocr-slots.ts +61 -0
  67. package/src/lib/sidecar.ts +1 -1
  68. package/src/render.integration.test.ts +5 -4
  69. package/src/skill.ts +10 -5
package/dist/skill.js CHANGED
@@ -60,7 +60,9 @@ cached by content, so a repeat read of unchanged content is instant.
60
60
  ## Read a file
61
61
  \`fileq <file>\` (or \`fileq read <file> --budget 8000\`)
62
62
  - Prints a capsule (format, token cost), the content up to the budget, and \`saved:\` — the markdown file
63
- carrying the whole thing. Over budget, the cut is announced with that exact path to Read.
63
+ carrying the whole thing. Over budget, the last line says where the rest starts: \`[cut at line 212 of 1480,
64
+ ~19,100 of 23,100 tokens left: continue with Read <file> from line 212, or raise --budget]\`. Read that file
65
+ from that line rather than from the top.
64
66
  - Formats: docx and odt (headings, lists, tables), xlsx (capped tables), pptx (slides + speaker notes),
65
67
  pdf (text layer; ${OCR_FORMAT[host]}, and the note says the words are
66
68
  recognised, not exact), epub (chapters in reading order), ipynb (cells, fenced code, capped outputs),
@@ -82,7 +84,10 @@ ${OCR_REFUSAL[host]}
82
84
  - Plain text (md, csv, txt, code) is not fileq's business: Read it directly — but see below for the big ones.
83
85
  - Web pages belong to \`webq\`; images for a vision model belong to the Read tool, which shows the pixels.
84
86
 
85
- ${SEARCH[host]}${host === "sandbox" ? TEXTCONV : ""}Exit codes: 0 content, 1 nothing derivable, 2 broken invocation or install.
87
+ ${SEARCH[host]}${host === "sandbox" ? TEXTCONV : ""}Exit codes: 0 content, 1 nothing derivable, 2 broken invocation or install. A failure is one line,
88
+ \`fileq: error: <code>: <message>\`, often followed by \`fileq: next: <step>\`: do the step. The codes are
89
+ \`usage\`, \`not_found\`, \`unsupported\`, \`too_large\`, \`unreadable\` (damaged, locked or password-protected),
90
+ \`missing_tool\`, \`broken_install\` and \`internal\`; the last two are fileq's fault, never an empty document.
86
91
 
87
92
  ## After you produce a document
88
93
  A deck, report, spreadsheet or PDF made for someone is not finished until you have checked it and looked at it.
package/dist/skill.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"skill.js","sourceRoot":"","sources":["../src/skill.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAavD,MAAM,UAAU,GAA2C;IACvD,OAAO,EAAE,gFAAgF;IACzF,UAAU,EAAE,kDAAkD;CACjE,CAAC;AAEF,MAAM,WAAW,GAA2C;IACxD,OAAO,EAAE;;;+FAGkF;IAC3F,UAAU,EAAE;;;kEAGkD;CACjE,CAAC;AAKF,MAAM,YAAY,GAAG;IACjB,OAAO,EAAE;;4GAE+F;IACxG,UAAU,EAAE;2GAC2F;CACzD,CAAC;AAGnD,MAAM,QAAQ,GAAG;;;;;CAKhB,CAAC;AAKF,MAAM,MAAM,GAAG;IACX,OAAO,EAAE;;;;;;;;;;;CAWZ;IACG,UAAU,EAAE;;;;;CAKf;CACiD,CAAC;AAEnD,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,EAAE,IAAI,EAAkB,EAAU,EAAE,CAAC;;;;;;;;;;;;;;;qBAe3C,UAAU,CAAC,IAAI,CAAC;;;;;;;;;;;;+EAY0C,WAAW;;;;EAIxF,WAAW,CAAC,IAAI,CAAC;;;;EAIjB,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE;;;;;;;;;;;KAW9C,YAAY,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC;;;;EAI/C,eAAe;;;;;;;;;;;;;;;;;;;;CAoBhB,CAAC"}
1
+ {"version":3,"file":"skill.js","sourceRoot":"","sources":["../src/skill.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAavD,MAAM,UAAU,GAA2C;IACvD,OAAO,EAAE,gFAAgF;IACzF,UAAU,EAAE,kDAAkD;CACjE,CAAC;AAEF,MAAM,WAAW,GAA2C;IACxD,OAAO,EAAE;;;+FAGkF;IAC3F,UAAU,EAAE;;;kEAGkD;CACjE,CAAC;AAKF,MAAM,YAAY,GAAG;IACjB,OAAO,EAAE;;4GAE+F;IACxG,UAAU,EAAE;2GAC2F;CACzD,CAAC;AAGnD,MAAM,QAAQ,GAAG;;;;;CAKhB,CAAC;AAKF,MAAM,MAAM,GAAG;IACX,OAAO,EAAE;;;;;;;;;;;CAWZ;IACG,UAAU,EAAE;;;;;CAKf;CACiD,CAAC;AAEnD,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,EAAE,IAAI,EAAkB,EAAU,EAAE,CAAC;;;;;;;;;;;;;;;;;qBAiB3C,UAAU,CAAC,IAAI,CAAC;;;;;;;;;;;;+EAY0C,WAAW;;;;EAIxF,WAAW,CAAC,IAAI,CAAC;;;;EAIjB,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE;;;;;;;;;;;;;;KAc9C,YAAY,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC;;;;EAI/C,eAAe;;;;;;;;;;;;;;;;;;;;CAoBhB,CAAC"}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@intentic/fileq",
3
- "version": "1.430.0",
3
+ "version": "1.432.0",
4
4
  "description": "fileq, agent-native file reading: any binary workspace file (docx, xlsx, pptx, pdf, images, audio, archives) as clean budgeted markdown, cached by content so a repeat read is instant",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/intentic/intentic.git",
10
- "directory": "_sandbox/fileq"
10
+ "directory": "_agent-tools/fileq"
11
11
  },
12
12
  "files": [
13
13
  "bin",
@@ -73,11 +73,11 @@
73
73
  }
74
74
  },
75
75
  "dependencies": {
76
- "@intentic/agent-cli": "1.430.0",
77
- "@intentic/base": "1.430.0",
78
- "@intentic/constants": "1.430.0",
79
- "@intentic/webq": "1.430.0",
80
- "@intentic/workspace-ignore": "1.430.0",
76
+ "@intentic/agent-cli": "1.432.0",
77
+ "@intentic/base": "1.432.0",
78
+ "@intentic/constants": "1.432.0",
79
+ "@intentic/webq": "1.432.0",
80
+ "@intentic/workspace-ignore": "1.432.0",
81
81
  "@stricli/core": "1.3.0",
82
82
  "exifr": "7.1.3",
83
83
  "fflate": "0.8.3",
package/src/app.ts CHANGED
@@ -41,7 +41,10 @@ Not fileq's business: plain text (read it directly), the open web (webq),
41
41
  files needing OCR or transcription (later tiers say so in their sidecars).
42
42
 
43
43
  Exit codes: 0 content, 1 nothing derivable (check: an error found), 2 broken
44
- invocation or install (render: a tool it needs is missing).`;
44
+ invocation or install (render: a tool it needs is missing). A failure is one
45
+ line, \`fileq: error: <code>: <message>\` (usage, not_found, unsupported,
46
+ too_large, unreadable, missing_tool, internal), then \`fileq: next: <step>\`.
47
+ A cut read ends with the saved file's line to continue from.`;
45
48
 
46
49
  export const app = buildApplication(
47
50
  buildRouteMap({
@@ -115,12 +115,19 @@ describe("read", () => {
115
115
  expect(out).toContain(sidecarOf("notes.docx"));
116
116
  });
117
117
 
118
- it("clips at the budget and points at the sidecar for the rest", async () => {
118
+ it("clips at the budget and names the sidecar line the rest starts on", async () => {
119
119
  const long = Array.from({ length: 200 }, (_, i) => `Paragraph ${i} with a good number of words in it to cost tokens.`);
120
120
  writeFileSync(join(root, "long.docx"), docxBytes("Long", long));
121
121
  const { out } = await fileq("read", join(root, "long.docx"), "--budget", "100");
122
- expect(out).toContain("[cut at 100 of");
123
- expect(out).toContain("for the whole document]");
122
+ const resume = Number(/ from line (\d+), or raise --budget\]\n$/.exec(out)?.[1]);
123
+ expect(out).toContain(`continue with Read ${sidecarOf("long.docx")} from line ${resume}, or raise --budget]`);
124
+ // What was printed is the sidecar's body from its first line, and the line named is the first one left out.
125
+ const printed = out.slice(out.indexOf("\n---\n") + 5, out.indexOf("\n[cut ")).split("\n").slice(0, -1);
126
+ const sidecar = readFileSync(sidecarOf("long.docx"), "utf8").split("\n");
127
+ const firstLine = resume - printed.length;
128
+ expect(sidecar[firstLine - 2]).toBe("---");
129
+ expect(sidecar.slice(firstLine - 1, resume - 1)).toEqual(printed);
130
+ expect(out).toContain(`[cut at line ${resume} of ${sidecar.length - 1}, ~`);
124
131
  });
125
132
 
126
133
  it("--plain prints the markdown alone, whole, with no capsule to strip", async () => {
@@ -152,11 +159,23 @@ describe("read", () => {
152
159
  expect(out).toContain("fileq:");
153
160
  });
154
161
 
155
- it("answers 1, not a stack, for a file nothing derives", async () => {
162
+ it("answers 1, not a stack, for a file nothing derives, with the code and where the formats are listed", async () => {
156
163
  writeFileSync(join(root, "data.bin"), Buffer.from([0, 1, 2, 3]));
157
164
  const { out, exitCode } = await fileq("read", join(root, "data.bin"));
158
165
  expect(exitCode).toBe(1);
159
- expect(out).toContain("unsupported");
166
+ expect(out).toBe("fileq: error: unsupported: cannot read data.bin: unsupported\nfileq: next: fileq --help lists the formats it reads; read a text file directly\n");
167
+ });
168
+
169
+ it("a path that is not there is not_found, with where to look", async () => {
170
+ const { out, exitCode } = await fileq("read", join(root, "nowhere.docx"));
171
+ expect(exitCode).toBe(1);
172
+ expect(out).toBe(`fileq: error: not_found: cannot read nowhere.docx: missing\nfileq: next: ls ${root}\n`);
173
+ });
174
+
175
+ it("a mistyped flag is a usage error pointing at the verb's help", async () => {
176
+ const { err, exitCode } = await fileq("read", join(root, "notes.docx"), "--budgt", "5");
177
+ expect(exitCode).toBe(2);
178
+ expect(err).toBe("fileq: error: usage: No flag registered for --budgt, did you mean --budget?\nfileq: next: fileq read --help\n");
160
179
  });
161
180
 
162
181
  it("answers 1 with the reason, not a stack, for a corrupt file outside the workspace", async () => {
@@ -164,7 +183,7 @@ describe("read", () => {
164
183
  writeFileSync(join(outside, "broken.ipynb"), "{ this is not json");
165
184
  const { out, exitCode } = await fileq("read", join(outside, "broken.ipynb"));
166
185
  expect(exitCode).toBe(1);
167
- expect(out).toContain("derive-failed (ipynb)");
186
+ expect(out).toContain(`fileq: error: unreadable: cannot read ${join(outside, "broken.ipynb")}: derive-failed (ipynb)`);
168
187
  expect(out).not.toContain(" at ");
169
188
  rmSync(outside, { recursive: true, force: true });
170
189
  });
@@ -278,10 +297,13 @@ describe("check", () => {
278
297
  writeFileSync(join(root, "picture.png"), pngBytes());
279
298
  const unsupported = await fileq("check", join(root, "picture.png"));
280
299
  expect(unsupported.exitCode).toBe(2);
281
- expect(unsupported.out).toBe(`fileq: cannot check ${join(root, "picture.png")}: fileq check reads docx, pptx, xlsx, pdf; this is image (fileq read shows what it holds)\n`);
300
+ expect(unsupported.out).toBe(
301
+ `fileq: error: unsupported: cannot check ${join(root, "picture.png")}: fileq check reads docx, pptx, xlsx, pdf; this is image\n` +
302
+ `fileq: next: fileq read ${join(root, "picture.png")} shows what it holds\n`,
303
+ );
282
304
  const missing = await fileq("check", join(root, "nowhere.docx"));
283
305
  expect(missing.exitCode).toBe(2);
284
- expect(missing.out).toBe(`fileq: cannot check ${join(root, "nowhere.docx")}: no such file\n`);
306
+ expect(missing.out).toBe(`fileq: error: not_found: cannot check ${join(root, "nowhere.docx")}: no such file\nfileq: next: ls ${root}\n`);
285
307
  });
286
308
 
287
309
  it("a file with a document's extension that is not one gets that format's answer", async () => {
@@ -1,5 +1,6 @@
1
1
  /* `fileq check <file>`: a document's structural problems, each with where it is, so an agent can fix what it produced before a person opens it. */
2
- import { basename, resolve } from "node:path";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { failure, shellWord } from "@intentic/agent-cli/errors";
3
4
  import { capsule } from "@intentic/agent-cli/output";
4
5
  import { neutralizeOutsideText } from "@intentic/base/outside-text";
5
6
  import { buildCommand, type CommandContext } from "@stricli/core";
@@ -49,6 +50,15 @@ const tally = (report: CheckReport): string => {
49
50
  return [errors > 0 ? counted(errors, "error") : "", warnings > 0 ? counted(warnings, "warning") : ""].filter((part) => part !== "").join(", ");
50
51
  };
51
52
 
53
+ // check.ts's reasons: `no such file`, `N MB is over the M MB a check reads`, or what opening it threw.
54
+ const unreadable = (absPath: string, reason: string): string => {
55
+ const message = `cannot check ${absPath}: ${reason}`;
56
+ if (reason === "no such file") {
57
+ return failure("fileq", "not_found", message, `ls ${shellWord(dirname(absPath))}`);
58
+ }
59
+ return failure("fileq", / MB is over the /.test(reason) ? "too_large" : "unreadable", message);
60
+ };
61
+
52
62
  export const checkCommand = buildCommand({
53
63
  docs: { brief: "Lint a docx, pptx, xlsx or pdf for problems a reader would meet; exit 1 on any error" },
54
64
  parameters: {
@@ -67,11 +77,16 @@ export const checkCommand = buildCommand({
67
77
  const { CHECKABLE, checkFile } = await import("../lib/check/check.js");
68
78
  const outcome = await checkFile(absPath);
69
79
  if (outcome.kind !== "checked") {
70
- const reason =
80
+ this.process.stdout.write(
71
81
  outcome.kind === "unreadable"
72
- ? outcome.reason
73
- : `fileq check reads ${CHECKABLE.join(", ")}; this is ${outcome.format ?? "none of them"} (fileq read shows what it holds)`;
74
- this.process.stdout.write(`fileq: cannot check ${absPath}: ${reason}\n`);
82
+ ? unreadable(absPath, outcome.reason)
83
+ : failure(
84
+ "fileq",
85
+ "unsupported",
86
+ `cannot check ${absPath}: fileq check reads ${CHECKABLE.join(", ")}; this is ${outcome.format ?? "none of them"}`,
87
+ `fileq read ${shellWord(file)} shows what it holds`,
88
+ ),
89
+ );
75
90
  process.exitCode = 2;
76
91
  return;
77
92
  }
@@ -1,5 +1,6 @@
1
1
  /* `fileq derive` derives metadata from one input file. */
2
2
  import { resolve } from "node:path";
3
+ import { failure } from "@intentic/agent-cli/errors";
3
4
  import { countParser } from "@intentic/agent-cli/flags";
4
5
  import { buildCommand, type CommandContext } from "@stricli/core";
5
6
  import { ensureSidecar, type Outcome } from "../lib/derive.js";
@@ -40,12 +41,12 @@ export const deriveCommand = buildCommand({
40
41
  async func(this: CommandContext, flags: DeriveFlags, ...files: string[]) {
41
42
  const root = workspaceRoot();
42
43
  if (root === undefined) {
43
- this.process.stdout.write("fileq: derive needs a workspace (WORKSPACE_ROOT is not set); use `fileq read` for one-off files\n");
44
+ this.process.stdout.write(failure("fileq", "usage", "derive needs a workspace (WORKSPACE_ROOT is not set)", "fileq read <file> reads a one-off file"));
44
45
  process.exitCode = 2;
45
46
  return;
46
47
  }
47
48
  if (files.length === 0) {
48
- this.process.stdout.write("fileq: derive takes file paths\n");
49
+ this.process.stdout.write(failure("fileq", "usage", "derive takes file paths", "fileq derive <file…>"));
49
50
  process.exitCode = 2;
50
51
  return;
51
52
  }
@@ -1,7 +1,10 @@
1
1
  /* `fileq read <file>` (also the default command): one file as markdown — a capsule line saying what happened, the content up to a token budget; `--plain` is the body alone, whole, for a program (git's textconv) rather than an agent. */
2
- import { basename, resolve } from "node:path";
2
+ import { existsSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { basename, dirname, resolve } from "node:path";
5
+ import { type ErrorCode, failure, shellWord } from "@intentic/agent-cli/errors";
3
6
  import { countParser } from "@intentic/agent-cli/flags";
4
- import { capsule, clip } from "@intentic/agent-cli/output";
7
+ import { capsule, clip, type Whole } from "@intentic/agent-cli/output";
5
8
  import { estimateTokens } from "@intentic/base/format";
6
9
  import { buildCommand, type CommandContext } from "@stricli/core";
7
10
  import { deriverStamp } from "../lib/derivers/deriver.js";
@@ -52,9 +55,9 @@ export const readCommand = buildCommand({
52
55
  this.process.stdout.write(`saved: ${result.savedPath}\n`);
53
56
  }
54
57
  if (flags.budget > 0 && result.body !== "") {
55
- const whole = result.savedPath ?? `the output of \`fileq read --plain ${absPath}\``;
58
+ const { body, whole } = await printable(result, absPath);
56
59
  this.process.stdout.write("---\n");
57
- this.process.stdout.write(withFinalNewline(clip(result.body, flags.budget, whole, "document")));
60
+ this.process.stdout.write(withFinalNewline(clip(body, flags.budget, whole)));
58
61
  }
59
62
  },
60
63
  });
@@ -79,10 +82,10 @@ const readInWorkspace = async (root: string, absPath: string): Promise<ReadResul
79
82
  if (outcome.kind === "skipped" && (outcome.reason === "outside-workspace" || outcome.reason === "ignored-path")) {
80
83
  return readOutsideWorkspace(root, absPath);
81
84
  }
82
- return fromOutcome(outcome);
85
+ return fromOutcome(outcome, absPath);
83
86
  };
84
87
 
85
- const fromOutcome = (outcome: Outcome): ReadResult | undefined => {
88
+ const fromOutcome = async (outcome: Outcome, absPath: string): Promise<ReadResult | undefined> => {
86
89
  switch (outcome.kind) {
87
90
  case "derived":
88
91
  return {
@@ -108,18 +111,48 @@ const fromOutcome = (outcome: Outcome): ReadResult | undefined => {
108
111
  case "removed":
109
112
  case "skipped": {
110
113
  const reason = outcome.kind === "removed" ? "missing" : outcome.reason;
111
- process.stdout.write(`fileq: cannot read ${outcome.relPath}: ${reason}\n`);
114
+ process.stdout.write(await refusal(outcome.relPath, absPath, reason));
112
115
  return undefined;
113
116
  }
114
117
  }
115
118
  };
116
119
 
120
+ // Why a read failed, as a code and the step that gets further. The reasons are derive.ts's: `missing`, `unsupported`,
121
+ // `too-large (N MB)`, `unreadable (EACCES)`, `derive-failed (docx): …`. The daemon reads the reason back off the
122
+ // error line's `cannot read <path>: ` (_sandbox/sandbox/src/derived/derived-blob.ts), so that wording stays.
123
+ const refusal = async (shown: string, absPath: string, reason: string): Promise<string> => {
124
+ const [code, next] = await refusalKind(absPath, reason);
125
+ return failure("fileq", code, `cannot read ${shown}: ${reason}`, next);
126
+ };
127
+
128
+ const refusalKind = async (absPath: string, reason: string): Promise<readonly [ErrorCode, string | undefined]> => {
129
+ if (reason === "missing") {
130
+ return ["not_found", `ls ${shellWord(dirname(absPath))}`];
131
+ }
132
+ if (reason === "unsupported") {
133
+ return ["unsupported", "fileq --help lists the formats it reads; read a text file directly"];
134
+ }
135
+ if (reason.startsWith("too-large")) {
136
+ return ["too_large", undefined];
137
+ }
138
+ if (reason.startsWith("unreadable")) {
139
+ return ["unreadable", `ls -l ${shellWord(absPath)}`];
140
+ }
141
+ // A document that will not open: a check names what is wrong with it (damaged, password-protected), and is loaded
142
+ // only on this path.
143
+ const failed = /^derive-failed \((\w+)\)/.exec(reason)?.[1];
144
+ const { CHECKABLE } = await import("../lib/check/check.js");
145
+ return ["unreadable", CHECKABLE.some((format) => format === failed) ? `fileq check ${shellWord(absPath)}` : undefined];
146
+ };
147
+
117
148
  // A file outside the workspace has no sidecar: the content cache alone keeps its rendering, and its entry is what `saved:`
118
149
  // names, so git's textconv reading the same blob twice derives it once.
119
150
  const readOutsideWorkspace = async (root: string | undefined, absPath: string): Promise<ReadResult | undefined> => {
120
151
  const outcome = await renderByContent(root, absPath);
121
152
  if (outcome.kind === "failed") {
122
- process.stdout.write(`fileq: cannot read ${absPath}: ${outcome.reason}\n`);
153
+ // The content cache cannot tell a missing file from one in no format it reads; the file system can.
154
+ const reason = outcome.reason === "unsupported or missing" ? (existsSync(absPath) ? "unsupported" : "missing") : outcome.reason;
155
+ process.stdout.write(await refusal(absPath, absPath, reason));
123
156
  return undefined;
124
157
  }
125
158
  return {
@@ -134,5 +167,20 @@ const readOutsideWorkspace = async (root: string | undefined, absPath: string):
134
167
  };
135
168
  };
136
169
 
170
+ // The body to print and where its continuation is read: the saved rendering's own text below its front matter, so the
171
+ // line a cut names is the line that file shows there; `--plain`'s output when nothing was saved or it cannot be read back.
172
+ const printable = async (result: ReadResult, absPath: string): Promise<{ body: string; whole: Whole }> => {
173
+ // allow(silent-catch): a rendering that cannot be read back is still printed, from memory, with `--plain` as its rest.
174
+ const saved = result.savedPath === undefined ? undefined : await readFile(result.savedPath, "utf8").catch(() => undefined);
175
+ if (result.savedPath === undefined || saved === undefined) {
176
+ return { body: result.body, whole: { command: `fileq read --plain ${shellWord(absPath)}` } };
177
+ }
178
+ const fence = saved.startsWith("---\n") ? saved.indexOf("\n---\n", 4) : -1;
179
+ const start = fence === -1 ? 0 : fence + "\n---\n".length;
180
+ // The front matter's lines, plus one: the line the body starts on.
181
+ const firstLine = saved.slice(0, start).split("\n").length;
182
+ return { body: saved.slice(start), whole: { file: result.savedPath, firstLine } };
183
+ };
184
+
137
185
  // A document's last line is content, and a sidecar body need not end in a newline; a clipped one already does.
138
186
  const withFinalNewline = (text: string): string => (text.endsWith("\n") ? text : `${text}\n`);
@@ -1,8 +1,9 @@
1
1
  /* `fileq render <file>`: a document's pages (a deck's slides) as PNG files, one path per line, for an agent to look at with its image reader. */
2
2
  import { basename, resolve } from "node:path";
3
+ import { type ErrorCode, failure } from "@intentic/agent-cli/errors";
3
4
  import { countParser } from "@intentic/agent-cli/flags";
4
5
  import { capsule } from "@intentic/agent-cli/output";
5
- import { errorMessage } from "@intentic/base/errors";
6
+ import { errnoCode, errorMessage } from "@intentic/base/errors";
6
7
  import { buildCommand, type CommandContext } from "@stricli/core";
7
8
  import { workspaceRoot } from "../lib/env.js";
8
9
  import { ConvertFailed, ToolMissing } from "../lib/render/convert.js";
@@ -16,16 +17,37 @@ interface RenderFlags {
16
17
  readonly json: boolean;
17
18
  }
18
19
 
20
+ interface Failure {
21
+ readonly exit: number;
22
+ readonly code: ErrorCode;
23
+ readonly message: string;
24
+ readonly next?: string;
25
+ }
26
+
19
27
  // What went wrong, as the exit code the agent-CLI contract gives it: a missing tool or a bad flag is the invocation's
20
- // fault (2); a document that cannot be drawn is "nothing here" (1).
21
- const failure = (cause: unknown): { code: number; message: string } | undefined => {
22
- if (cause instanceof ToolMissing || cause instanceof BadPages) {
23
- return { code: 2, message: cause.message };
28
+ // fault (2); a document that cannot be drawn is "nothing here" (1). Anything else is fileq's own failure (2).
29
+ const failureOf = (cause: unknown): Failure => {
30
+ const message = errorMessage(cause);
31
+ if (cause instanceof ToolMissing) {
32
+ // convert.ts words it `<what is missing> … here: <how to get it>`; the second half is the step.
33
+ const at = message.indexOf(" here: ");
34
+ return at === -1
35
+ ? { exit: 2, code: "missing_tool", message }
36
+ : { exit: 2, code: "missing_tool", message: message.slice(0, at + " here".length), next: message.slice(at + " here: ".length) };
37
+ }
38
+ if (cause instanceof BadPages) {
39
+ return { exit: 2, code: "usage", message };
40
+ }
41
+ if (cause instanceof NotRenderable) {
42
+ return { exit: 1, code: "unsupported", message };
24
43
  }
25
- if (cause instanceof NotRenderable || cause instanceof ConvertFailed) {
26
- return { code: 1, message: cause.message };
44
+ if (cause instanceof ConvertFailed) {
45
+ return { exit: 1, code: "unreadable", message };
27
46
  }
28
- return undefined;
47
+ // A file system's refusal (an --out it cannot write) names itself; only a bug is worth reporting.
48
+ return errnoCode(cause) === undefined
49
+ ? { exit: 2, code: "internal", message, next: "this is fileq's own failure, not an empty answer: report it with the command that was run" }
50
+ : { exit: 2, code: "internal", message };
29
51
  };
30
52
 
31
53
  const summary = (file: string, result: RenderResult): string => {
@@ -62,9 +84,9 @@ export const renderCommand = buildCommand({
62
84
  const size = Math.max(64, Math.round(flags.size));
63
85
  result = await renderDocument({ absPath, pages, outDir: flags.out === undefined ? undefined : resolve(flags.out), size }, workspaceRoot());
64
86
  } catch (cause) {
65
- const known = failure(cause);
66
- this.process.stdout.write(`fileq: cannot render ${absPath}: ${known?.message ?? errorMessage(cause)}\n`);
67
- process.exitCode = known?.code ?? 2;
87
+ const failed = failureOf(cause);
88
+ this.process.stdout.write(failure("fileq", failed.code, `cannot render ${absPath}: ${failed.message}`, failed.next));
89
+ process.exitCode = failed.exit;
68
90
  return;
69
91
  }
70
92
  process.exitCode = result.images.length > 0 ? 0 : 1;
@@ -1,11 +1,13 @@
1
1
  /* Every deriver against a real file its real parser accepts, in a temp tree. */
2
2
  import { execFileSync, spawnSync } from "node:child_process";
3
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
4
5
  import { tmpdir } from "node:os";
5
6
  import { join } from "node:path";
6
7
  import { requires } from "@intentic/testing/requires";
7
8
  import { onPath } from "./lib/tools.js";
8
9
  import { archiveDeriver } from "./lib/derivers/archive.js";
10
+ import { mammothInput } from "./lib/derivers/docx-math.js";
9
11
  import { docxDeriver } from "./lib/derivers/docx.js";
10
12
  import { epubDeriver } from "./lib/derivers/epub.js";
11
13
  import { htmlDeriver } from "./lib/derivers/html.js";
@@ -22,6 +24,7 @@ import { rtfDeriver, rtfParagraphs } from "./lib/derivers/rtf.js";
22
24
  import { xlsxDeriver } from "./lib/derivers/xlsx.js";
23
25
  import { detectFormat } from "./lib/formats.js";
24
26
  import {
27
+ docxBodyBytes,
25
28
  docxBytes,
26
29
  epubBytes,
27
30
  gzipBytes,
@@ -68,6 +71,32 @@ describe("docx", () => {
68
71
  const path = fixture("plan2.docx", docxBytes("T", ["x"]));
69
72
  expect(await detectFormat(path)).toBe("docx");
70
73
  });
74
+
75
+ // The equations of markitdown's equations.docx (tests/test_files, MIT), one inline and two display, as Word writes
76
+ // them, its run properties left out.
77
+ const r = (text: string): string => `<m:r><m:t>${text}</m:t></m:r>`;
78
+ const fraction = (num: string, den: string): string => `<m:f><m:fPr/><m:num>${num}</m:num><m:den>${den}</m:den></m:f>`;
79
+ const EQUATIONS = [
80
+ `<w:p><w:r><w:t xml:space="preserve">For </w:t></w:r><m:oMath>${r("m")}${r("=1")}</m:oMath><w:r><w:t>,</w:t></w:r></w:p>`,
81
+ `<w:p><m:oMathPara><m:oMath>${r("sin\u2061")}${r("θ")}${r("=")}${fraction(r("mλ"), r("a"))}${r("=")}${fraction(
82
+ `${r("(1)")}<m:d><m:dPr/><m:e>${r("550×")}<m:sSup><m:e>${r("10")}</m:e><m:sup>${r("-6")}</m:sup></m:sSup>${r(" mm")}</m:e></m:d>`,
83
+ r("2.5 mm"),
84
+ )}</m:oMath></m:oMathPara></w:p>`,
85
+ `<w:p><w:r><w:t xml:space="preserve">The angle is </w:t></w:r><m:oMath>${r("θ=")}<m:sSup><m:e>${r("sin")}</m:e><m:sup>${r("-1")}</m:sup></m:sSup>${r("(2.2×10)")}</m:oMath><w:r><w:t>.</w:t></w:r></w:p>`,
86
+ ].join("");
87
+
88
+ test("equations read as LaTeX, $…$ inline and $$…$$ on their own, where mammoth alone dropped them", async () => {
89
+ const doc = await docxDeriver.derive(fixture("equations.docx", docxBodyBytes(EQUATIONS)));
90
+ expect(doc.markdown).toContain("For $m=1$,");
91
+ expect(doc.markdown).toContain("$$sinθ=\\frac{mλ}{a}=\\frac{(1)\\left(550×10^{-6} mm\\right)}{2.5 mm}$$");
92
+ expect(doc.markdown).toContain("The angle is $θ=sin^{-1}(2.2×10)$.");
93
+ expect(doc.notes.join(" ")).not.toContain("oMath");
94
+ });
95
+
96
+ test("a document without an equation reaches mammoth by its path, so it converts exactly as it always did", async () => {
97
+ const path = fixture("no-math.docx", docxBytes("Plain", ["No equations, though m=1 is written here."]));
98
+ expect(await mammothInput(path)).toEqual({ path });
99
+ });
71
100
  });
72
101
 
73
102
  describe("pptx", () => {
@@ -117,6 +146,81 @@ describe("xlsx", () => {
117
146
  });
118
147
  });
119
148
 
149
+ // markitdown's own PDF test files (fixtures/markitdown/ATTRIBUTION), read against the expectations of its
150
+ // tests/test_pdf_tables.py and test_pdf_masterformat.py.
151
+ const markitdown = (name: string): string => fileURLToPath(new URL(`../fixtures/markitdown/${name}`, import.meta.url));
152
+
153
+ // Each of `needles` found, in the order given.
154
+ const inOrder = (text: string, needles: readonly string[]): number[] => needles.map((needle) => text.indexOf(needle));
155
+
156
+ describe("pdf tables (markitdown's fixtures)", () => {
157
+ test("a borderless table keeps every value in its own column, between the prose around it", async () => {
158
+ const { markdown } = await pdfDeriver.derive(markitdown("SPARSE-2024-INV-1234_borderless_table.pdf"));
159
+ for (const header of ["Report ID: SPARSE-2024-INV-1234", "Warehouse: Distribution Center East", "Prepared By: Sarah Martinez"]) {
160
+ expect(markdown).toContain(header);
161
+ }
162
+ // Page 1's sparse rows: which column a value sits in is the whole of what it means.
163
+ expect(markdown).toContain(
164
+ [
165
+ "| Product Code | Location | Expected | Actual | Variance | Status |",
166
+ "| --- | --- | --- | --- | --- | --- |",
167
+ "| SKU-8847 | A-12 | 450 | | | |",
168
+ "| | B-07 | | 289 | -23 | |",
169
+ "| SKU-9201 | | 780 | 778 | | OK |",
170
+ "| | C-15 | | | +15 | |",
171
+ ].join("\n"),
172
+ );
173
+ // Page 2: "Critical" is a note, not a last audit date.
174
+ expect(markdown).toContain("| SKU-4563 | Software | $120.00 | $18,720.00 | | Critical |");
175
+ expect(markdown).toContain("| SKU-6678 | Software | $200.00 | $42,000.00 | 2024-10-25 | High Value |");
176
+ const positions = inOrder(markdown, [
177
+ "INVENTORY RECONCILIATION REPORT",
178
+ "| Product Code | Location",
179
+ "Variance Analysis:",
180
+ "## Page 2",
181
+ "Extended Inventory Review:",
182
+ "| Product Code | Category",
183
+ "Recommendations:",
184
+ ]);
185
+ expect(positions.every((position) => position >= 0)).toBe(true);
186
+ expect(positions).toEqual(positions.toSorted((a, b) => a - b));
187
+ expect(markdown.split("SKU-8847").length - 1).toBeLessThanOrEqual(4);
188
+ });
189
+
190
+ test("a booking order's tables come out whole, a wrapped title and a footer drawn across rows included", async () => {
191
+ const { markdown } = await pdfDeriver.derive(markitdown("movie-theater-booking-2024.pdf"));
192
+ for (const expected of ["BOOKING ORDER", "2024-12-5678", "Holiday Movie Marathon Package", "12/20/2024 - 12/31/2024", "CUST-98765", "December 2024"]) {
193
+ expect(markdown).toContain(expected);
194
+ }
195
+ expect(markdown).toContain("| Start Date | End Date | # Shows | Gross Amount | Net Amount |\n| --- | --- | --- | --- | --- |\n| 12/20/24 | 12/31/24 | 48 | $12,500.00 | $11,250.00 |");
196
+ expect(markdown).toContain("| 1 | SCR-1 | 12/20/24 | 12/25/24 | Holiday Spectacular | IMAX 3D | 7:00 PM | Daily | 12 | $250 | PM | $3,000 |");
197
+ expect(markdown).toContain("| | | | | (Runtime: 142 min); Holiday Season Premium | | | | | | | |");
198
+ expect(markdown).toContain(
199
+ [
200
+ "| 1 | SCR-1 | 12/20-12/25 | Holiday Spectacular | 7:00 PM | Daily | PM | $250 | $3,000 |",
201
+ "| 2 | SCR-2 | 12/20-12/31 | Winter Wonderland | 4:30 PM | Daily | MT | $150 | $3,600 |",
202
+ "| 3 | SCR-1 | 12/26-12/31 | New Year Mystery | 9:30 PM | Daily | PM | $300 | $3,600 |",
203
+ ].join("\n"),
204
+ );
205
+ expect(markdown).toContain("This booking order is subject to cinema availability and standard terms.");
206
+ });
207
+
208
+ test("a receipt's formatted text stays text, in reading order", async () => {
209
+ const { markdown } = await pdfDeriver.derive(markitdown("RECEIPT-2024-TXN-98765_retail_purchase.pdf"));
210
+ expect(markdown).not.toContain("|");
211
+ const positions = inOrder(markdown, ["TECHMART ELECTRONICS", "TXN: TXN-98765-2024", "Wireless Noise-Cancelling", "SUBTOTAL", "PAYMENT METHOD", "REWARDS MEMBER", "RETURN POLICY"]);
212
+ expect(positions.every((position) => position >= 0)).toBe(true);
213
+ expect(positions).toEqual(positions.toSorted((a, b) => a - b));
214
+ });
215
+
216
+ test("partial numbering stays on the line it numbers", async () => {
217
+ const { markdown } = await pdfDeriver.derive(markitdown("masterformat_partial_numbering.pdf"));
218
+ expect(markdown).toContain(".1 The intent of this Request for Proposal");
219
+ expect(markdown.split("\n").filter((each) => /^\.\d+$/.test(each.trim()))).toEqual([]);
220
+ expect(markdown).not.toContain("|");
221
+ });
222
+ });
223
+
120
224
  describe("pdf", () => {
121
225
  test("the text layer is the markdown", async () => {
122
226
  const path = fixture("hello.pdf", pdfBytes("Hello from the text layer of this fixture document"));
@@ -142,6 +246,7 @@ describe("pdf", () => {
142
246
  // A stand-in `ocr` on PATH, speaking the real one's protocol (_sandbox/ocr/src/cli.ts): `--check` answers
143
247
  // whether it can read, and a run prints each image's text with a form feed line between images, leaving an image
144
248
  // it could not read empty and exiting 1.
249
+ // Each run also logs how many images it was handed and how many drawings sat beside them, to `runs.log` in its bin.
145
250
  const standIn = (check: number): string => {
146
251
  const bin = mkdtempSync(join(tmpdir(), "fileq-ocr-bin-"));
147
252
  writeFileSync(
@@ -149,14 +254,15 @@ describe("pdf", () => {
149
254
  [
150
255
  "#!/bin/sh",
151
256
  `if [ "$1" = "--check" ]; then exit ${check}; fi`,
257
+ `echo "$# $(ls "$(dirname "$1")" | wc -l)" >> ${bin}/runs.log`,
152
258
  "status=0",
153
259
  "first=1",
154
260
  'for image in "$@"; do',
155
261
  " [ $first = 1 ] || printf '\\f\\n'",
156
262
  " first=0",
157
263
  ' case "$image" in',
158
- " *page-1.png) status=1 ;;",
159
- ' *) printf \'TOTAL DUE ON %s\\n\' "$(basename "$image" .png)" ;;',
264
+ " *page-1.tif) status=1 ;;",
265
+ ' *) printf \'TOTAL DUE ON %s\\n\' "$(basename "$image" .tif)" ;;',
160
266
  " esac",
161
267
  "done",
162
268
  "exit $status",
@@ -166,43 +272,57 @@ describe("pdf", () => {
166
272
  );
167
273
  return bin;
168
274
  };
169
- const withPath = async <T>(bin: string, body: () => Promise<T>): Promise<T> => {
275
+ const runsOf = (bin: string): string[] => readFileSync(join(bin, "runs.log"), "utf8").trim().split("\n");
276
+ const withPath = async <T>(bin: string, body: (bin: string) => Promise<T>): Promise<T> => {
170
277
  const previousPath = process.env["PATH"];
171
278
  process.env["PATH"] = `${bin}:${previousPath ?? ""}`;
172
279
  try {
173
- return await body();
280
+ return await body(bin);
174
281
  } finally {
175
282
  process.env["PATH"] = previousPath;
176
283
  rmSync(bin, { recursive: true, force: true });
177
284
  }
178
285
  };
179
- // A two-page scan, drawn by Pillow: pages of pixels, no text layer.
180
- const scan = (name: string): string => {
286
+ // A scan, two pages unless asked for more, drawn by Pillow: pages of pixels, no text layer.
287
+ const scan = (name: string, pages = 2): string => {
181
288
  const path = join(root, name);
182
289
  execFileSync("python3", [
183
290
  "-c",
184
291
  [
185
292
  "import sys",
186
293
  "from PIL import Image, ImageDraw",
187
- "pages = [Image.new('RGB', (850, 1100), 'white') for _ in range(2)]",
294
+ "pages = [Image.new('RGB', (850, 1100), 'white') for _ in range(int(sys.argv[2]))]",
188
295
  "for page in pages: ImageDraw.Draw(page).rectangle((100, 100, 700, 160), fill='black')",
189
296
  "pages[0].save(sys.argv[1], save_all=True, append_images=pages[1:], resolution=100.0)",
190
297
  ].join("\n"),
191
298
  path,
299
+ String(pages),
192
300
  ]);
193
301
  return path;
194
302
  };
195
303
 
196
304
  /* fileq's half of the OCR tier, wherever poppler and Pillow are (ci-base carries both): the pages drawn and handed
197
- to `ocr` in one run, each page keeping its own text, an unreadable page left empty in its place. */
305
+ to `ocr` a chunk at a time, each page keeping its own text, an unreadable page left empty in its place. */
198
306
  const poppler = requires(onPath("pdftoppm") && pillow(), "pdftoppm on PATH and python3 with Pillow");
199
- test.skipIf(!poppler.runs)(poppler.title("a scan's pages go to ocr in one run, and each keeps its own text"), async () => {
307
+ test.skipIf(!poppler.runs)(poppler.title("a scan's pages go to ocr together, and each keeps its own text"), async () => {
200
308
  const path = scan("two-pages.pdf");
201
- await withPath(standIn(0), async () => {
309
+ await withPath(standIn(0), async (bin) => {
202
310
  expect(pdfDeriver.name).toBe("pdf+ppocr");
203
311
  const doc = await pdfDeriver.derive(path);
204
312
  expect(doc.markdown).toBe("## Page 1\n\n(no text on this page)\n\n## Page 2\n\nTOTAL DUE ON page-2");
205
313
  expect(doc.notes.join(" ")).toContain("recognised by OCR (PaddleOCR) on 2 of 2 pages");
314
+ expect(runsOf(bin)).toEqual(["2 2"]);
315
+ });
316
+ });
317
+
318
+ test.skipIf(!poppler.runs)(poppler.title("a long scan is read eight pages a run, in order, with one chunk's drawings on disk at a time"), async () => {
319
+ const path = scan("eleven-pages.pdf", 11);
320
+ await withPath(standIn(0), async (bin) => {
321
+ const doc = await pdfDeriver.derive(path);
322
+ const pageTexts = [...doc.markdown.matchAll(/^TOTAL DUE ON (page-\d+)$/gm)].map((match) => match[1]);
323
+ expect(pageTexts).toEqual(Array.from({ length: 11 }, (_, index) => `page-${String(index + 1).padStart(2, "0")}`));
324
+ expect(doc.markdown).toContain("## Page 11\n\nTOTAL DUE ON page-11");
325
+ expect(runsOf(bin)).toEqual(["8 8", "3 3"]);
206
326
  });
207
327
  });
208
328