@p10i/flowmatter 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -150,6 +150,16 @@ Malformed frontmatter, duplicate IDs, conflicting module definitions, missing
150
150
  relation targets, invalid generated flow data, and output collisions fail the
151
151
  build with a nonzero exit code.
152
152
 
153
+ ## Query the document graph
154
+
155
+ ```sh
156
+ flowmatter query docs --from payment-service --direction incoming --relation uses --depth 2 --limit 20 --json
157
+ ```
158
+
159
+ `query` reads the same files, directories or quoted globs as `validate` and prints JSON without building HTML. Start at a **document ID**. By default it follows outgoing relations for one hop; use `incoming` to find documents referring to the start, or `both` to walk either way. `--relation` matches `relationType` when present, otherwise `type`.
160
+
161
+ `nodes` are in breadth-first order, with `id`, `title`, Markdown `path` relative to `baseDir`, and shortest `distance` from the start. `edges` are the matching relations traversed, in their original direction. `--depth 0` returns only the start. `--limit` caps nodes including the start (default 100); `truncated` is true if that limit omitted a reachable node within the requested depth.
162
+
153
163
  ## Agent discovery
154
164
 
155
165
  Agents can inspect the supported frontmatter, retrieve a complete multi-file
@@ -1,11 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { readFile } from "node:fs/promises";
4
- import { buildSite, FlowmatterError, validateSite } from "../src/index.mjs";
4
+ import { buildSite, FlowmatterError, querySite, validateSite } from "../src/index.mjs";
5
5
 
6
6
  const HELP = `Usage: flowmatter build <path-or-glob>... [options]
7
7
  flowmatter <path-or-glob>... [options]
8
8
  flowmatter validate <path-or-glob>... [--json]
9
+ flowmatter query <path-or-glob>... --from <id> [--direction incoming|outgoing|both]
10
+ [--relation <type>] [--depth <hops>] [--limit <nodes>] [--json]
9
11
  flowmatter serve <path-or-glob>... [--port 4173] [--title <title>] [--flow <filename>]
10
12
  flowmatter schema
11
13
  flowmatter example
@@ -85,6 +87,23 @@ async function main() {
85
87
  }
86
88
 
87
89
  const command = args[0];
90
+ if (command === 'query') {
91
+ const options = { input: [] };
92
+ for (let i = 1; i < args.length; i++) {
93
+ const arg = args[i];
94
+ if (arg === '--json') continue;
95
+ if (['--from', '--direction', '--relation', '--depth', '--limit'].includes(arg)) {
96
+ const value = takeValue(args, i++, arg);
97
+ if (arg === '--depth' || arg === '--limit') {
98
+ if (!/^\d+$/.test(value)) throw new Error(`${arg} requires an integer`);
99
+ options[arg.slice(2)] = Number(value);
100
+ } else options[arg.slice(2)] = value;
101
+ } else if (arg.startsWith('-')) throw new Error(`unknown query option ${arg}`);
102
+ else options.input.push(arg);
103
+ }
104
+ console.log(JSON.stringify(await querySite(options)));
105
+ return;
106
+ }
88
107
  if (command === 'serve') {
89
108
  const options = parseInputOptions(args.slice(1),true);
90
109
  if (options.outputDir || options.force || options.json) throw new Error('serve accepts --flow, --title and --port');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@p10i/flowmatter",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Generate flowjob maps and linked HTML pages from Markdown frontmatter.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -15,6 +15,8 @@ render one interactive flowjob map plus linked standalone HTML pages.
15
15
 
16
16
  ## Workflow
17
17
 
18
+ To find which documents reference a known document ID, use `flowmatter query docs --from <id> --direction incoming --depth 1 --limit 20 --json`. Inspect the returned edges for the reason each node was selected, then read the relevant Markdown paths relative to `baseDir`. Filter by `--relation <type>` or increase depth when needed. Check `truncated` before assuming the result is complete.
19
+
18
20
  1. Confirm the CLI is available with `flowmatter --version`. If it is not
19
21
  installed, use `npx --package @p10i/flowmatter flowmatter` as the command.
20
22
  2. Run `flowmatter schema` and inspect the complete frontmatter schema.
package/src/index.mjs CHANGED
@@ -287,8 +287,8 @@ export async function resolveMarkdownInputs(input, cwd) {
287
287
  return {baseDir, markdownFiles};
288
288
  }
289
289
 
290
- async function readDocuments(input, cwd) {
291
- const {baseDir, markdownFiles} = await resolveMarkdownInputs(input, cwd);
290
+ async function readDocuments(input, cwd, resolvedInputs) {
291
+ const {baseDir, markdownFiles} = resolvedInputs ?? await resolveMarkdownInputs(input, cwd);
292
292
 
293
293
  const sources = await Promise.all(markdownFiles.map(async (sourcePath) => {
294
294
  const relativePath = toPosix(path.relative(baseDir, sourcePath));
@@ -438,6 +438,47 @@ function compile(documents, title, relationTypes, moduleTypes) {
438
438
  return { byId, flow };
439
439
  }
440
440
 
441
+ export async function querySite({ input, cwd = process.cwd(), from, direction = 'outgoing', depth = 1, relation, limit = 100 } = {}) {
442
+ if (!isNonEmptyString(from)) throw new Error('query requires --from <document-id>');
443
+ if (!['incoming', 'outgoing', 'both'].includes(direction)) throw new Error('Expected direction incoming, outgoing or both');
444
+ if (!Number.isSafeInteger(depth) || depth < 0) throw new Error('Expected a non-negative integer depth');
445
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('Expected a positive integer limit');
446
+ const { baseDir, documents, relationTypes, moduleTypes } = await readDocuments(input, path.resolve(cwd));
447
+ const { byId, flow } = compile(documents, 'Query', relationTypes, moduleTypes);
448
+ if (!byId.has(from)) throw new FlowmatterError(`Unknown document id: ${from}`, { code: 'unknown_document_id' });
449
+
450
+ const adjacent = new Map();
451
+ function add(id, neighbor, edge) {
452
+ if (!adjacent.has(id)) adjacent.set(id, []);
453
+ adjacent.get(id).push({ neighbor, edge });
454
+ }
455
+ for (const { id, from: source, to: target, type, relationType } of flow.flows) {
456
+ if (relation !== undefined && relation !== (relationType ?? type)) continue;
457
+ const edge = { id, from: source.submodule, to: target.submodule, type, ...(relationType ? { relationType } : {}) };
458
+ if (direction !== 'incoming') add(edge.from, edge.to, edge);
459
+ if (direction !== 'outgoing') add(edge.to, edge.from, edge);
460
+ }
461
+ const queue = [from], distances = new Map([[from, 0]]), edges = new Map();
462
+ let truncated = false;
463
+ for (let i = 0; i < queue.length; i++) {
464
+ const id = queue[i], distance = distances.get(id);
465
+ if (distance === depth) break;
466
+ for (const { neighbor, edge } of adjacent.get(id) ?? []) {
467
+ if (!distances.has(neighbor)) {
468
+ if (queue.length === limit) { truncated = true; continue; }
469
+ distances.set(neighbor, distance + 1);
470
+ queue.push(neighbor);
471
+ }
472
+ edges.set(edge.id, edge);
473
+ }
474
+ }
475
+ const nodes = queue.map(id => {
476
+ const { title, relativePath } = byId.get(id);
477
+ return { id, title, path: relativePath, distance: distances.get(id) };
478
+ });
479
+ return { baseDir, nodes, edges: [...edges.values()], truncated };
480
+ }
481
+
441
482
  export async function validateSite({ input, title, cwd = process.cwd() } = {}) {
442
483
  try {
443
484
  if (title !== undefined && !isNonEmptyString(title)) {
@@ -536,6 +577,7 @@ function renderPage(document, documents, byId) {
536
577
 
537
578
  export async function renderSite({
538
579
  input,
580
+ resolvedInputs,
539
581
  outputDir = "flowmatter-dist",
540
582
  flowFile = "flow.html",
541
583
  title,
@@ -549,7 +591,7 @@ export async function renderSite({
549
591
  throw new FlowmatterError("The title must be a non-empty string");
550
592
  }
551
593
 
552
- const { baseDir, documents, relationTypes, moduleTypes } = await readDocuments(input, path.resolve(cwd));
594
+ const { baseDir, documents, relationTypes, moduleTypes } = await readDocuments(input, path.resolve(cwd), resolvedInputs);
553
595
  const outputRoot = path.resolve(cwd, outputDir);
554
596
  const flowPath = path.join(outputRoot, flowFile);
555
597
  for (const document of documents) {
package/src/serve.mjs CHANGED
@@ -7,24 +7,26 @@ import {renderSite, resolveMarkdownInputs} from './index.mjs';
7
7
  // work for globs as well as directories on bind-mounted filesystems.
8
8
  export async function serveSite({input, cwd = process.cwd(), title, flowFile = 'flow.html', port = 4173,
9
9
  interval = 500, log = console.error}) {
10
- async function fingerprint() {
11
- const {markdownFiles} = await resolveMarkdownInputs(input, cwd);
10
+ async function fingerprint({markdownFiles}) {
12
11
  return JSON.stringify(await Promise.all(markdownFiles.map(async file => {
13
12
  const s = await stat(file, {bigint:true});
14
13
  return [file, String(s.ino), String(s.size), String(s.ctimeNs), String(s.mtimeNs)];
15
14
  })));
16
15
  }
17
- async function render() {
18
- const site = await renderSite({input,cwd,title,flowFile});
16
+ async function render(resolvedInputs) {
17
+ const site = await renderSite({resolvedInputs,cwd,title,flowFile});
19
18
  return new Map(site.outputs.map(({path:file,content}) => ['/' + path.relative(site.outputDir,file).split(path.sep).join('/'),content]));
20
19
  }
21
- let seen = await fingerprint(), pages = await render(), stopped = false, timer, lastError;
20
+ // The fingerprint and rendered pages must describe the same set of files.
21
+ const initial = await resolveMarkdownInputs(input, cwd);
22
+ let seen = await fingerprint(initial), pages = await render(initial), stopped = false, timer, lastError;
22
23
  async function poll() {
23
24
  try {
24
- const next = await fingerprint();
25
+ const inputs = await resolveMarkdownInputs(input, cwd);
26
+ const next = await fingerprint(inputs);
25
27
  if (next !== seen) {
26
28
  seen = next;
27
- pages = await render(); // Publish the entire new generation together.
29
+ pages = await render(inputs); // Publish the entire new generation together.
28
30
  log(`Rebuilt ${pages.size - 1} pages`);
29
31
  }
30
32
  lastError = undefined;