@omgbase/core 0.19.0 → 0.21.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 (36) hide show
  1. package/dist/src/core/ingest.d.ts +2 -0
  2. package/dist/src/core/ingest.js +13 -0
  3. package/dist/src/core/read/document.d.ts +9 -8
  4. package/dist/src/core/read/document.js +0 -2
  5. package/dist/src/core/store/gc.d.ts +13 -1
  6. package/dist/src/core/store/gc.js +24 -5
  7. package/dist/src/core/store/size.d.ts +4 -1
  8. package/dist/src/core/store/size.js +11 -2
  9. package/dist/src/mcp/arguments.d.ts +10 -2
  10. package/dist/src/mcp/arguments.js +37 -3
  11. package/dist/src/mcp/reference.d.ts +1 -1
  12. package/dist/src/mcp/reference.js +36 -4
  13. package/dist/src/mcp/server.js +50 -23
  14. package/dist/src/mutate/effects.d.ts +23 -5
  15. package/dist/src/mutate/effects.js +111 -22
  16. package/dist/src/mutate/known-ids.d.ts +19 -0
  17. package/dist/src/mutate/known-ids.js +47 -7
  18. package/dist/src/mutate/ops.d.ts +1 -0
  19. package/dist/src/mutate/ops.js +20 -1
  20. package/dist/src/mutate/select.d.ts +0 -11
  21. package/dist/src/mutate/select.js +33 -9
  22. package/dist/src/oqx-js/context.d.ts +9 -2
  23. package/dist/src/oqx-js/context.js +74 -28
  24. package/dist/src/oqx-js/names.d.ts +40 -0
  25. package/dist/src/oqx-js/names.js +347 -0
  26. package/dist/src/oqx-js/planner.d.ts +3 -3
  27. package/dist/src/oqx-js/planner.js +13 -9
  28. package/dist/src/oqx-js/root-row.d.ts +15 -4
  29. package/dist/src/oqx-js/root-row.js +18 -10
  30. package/dist/src/oqx-js/run.d.ts +18 -1
  31. package/dist/src/oqx-js/run.js +31 -12
  32. package/dist/src/oqx-js/sql/translate.js +1 -1
  33. package/dist/src/spec-versions.d.ts +5 -5
  34. package/dist/src/spec-versions.js +4 -4
  35. package/dist/src/sync/observe.js +9 -3
  36. package/package.json +2 -2
@@ -10,6 +10,8 @@ export interface DispositionRow {
10
10
  matcherV: string | null;
11
11
  detail: Record<string, unknown>;
12
12
  }
13
+ /** spec/store §5.4 step 10 (14.2): which verdicts the store persists — every kind but `same`. */
14
+ export declare function persistsDisposition(kind: string): boolean;
13
15
  export interface ResolvedEdgeRow {
14
16
  srcDoc: string;
15
17
  srcBlock: string | null;
@@ -13,6 +13,10 @@ import { flattenFrontmatter, flattenComputed, writeDocProperties } from "./store
13
13
  import { maintainEdges, adoptPhantoms } from "./store/edges.js";
14
14
  import { parse as parseYaml } from "yaml";
15
15
  import { adapterForPath } from "../format/index.js";
16
+ /** spec/store §5.4 step 10 (14.2): which verdicts the store persists — every kind but `same`. */
17
+ export function persistsDisposition(kind) {
18
+ return kind !== "same";
19
+ }
16
20
  /** The parse step of ingest, exported so a batch caller can parse + reconcile
17
21
  * every document of a checkpoint BEFORE committing any (the cross-document
18
22
  * phase needs all per-doc results first) and hand the tree back via
@@ -279,10 +283,19 @@ export function ingestInto(db, repoId, path, content, opts) {
279
283
  const dispositions = resolved.dispositions.length > 0 || opts.resolveIds
280
284
  ? resolved.dispositions
281
285
  : rows.map((r) => ({ blockId: r.blockId, kind: "inserted", confidence: null, reason: null, matcherV: null, detail: {} }));
286
+ // spec/store §5.4 step 10 (14.2): a `same` verdict is not persisted. The
287
+ // matcher (and the known-id resolver) still produce one per untouched block
288
+ // — the outcome counts them — but the table records what CHANGED, so a
289
+ // block's `updated_at` (MAX commit ts over its `block_changes`) and its
290
+ // `blocks_history` are the block's own changes, not its siblings'. Every
291
+ // other kind — the first revision's `inserted` rows the mint oracle (§2.1)
292
+ // depends on included — is written as before.
282
293
  const insDisp = db.prepare(`INSERT OR IGNORE INTO dispositions (commit_id, block_id, kind, confidence, reason, matcher_v, detail)
283
294
  VALUES (?, ?, ?, ?, ?, ?, ?)`);
284
295
  const bc = db.prepare("INSERT OR IGNORE INTO block_changes (block_id, commit_id, kind) VALUES (?, ?, ?)");
285
296
  for (const d of dispositions) {
297
+ if (!persistsDisposition(d.kind))
298
+ continue;
286
299
  insDisp.run(commitId, d.blockId, d.kind, d.confidence, d.reason, d.matcherV, JSON.stringify(d.detail));
287
300
  bc.run(d.blockId, commitId, d.kind);
288
301
  }
@@ -76,6 +76,15 @@ export declare function docsReadMany(store: Store, repoId: string, refs: string[
76
76
  includeIds?: boolean;
77
77
  budgetTokens?: number;
78
78
  }): DocsReadManyResult;
79
+ /**
80
+ * `docs_read { at }` / `docs_read_at` (spec/surface §2, 4.7): the document AS
81
+ * OF a revision. No `properties`: the properties table is current-state only
82
+ * (`spec/properties`), and recomputing the bag from the reconstructed bytes is
83
+ * not yet a one-call affair of the format layer (the inline fields come out of
84
+ * the ingest's node projection) — so the time-travel read carries the bytes
85
+ * and nothing it would have to guess at (through 4.6 `docs_read_at` returned
86
+ * the CURRENT bag flagged `propertiesAreCurrent: true`).
87
+ */
79
88
  export interface DocsReadAtResult {
80
89
  id: string;
81
90
  /** The path as of that revision, in the reference form. */
@@ -88,14 +97,6 @@ export interface DocsReadAtResult {
88
97
  * rendered_hash — a byte-faithful round-trip. False flags the fidelity gap
89
98
  * described below (doc-level trivia may differ for an old revision). */
90
99
  renderedHashMatch: boolean;
91
- /**
92
- * Properties as they are CURRENTLY (not at `rev`): the properties table is
93
- * current-state only (properties-table), so historical property values are
94
- * not recoverable. Included as best-effort context, flagged by
95
- * `propertiesAreCurrent: true`.
96
- */
97
- properties: Record<string, Record<string, unknown>>;
98
- propertiesAreCurrent: true;
99
100
  }
100
101
  /**
101
102
  * Whole-document TIME-TRAVEL read: reconstruct a document's full file bytes AS
@@ -204,8 +204,6 @@ export function readDocumentAtRevision(store, docId, revId) {
204
204
  rev: revId,
205
205
  raw: content,
206
206
  renderedHashMatch,
207
- properties: surfaceProperties(docPropertiesGrouped(db, docId)),
208
- propertiesAreCurrent: true,
209
207
  };
210
208
  }
211
209
  //# sourceMappingURL=document.js.map
@@ -2,16 +2,28 @@ import type { Store } from "./store.js";
2
2
  export interface GcResult {
3
3
  blobsSwept: number;
4
4
  treeNodesSwept: number;
5
+ /** spec/store §7 (14.2): `same` rows a 14.1 store wrote into `dispositions`/`block_changes` — history nothing reads. */
6
+ sameDispositionsSwept: number;
5
7
  }
8
+ /** The `same` rows a store through 14.1 persisted (spec/store §7, 14.2). */
9
+ export declare function countSameDispositions(store: Store): number;
6
10
  /**
7
11
  * Mark-and-sweep GC (flag-gated; enabled must be true to run — v1.0 ships it
8
12
  * off). Removes blobs/tree_nodes unreachable from any revision root. Because
9
13
  * revisions are append-only and never pruned in v1, nothing is actually
10
- * unreachable unless revision pruning ran first — so this is a no-op in a
14
+ * unreachable unless revision pruning ran first — so that half is a no-op in a
11
15
  * default v1 repo, exactly as specified. Rebuild-equivalence is preserved.
16
+ *
17
+ * spec/store §7 (14.2): the same sweep deletes every `same` row of
18
+ * `dispositions` and `block_changes` — what a 14.1 store wrote for every
19
+ * untouched block of every commit, and nothing reads (`updated_at` and
20
+ * `blocks_history` are the block's own changes now). Not a migration: a
21
+ * data-only change needs no `user_version`, and opening a database must never
22
+ * bulk-delete. `dryRun` counts everything and deletes nothing.
12
23
  */
13
24
  export declare function runGc(store: Store, opts?: {
14
25
  enabled?: boolean;
26
+ dryRun?: boolean;
15
27
  }): GcResult;
16
28
  /** Resurrection-pool expiry sweep (02 §7): drop rows past their expires_ts.
17
29
  * Runs routinely (lazy, at checkpoint time). */
@@ -29,24 +29,37 @@ function markReachable(store) {
29
29
  walk(r.root_tree.toString("hex"));
30
30
  return { trees, blobs };
31
31
  }
32
+ /** The `same` rows a store through 14.1 persisted (spec/store §7, 14.2). */
33
+ export function countSameDispositions(store) {
34
+ return store.db.prepare("SELECT count(*) AS c FROM dispositions WHERE kind = 'same'").get().c;
35
+ }
32
36
  /**
33
37
  * Mark-and-sweep GC (flag-gated; enabled must be true to run — v1.0 ships it
34
38
  * off). Removes blobs/tree_nodes unreachable from any revision root. Because
35
39
  * revisions are append-only and never pruned in v1, nothing is actually
36
- * unreachable unless revision pruning ran first — so this is a no-op in a
40
+ * unreachable unless revision pruning ran first — so that half is a no-op in a
37
41
  * default v1 repo, exactly as specified. Rebuild-equivalence is preserved.
42
+ *
43
+ * spec/store §7 (14.2): the same sweep deletes every `same` row of
44
+ * `dispositions` and `block_changes` — what a 14.1 store wrote for every
45
+ * untouched block of every commit, and nothing reads (`updated_at` and
46
+ * `blocks_history` are the block's own changes now). Not a migration: a
47
+ * data-only change needs no `user_version`, and opening a database must never
48
+ * bulk-delete. `dryRun` counts everything and deletes nothing.
38
49
  */
39
50
  export function runGc(store, opts = {}) {
40
51
  if (!opts.enabled)
41
- return { blobsSwept: 0, treeNodesSwept: 0 };
52
+ return { blobsSwept: 0, treeNodesSwept: 0, sameDispositionsSwept: 0 };
42
53
  return store.write((db) => {
43
54
  const { trees, blobs } = markReachable(store);
55
+ const dry = Boolean(opts.dryRun);
44
56
  let treeNodesSwept = 0;
45
57
  const allTrees = db.prepare("SELECT hash FROM tree_nodes").all();
46
58
  const delTree = db.prepare("DELETE FROM tree_nodes WHERE hash = ?");
47
59
  for (const t of allTrees)
48
60
  if (!trees.has(t.hash.toString("hex"))) {
49
- delTree.run(t.hash);
61
+ if (!dry)
62
+ delTree.run(t.hash);
50
63
  treeNodesSwept++;
51
64
  }
52
65
  let blobsSwept = 0;
@@ -54,10 +67,16 @@ export function runGc(store, opts = {}) {
54
67
  const delBlob = db.prepare("DELETE FROM blobs WHERE hash = ?");
55
68
  for (const b of allBlobs)
56
69
  if (!blobs.has(b.hash.toString("hex"))) {
57
- delBlob.run(b.hash);
70
+ if (!dry)
71
+ delBlob.run(b.hash);
58
72
  blobsSwept++;
59
73
  }
60
- return { blobsSwept, treeNodesSwept };
74
+ const sameDispositionsSwept = countSameDispositions(store);
75
+ if (!dry && sameDispositionsSwept > 0) {
76
+ db.prepare("DELETE FROM block_changes WHERE kind = 'same'").run();
77
+ db.prepare("DELETE FROM dispositions WHERE kind = 'same'").run();
78
+ }
79
+ return { blobsSwept, treeNodesSwept, sameDispositionsSwept };
61
80
  });
62
81
  }
63
82
  /** Resurrection-pool expiry sweep (02 §7): drop rows past their expires_ts.
@@ -39,6 +39,8 @@ export interface SizeReport {
39
39
  file: SizeFile;
40
40
  /** Always the four categories, in the fixed order content, history, search, sync. */
41
41
  categories: SizeCategoryReport[];
42
+ /** spec/store §7 (14.2): `dispositions` rows with `kind = 'same'` — what a store through 14.1 wrote and `omg gc` removes. */
43
+ same_dispositions: number;
42
44
  advice: string[];
43
45
  /** Present only when the SQLite build lacks `dbstat` (row counts only). */
44
46
  detail?: "dbstat unavailable";
@@ -47,6 +49,7 @@ export interface SizeReport {
47
49
  export declare const VACUUM_ADVICE_MIN_BYTES: number;
48
50
  export declare const VACUUM_ADVICE_MIN_SHARE = 10;
49
51
  export declare const HISTORY_ADVICE_MIN_SHARE = 50;
52
+ export declare const SAME_ADVICE_MIN_SHARE = 25;
50
53
  export declare const EMBEDDINGS_ADVICE_MIN_SHARE = 25;
51
54
  /**
52
55
  * `<n> B` under 1024, else one decimal of KB/MB/GB/TB (1024-based), the tenths
@@ -59,7 +62,7 @@ export declare function formatShare(share: number): string;
59
62
  /** `bytes / total` in percent, one decimal, rounded half up; 0 when the total is 0. */
60
63
  export declare function shareOf(bytes: number, total: number): number;
61
64
  /** spec/store §7: the advice lines, in this order; `nothing to reclaim` when none applies. */
62
- export declare function sizeAdvice(file: SizeFile, categories: SizeCategoryReport[]): string[];
65
+ export declare function sizeAdvice(file: SizeFile, categories: SizeCategoryReport[], sameDispositions?: number): string[];
63
66
  /** The size report of an open store (spec/store §7 "Size"). */
64
67
  export declare function sizeReport(store: Store): SizeReport;
65
68
  export interface VacuumResult {
@@ -51,6 +51,7 @@ export function categoryOf(table) {
51
51
  export const VACUUM_ADVICE_MIN_BYTES = 1024 * 1024;
52
52
  export const VACUUM_ADVICE_MIN_SHARE = 10;
53
53
  export const HISTORY_ADVICE_MIN_SHARE = 50;
54
+ export const SAME_ADVICE_MIN_SHARE = 25;
54
55
  export const EMBEDDINGS_ADVICE_MIN_SHARE = 25;
55
56
  /**
56
57
  * `<n> B` under 1024, else one decimal of KB/MB/GB/TB (1024-based), the tenths
@@ -82,7 +83,7 @@ export function shareOf(bytes, total) {
82
83
  return Math.round((bytes * 1000) / total) / 10;
83
84
  }
84
85
  /** spec/store §7: the advice lines, in this order; `nothing to reclaim` when none applies. */
85
- export function sizeAdvice(file, categories) {
86
+ export function sizeAdvice(file, categories, sameDispositions = 0) {
86
87
  const advice = [];
87
88
  const logical = file.page_count * file.page_size;
88
89
  if (file.reclaimable > VACUUM_ADVICE_MIN_BYTES && file.reclaimable * 100 > logical * VACUUM_ADVICE_MIN_SHARE) {
@@ -92,6 +93,13 @@ export function sizeAdvice(file, categories) {
92
93
  if (history && history.share !== null && history.share > HISTORY_ADVICE_MIN_SHARE) {
93
94
  advice.push(`history dominates (${formatShare(history.share)}): blobs, tree nodes and dispositions grow with every commit — enable gc (\`omg config set gc.enabled true\`) and run \`omg gc --vacuum\``);
94
95
  }
96
+ // 14.2: `same` rows are what a 14.1 store wrote for every untouched block;
97
+ // past a quarter of the table they are worth a sweep (the share is over rows,
98
+ // so it holds with or without dbstat).
99
+ const dispositionRows = history?.tables.find((t) => t.name === "dispositions")?.rows ?? 0;
100
+ if (sameDispositions > 0 && sameDispositions * 100 > dispositionRows * SAME_ADVICE_MIN_SHARE) {
101
+ advice.push(`${sameDispositions} same dispositions are history nothing reads (store 14.2): \`omg gc\` removes them, \`--vacuum\` reclaims the pages`);
102
+ }
95
103
  const search = categories.find((c) => c.name === "search");
96
104
  if (search && search.bytes !== null) {
97
105
  const total = categories.reduce((n, c) => n + (c.bytes ?? 0), 0);
@@ -199,7 +207,8 @@ export function sizeReport(store) {
199
207
  const bytes = stat ? tables.reduce((n, t) => n + (t.bytes ?? 0), 0) : null;
200
208
  return { name, bytes, share: bytes === null ? null : shareOf(bytes, total), rows: tables.reduce((n, t) => n + t.rows, 0), tables };
201
209
  });
202
- const report = { file, categories, advice: sizeAdvice(file, categories) };
210
+ const same_dispositions = db.prepare("SELECT count(*) AS c FROM dispositions WHERE kind = 'same'").get().c;
211
+ const report = { file, categories, same_dispositions, advice: sizeAdvice(file, categories, same_dispositions) };
203
212
  if (!stat)
204
213
  report.detail = "dbstat unavailable";
205
214
  return report;
@@ -4,8 +4,16 @@ import { EngineError } from "./errors.js";
4
4
  export type ArgShape = Record<string, z.ZodTypeAny>;
5
5
  /** The `(tool takes …)` tail: names in bytewise order, `?` on the optional ones. */
6
6
  export declare function argumentsHint(tool: string, shape: ArgShape): string;
7
- /** A `filter_invalid` for an argument-shape failure: the message plus the tool's shape. */
8
- export declare function argumentError(tool: string, message: string, shape: ArgShape): EngineError;
7
+ /** A `filter_invalid` for an argument-shape failure: the message plus the tool's shape — and a `fix` (4.5, spec/surface §4) when the corrected call can be spelled. */
8
+ export declare function argumentError(tool: string, message: string, shape: ArgShape, fix?: string): EngineError;
9
+ /** The schema of a string-list argument: an array of strings, or one bare string (normalized to `[s]` by `validateArguments`). */
10
+ export declare function stringList(opts?: {
11
+ min?: number;
12
+ }): z.ZodType<string[]>;
13
+ /** Is this argument a string list (through `optional`/`nullable`)? */
14
+ export declare function isStringList(schema: z.ZodTypeAny): boolean;
15
+ /** The parts of a comma-joined string: split on `,`, trimmed, empty parts dropped. */
16
+ export declare function commaSplit(s: string): string[];
9
17
  /**
10
18
  * Validate `raw` against `shape`: unknown names first (in bytewise order), then
11
19
  * each declared argument (bytewise order) for presence and type. Returns the
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { EngineError } from "./errors.js";
3
+ import { canonicalJson } from "../mutate/canonical.js";
3
4
  /** The `(tool takes …)` tail: names in bytewise order, `?` on the optional ones. */
4
5
  export function argumentsHint(tool, shape) {
5
6
  const names = Object.keys(shape).sort(cmpBytes);
@@ -7,10 +8,33 @@ export function argumentsHint(tool, shape) {
7
8
  return `${tool} takes no arguments`;
8
9
  return `${tool} takes ${names.map((n) => (isOptional(shape[n]) ? `${n}?` : n)).join(", ")}`;
9
10
  }
10
- /** A `filter_invalid` for an argument-shape failure: the message plus the tool's shape. */
11
- export function argumentError(tool, message, shape) {
11
+ /** A `filter_invalid` for an argument-shape failure: the message plus the tool's shape — and a `fix` (4.5, spec/surface §4) when the corrected call can be spelled. */
12
+ export function argumentError(tool, message, shape, fix) {
12
13
  const full = `${message} (${argumentsHint(tool, shape)})`;
13
- return new EngineError("filter_invalid", full, { data: { reason: full, hint: "arguments" } });
14
+ return new EngineError("filter_invalid", full, { data: { reason: full, hint: "arguments", ...(fix !== undefined ? { fix } : {}) } });
15
+ }
16
+ // ---- string lists (spec/surface §4 "Arguments", 4.5) ---------------------------------
17
+ //
18
+ // Every list-of-strings argument (`docs`, `ids`, `roots`, `blocks`, `select`,
19
+ // `unset`) also takes ONE bare string as a one-element list — the first guess
20
+ // of a caller who has one ref. A comma-joined string is still "must be an array
21
+ // of strings", but that error carries a `fix`: the same call with the string
22
+ // split on commas (each part trimmed, empty parts dropped), canonical JSON.
23
+ const STRING_LISTS = new WeakSet();
24
+ /** The schema of a string-list argument: an array of strings, or one bare string (normalized to `[s]` by `validateArguments`). */
25
+ export function stringList(opts = {}) {
26
+ const list = opts.min !== undefined ? z.array(z.string()).min(opts.min) : z.array(z.string());
27
+ const schema = z.union([list, z.string()]);
28
+ STRING_LISTS.add(schema);
29
+ return schema;
30
+ }
31
+ /** Is this argument a string list (through `optional`/`nullable`)? */
32
+ export function isStringList(schema) {
33
+ return STRING_LISTS.has(unwrap(schema));
34
+ }
35
+ /** The parts of a comma-joined string: split on `,`, trimmed, empty parts dropped. */
36
+ export function commaSplit(s) {
37
+ return s.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
14
38
  }
15
39
  /**
16
40
  * Validate `raw` against `shape`: unknown names first (in bytewise order), then
@@ -36,6 +60,14 @@ export function validateArguments(tool, shape, raw) {
36
60
  throw argumentError(tool, `\`${key}\` is required`, shape);
37
61
  continue;
38
62
  }
63
+ if (isStringList(schema) && typeof value === "string") {
64
+ // (4.5) one bare string is a one-element list; a comma-joined one is the
65
+ // array error with the split list as its `fix`.
66
+ if (value.includes(","))
67
+ throw argumentError(tool, `\`${key}\` must be an array of strings`, shape, canonicalJson({ ...args, [key]: commaSplit(value) }));
68
+ out[key] = [value];
69
+ continue;
70
+ }
39
71
  const parsed = schema.safeParse(value);
40
72
  if (!parsed.success)
41
73
  throw argumentError(tool, issueMessage(key, schema, parsed.error.issues), shape);
@@ -141,6 +173,8 @@ function unwrap(schema) {
141
173
  }
142
174
  /** The expected-type phrase of an argument, as the Rust catalog spells it from its JSON schema. */
143
175
  export function phraseFor(schema) {
176
+ if (isStringList(schema))
177
+ return "an array of strings";
144
178
  const d = defOf(unwrap(schema));
145
179
  switch (d.type) {
146
180
  case "string": return "a string";
@@ -1 +1 @@
1
- export declare const QUERY_SYNTAX = "# query \u2014 OQX syntax reference\n\nThe `query` tool takes ONE plain OQX string (+ optional `limit`/`cursor`, and\n`bare: true` to drop the automatic `id`/`path` envelope \u2014 needs a `select`).\nThere is no {from, filter, order} envelope: every concern is a clause of the\nstring. Two rules tell the two syntaxes apart: DOT navigation belongs to the\nhost object model (`doc.layer`, `section.blocks`, `dst.title`); WHITESPACE\nquery directives belong to OQX \u2014 a nested query is `<receiver> collect|exists|\ncount|first|single { <block> }` (a postfix directive + a `{ \u2026 }` block), never a\nmethod. Its distinctive power is the receiver-constrained nested query that\ncorrelates to the current row: `from docs where nodes exists { where kind ==\n\"md:task\" }` returns only the docs that themselves contain a matching node.\n\n [select <items>] from <target> [where <pred>] [frontier <pred>] [follow <dest> [{ \u2026 }], \u2026]\n [order by <expr> [asc|desc], \u2026] [limit N] [offset N]\n <target> count|exists|none|first|single { <block> } (scalar/one-row form: a bare target at the root scope)\n\nCLAUSE ORDER IS FIXED: select, from, where, frontier, follow, order by, limit, offset \u2014\neach at most once; an out-of-order clause is a parse error naming the order.\nOnly `select` may drop its keyword, and only as the first clause\n(`path, era from docs where \u2026`). A top-level predicate needs `where`, because\n`where` follows `from` (`era > 1600 from docs` is the clause-order error); a\nblock may LEAD with a predicate (see Sugar), but a predicate after a projection\nstill needs the keyword (`{ name where kind == \"md:task\" }`, not\n`{ name, kind == \"md:task\" }`); `from docs count` is an error (write\n`docs count { \u2026 }`). `where` and later `select` items may use the same body's\n`select` aliases (`select path, old: era < 1000 from docs where old`; an alias\nshadows a same-named field there). `and` / `or` / `not` are the connectives;\nthe symbols `&&` / `||` / `!` are accepted synonyms (the words are canonical and\nwhat `print` writes).\n\n## Sugar (OQX 0.17)\n\nEvery form here is shorthand for an explicit directive (the AST is the explicit form):\n nodes { kind == \"md:task\" } \u2261 nodes collect { where kind == \"md:task\" } \u2014 a receiver block with\n no consumer is collect; a block whose LEADING expression is a predicate\n (comparison, call, !/is/not, in, literal, (\u2026), a consumer test \u2014 anything\n but a bare name, a dotted path or a ^lift) is where-first. Bare names still\n project: nodes { name } \u2261 nodes collect { name }; filter a bare field with\n nodes { is checked }. Wherever a value stands (0.20), call arguments included:\n size(children { is checked }); x distinct { \u2026 } \u2261 x collect distinct { \u2026 }. After a\n follow destination too: follow children { depth 2 } is that destination's block.\n (a, b) a tuple (0.20): two or more expressions, concatenated one level flat \u2014 a value\n (size((tags, aliases)), \"x\" in (tags, aliases)) and a receiver ((a, b) { \u2026 },\n follow (before, after) { depth 2 }); (a) alone is grouping\n refs(x)[0] \u2261 refs(x) first { offset 0 } positional (integer literal or ${binding});\n out of range \u21D2 absent; refs(x)[0].path navigates the row\n ^docs[path == ^company] \u2261 ^docs first { where path == ^company } first match or absent\n ^docs[path == ^company]! \u2261 \u2026 single { \u2026 } required: exactly one, else filter_invalid\n title! required: title, or an error naming the expression (and the row's $key \u2014 its id)\n \u2014 never a filter, never a coercion (0!, \"\"! are values); tightest: a!.b vs a.b!\n is x / not x truthiness of x, and its negation (prefix; `not` \u2261 `!`)\n x is y / x is not y identity ($key: a store row's id, else structural) \u2014 compares rows, which == does not;\n x is null = absent; for scalars is \u2261 ==; comparison precedence, no chaining\n a and b / a or b the connectives (\u2261 && / ||: same precedence, short-circuit, value: data.title or path coalesces)\n boss: ^docs[path == ^manager], bossName: boss.title a select item may use the items to its LEFT\n Reserved words (never a bare field name): from where select is not and or, true false null.\n Contextual words (limit order offset follow collect count first distinct desc by in frontier depth) parse as\n fields in expression position (select o: order from docs).\n\nResults are LEAN hits \u2014 { id, path } + whatever `select` projects (or `values`,\n`count`, `exists`, `none`). The envelope keys ARE the attributes: copy a hit's\n`id` straight into `where id == \"\u2026\"` (no translation); `select id, path` is simply\nthe envelope (no duplicate columns); any OTHER projection whose output key would\nbe `id` or `path` must be aliased \u2014 `select data.path` is refused (\"projection\n`path` collides with the hit envelope \u2014 alias it (`p: data.path`)\"); a row\nsurfacing as a value (an empty `collect { }`) is the same `{ id, path }`. Every\nother tool spells a row the same way (`docs_read` \u2192 `{ id, path, rev, properties,\nraw }`, `blocks_read` \u2192 `{ id, type, text, raw, hash, \u2026 }`, `docs_list` \u2192 `{ id,\npath, updated_at, blocks }`, a revision \u2192 `{ id, path, hash }`): hydrate by id via\nblocks_read/docs_read.\n\n## Paths\n\nEvery path the surface returns is `/`-rooted \u2014 the form a reference is\nwritten in (`[x](/projects/oqx.md)`, `before: [/timeline/kickoff.md]`): a\nhit's `path`, an edge's `dst_path`, every tool's paths. Every path it\naccepts tolerates both forms (`/a.md` or `a.md`): tool arguments, `refs(x)`,\n`within(...)`, and a string LITERAL compared with `path`/`dst_path` (bare, or\nthrough a row handle: `doc.path`) by `==`/`!=` or passed to their\n`.startsWith(...)` (it is rooted first, so `path == \"a.md\"` and `path == \"/a.md\"`\nboth match). A property holding a reference compares directly \u2014 and is never\nrooted: `where ^path in list(after)`, `where customer == ^path`,\n`where data.path == \"/x.md\"` (the author's `path:` key, as written) \u2014 no\n`\"/\" + ...` glue.\n\n## Targets & field namespaces\n\nTHE NAME RULE: `$` belongs to OQX \u2014 $it, $key, $depth, $stop, $leaf, $frontier,\n$ordinal are values the LANGUAGE injects into a scope; omgbase adds NO $ names\n(a `$id` in a query is an unknown name, absent). Every engine attribute is a BARE\nsnake_case name that WINS on collision \u2014 the convention the relations (children,\nblocks, out, in, doc, frontmatter, \u2026) always followed: a bare name that is an\nengine attribute reads the engine's value, never yours. Your data is bare too;\nwhere a key of yours collides with an engine name, reach it through a source\nhandle: `data.<k>` (the merged authored view \u2014 frontmatter + inline, exactly the\nread a bare non-colliding key performs), `frontmatter.<k>`, `inline.<k>`. So\n`path` is the engine's /-rooted location and `data.path` your `path:` key;\n`tags` is your tags \u222A the body #hashtags and `data.tags` the authored list alone;\n`title` the computed title (the first H1) and `data.title` your `title:`;\n`entries(data)` lists every authored top-level key. Same value, same name\neverywhere: a hit's `id` is docs_read's `id` and the `id` argument of blocks_read.\n\n Reserved bare names per kind (engine attributes; handles; self; relations):\n docs id path raw hash updated_at title tags format | data frontmatter inline | doc | blocks nodes out in out_links in_links\n blocks id path doc_id raw hash updated_at type text attrs depth ordinal | block doc | children nodes out_links section\n nodes id path doc_id block_id kind name value attrs | section doc block | blocks subsections children\n links id path doc_id block_id via_id dst_id dst_path uri field dst_kind predicate provenance anchor | doc\n A key of yours with any of these names is `data.<k>` (or frontmatter.<k> /\n inline.<k> by source; attrs.<k> on a block or node).\n\ndocs:\n - bare identifier = a document PROPERTY (frontmatter + inline `key:: value`,\n unioned; nested via dots: meta.owner). YAML/JSON docs\n expose the parsed object's keys the same way.\n - source handles = data.<k> (merged authored view) / frontmatter.<k> /\n inline.<k>; the whole bag as a collection via entries(data)\n / entries(frontmatter) / entries(inline) (see entries()).\n - attributes = id, path (/-rooted, see Paths), updated_at (ISO-8601,\n sorts chronologically), raw (the whole file, frontmatter\n included), hash (its sha256, 64 hex), title (the computed\n title: the first H1; data.title is the authored key), tags\n (authored tags \u222A body #hashtags, deduped, authored first;\n data.tags is the authored list), format (the doc's format \u2014\n \"markdown\"/\"yaml\"/\"json\"; present on EVERY doc, so\n has(format) is always true and `format == \"yaml\"` is the\n filter).\n - relations = nodes, blocks, doc.out_links / doc.in_links (a doc's\n links as rows; the documents at their other end are\n out_links collect distinct { from dst } and\n in_links collect distinct { from doc } \u2014 there is no\n out / in relation).\n\nblocks:\n - bare fields = doc_id (the owning doc), type, text (normalized), ordinal\n (0-based among siblings), depth (0 at the top level), and\n every attrs key FLATTENED onto the row (bare `checked`\n reads attrs.checked; `attrs.<k>` still works; the\n structural fields win on collision; absent \u21D2 false).\n - attributes = id, path (the owning doc's path), raw (the block's raw\n source \u2014 a container's raw holds its children), hash\n (its sha256 \u2014 the value update/split expect as\n expect.content_hash), updated_at.\n - reach-through = doc.<key> / doc.path / doc.id / doc.format = the\n CONTAINING doc (doc.id and doc.path cost nothing \u2014 they\n read the row's own doc_id / joined path, no lookup).\n - relations = block.children, block.nodes, block.out_links, section.\n NOTE: inside a `follow`, $depth/$ordinal are ALWAYS the walk's metadata; a\n block's own nesting is `depth` / `ordinal` (no $) everywhere.\n\nnodes:\n - bare fields = doc_id, block_id (null for a block-less node), kind\n (md:task / md:link / md:section / yaml:\u2026), name, value,\n + attrs keys flattened (checked, level).\n - attributes = id, path.\n - reach-through = doc.<key> / doc.id / doc.path, block.type / block.text\n / block.id / block.path.\n - relations = section.blocks, section.children, section.subsections.\n\nlinks: (the authored link graph as rows \u2014 one per open link: the relation a link\n establishes; the md:link NODE is its occurrence in the text and via_id\n points at it \u2014 a frontmatter link has a row and no node)\n - bare fields = doc_id (the SOURCE doc), block_id (the source block; null\n for a frontmatter edge), via_id, dst_id (the destination\n node id: a doc id, an external node id or phantom:<path>),\n dst_path (target doc path, /-rooted; NULL when\n dangling/external), uri (external URL; NULL otherwise),\n predicate (\"references\"/\"embeds\"/freeform), provenance\n (\"link\"/\"frontmatter\"/\"inline_field\"/\u2026), dst_kind\n (\"document\"/\"external\"/\"collection\"), anchor, field (the\n frontmatter key / inline field it was authored in).\n - attributes = id, path (the SOURCE doc's path); doc.<key> reaches the\n source document. There is no from_commit: a query sees\n open edges only (history is blocks_history/changes_since).\n - text()/semantic() are N/A on links.\n\n## Scoping (ADR-015; the root row since surface 2.0): bare names are LOCAL\n\n name the CURRENT row only \u2014 never falls through to an enclosing row\n or the repository; an absent field is simply absent.\n ^name one scope OUT (the enclosing row's fields/intrinsics/lifts);\n ^^name two scopes out. `^path` = the enclosing row's path.\n ^docs ^nodes ^blocks ^links\n THE ROOT ROW (surface 2.0, oqx 0.18): the repository is the root\n scope's row, one scope out from a top-level row, so ^docs there is\n the whole documents scan (uncorrelated until you add a ^ predicate);\n one caret per enclosing block (^^docs from depth two), or the\n absolute 0^docs from ANY depth. ^id / 0^id = the repository id.\n ^$it = the root object: ^$it.docs \u2261 ^docs, entries(^$it) names the\n four collections. At the root scope itself a bare target is the scan\n (docs count { \u2026 }, from docs, entries(docs)).\n ERRORS: a bare `docs` INSIDE a block reads a property of the current\n row, which has none \u2014 refused (\"did you mean ^docs\"); `^docs` AT THE\n TOP LEVEL reaches past the root \u2014 refused (write the bare `docs`);\n so is `$repo` (surface < 2.0; the message names the replacement).\n nodes/blocks on a doc row are that doc's RELATIONS, not the root.\n $it the current item itself (a row, or each ELEMENT when the\n receiver is a list property); ^$it = the enclosing row.\n $value is NOT an intrinsic (since oqx 0.15): it reads a\n property literally named $value, absent when there is none.\n $key the row's identity (0.20): a store row's id (doc/block/node/edge), an entries(x)\n entry's key, a follow occurrence's walk identity; project $key: <expr> to rekey the\n rows a block yields (a destination block's $key: is not a column).\n\n## Scalar semantics (@omgbase/oqx)\n\n comparisons == != < <= > >= strict & typed (5 == \"5\" is false); either\n side may be a field (field-vs-field OK).\n absence null and a missing field are the same \"absent\" value; two absents\n are EQUAL, so `absent != \"x\"` is TRUE and `absent == null` is TRUE.\n Relational (< <= > >=) on an absent operand \u2192 FALSE. Bare `f` in\n boolean position uses JS truthiness (absent/false/0/\"\" \u21D2 false;\n NOTE: \"false\", [] and {} are truthy). has(f) = explicit presence.\n boolean and or not grouping ( \u2026 ) \u2014 && || ! are accepted synonyms\n arithmetic + - * / % (+ concatenates if either side is a string)\n membership x in y array \u2192 typed membership; string \u2192 substring;\n object \u2192 key exists; range \u2192 coverage. Any list\n property works directly: \"pricing\" in tags. list(f)\n coerces scalar-or-list (absent \u2192 []) \u2014 use it when a\n key is sometimes scalar, sometimes a list.\n ranges lo..hi (inclusive) lo...hi (exclusive hi) ..hi lo..\n era in 800..1680; works over ISO dates. range(prop) reads a\n range-shaped STRING property as an interval: \"2026-01-15\" in range(window).\n strings x.contains(\"s\") x.startsWith(\"p\") x.endsWith(\"s\") x.matches(\"^re$\")\n (real regex) x.lower() x.upper() size(x). ALL CASE-SENSITIVE \u2014\n fold with .lower(): title.lower().contains(\"aurora\").\n functions has(f) size(x) list(x) entries(x) range(s)\n literals \"str\" 'str' 123 1.5 true false null\n determinism no now()/clock/random. Lists/structs are not literals; ternary is\n not supported. Errors surface as filter_invalid.\n scalars vs lists a list-authored key never == a scalar (tags == \"x\" is false\n when tags is a list) \u2014 use `\"x\" in tags` / `in list(tags)`.\n\n## Domain predicates (omgbase)\n\n text(\"terms\") FTS5 PRUNING predicate (docs match via their blocks, nodes\n via the node index); composes anywhere, incl. nested scopes.\n semantic(\"phrase\") embedding cosine SCORE (docs/blocks): threshold it\n (semantic(\"x\") > 0.6), project it, or `order by semantic(\"x\")\n desc` for top-K. Needs a provider that has embedded the repository; else provider_unavailable.\n blocks target only:\n under(id_or_heading) block in the containment subtree / section range\n under_heading(\"Launch\") an ancestor section heading contains the text (ci)\n under_kind(type[, name]) an ancestor block has that type (name: its text\n contains / its key equals name)\n within(\"path\" | \"d_..\") containing doc = id, exact path, or path glob (*);\n either path form\n yaml_path(\"a.b\") YAML docs: the block at that key path\n json_pointer(\"#/a/b\") JSON docs: the block at that pointer\n has_edge(\"pred\"[, target]) an open authored edge with that predicate leaves here\n has_anchor() block carries an authored ^ref\n parent_type() == \"x\" parent block's type (must be compared)\n child_count() > 0 number of direct children (must be compared)\n refs(x) the live documents a property's document references name:\n x is a string, a list or absent; each \"/a/b.md\", \"a/b.md\"\n or \"d_\u2026\" element resolves to that doc's row; dangling and\n non-string elements are dropped. Yields docs rows, so it is\n a source, a receiver or a follow destination:\n follow refs(before), refs(after) walks a timeline both ways.\n The reverse direction needs no function: a document's\n path is already the reference form, so\n ^docs { where ^path in list(after) } is\n \"the documents whose `after` names me\".\n A HIT IS A STORE ROW: a top-level row that is not a doc/block/node/edge fails\n (filter_invalid). `follow before` over a list of paths\n reaches the STRINGS \u2014 write `follow refs(before)`.\n\n## Nested queries & consumers\n\n <receiver> collect|exists|none|count|first|single { <block> }\n receiver = a relation (nodes, blocks, doc.out_links, section.blocks, \u2026), a\n reach-through row (dst, doc: one row \u2014 dst { title }), a\n list property (tags), entries(x), or a root collection (^docs; 0^docs at depth \u2265 2).\n block = [select \u2026] [from E] [where \u2026] [frontier \u2026] [follow \u2026] [order by \u2026] [limit N] [offset N]\n \u2014 the same fixed order as the top level (`from` optional; the\n receiver supplies the rows). A leading name/alias list is the\n projection (`select` dropped); a predicate always needs `where`.\n A `from E` inside a block RE-PROJECTS the rows through a relation\n (a typed flatMap): `docs collect { from nodes where kind == \"md:task\" }`\n starts at docs, projects each through `nodes`, and queries the\n resulting nodes; a scalar relation (`from doc`) contributes one\n row; a missing or non-navigable relation is a loud error, never a\n global scan.\n exists \u22651 row nodes exists { where kind == \"md:task\" and not checked }\n none 0 rows nodes none { where kind == \"md:task\" and not checked } (\"every task done\")\n count a number nodes count { where kind == \"md:task\" } >= 2\n collect rows (default) \u2014 in select for nested results; in where with a lift\n first / single zero-or-one (single errors on >1) \u2014 lookups in select\n distinct on any consumer: dedup by projected value \u2014 nodes count distinct { select kind }\n limit/offset bound the block's rows AFTER where/order/distinct, BEFORE the\n consumer reduces: nodes exists { offset 1 } = at least two;\n first { \u2026 offset 1 } = the second.\n lift `^name:` in a where-collect binds values outward:\n select path, open from docs where nodes collect { ^open: value where kind == \"md:task\" and not checked }\n joins ^<t> exists { where slug == ^ref } semi-join; not \u2026 exists anti-join;\n ^nodes single { where kind == \"person\" and attrs.id == ^owner_id } lookup;\n x in ^keys membership over a lifted set.\n\n## select \u2014 projection\n\n select a, alias: expr, nested: nodes collect { \u2026 }\n bare key \u2192 the attribute when it is one (id, path, title, \u2026), else the property\n (scalar-authored \u2192 scalar; list \u2192 array); data.<k> forces the property;\n a call/arithmetic needs an alias (n: size(tags)) unless in values mode;\n an output key of id/path other than the attribute itself needs an alias.\n raw whole file bytes (docs) \u2014 docs_read is cheaper for one doc.\n distinct select distinct type (dedup hits by projected value)\n values select <ONE item> values \u2192 bare values instead of records:\n select distinct type values from docs \u2192 values: [\"hub\",\"lab-note\",\u2026]\n select path values from docs \u2192 values: [\"/index.md\", \u2026]\n tags: tags collect { $it values } \u2192 a plain array\n h: nodes first { name values where kind == \"md:section\" order by first_ordinal }\n entries(x) a record as a collection ($key / $it per entry), key order:\n select fm: entries(data) collect { k: $key, v: $it }\n where entries(frontmatter) exists { where $key == \"era\" and $it > 1600 }\n entries(inline), entries(attrs), a nested map, or a list (index keys)\n $semantic_score is not a field \u2014 project semantic(\"\u2026\") under an alias instead.\n\n## order by, limit/offset, pagination\n\n order by era desc, path asc absent values sort LAST (asc); ties \u2192 (path, id)\n limit N / offset N define the result SET (integer literals);\n the tool's limit/cursor then page WITHIN it\n cursor opaque keyset on (path,id); a custom order by\n disables it (you get the top page + truncated)\n\n## Graph traversal (follow) and links\n\n The citation graph is the LINK ROWS walked through a destination block:\n dst is a link's destination document (absent for an external or dangling\n link \u2014 it then contributes no successor), doc its source.\n from docs where <seed> follow out_links collect { from dst } docs the seed links TO\n from docs where <seed> follow in_links collect { from doc } backlinks\n follow out_links collect { from dst depth 3 } bound (1..8, default 8) \u2014 a clause of the block\n follow out_links collect { from dst where layer == \"canon\" } keep only matching successors\n follow in_links collect { from doc where ^path in list(before) } ^ = the row being expanded\n (^^ = the walk's enclosing scope)\n follow out_links collect { from dst where predicate == \"depends_on\" } one predicate only\n follow out_links collect { from dst }, in_links collect { from doc }\n several destinations: their union\n (one step dedups by identity)\n follow ^docs { where out_links exists { where dst_path == ^^path } }\n a destination block over the root's\n documents, re-read per frontier row\n (^ = that row) = the backlinks walk\n follow out_links collect { from dst frontier type == \"practitioner\" } cut, keeping the frontier row\n from docs where type == \"process\" frontier !verified follow out_links collect { from dst }\n the BODY's frontier applies to the seeds:\n an unverified seed is kept, not expanded\n follow distinct out_links collect { from dst } / \u2026 { $key: group from dst } identity control ($key)\n follow refs(before), ^docs { where ^path in list(after) } forward over `before`, backward\n over every doc whose `after` names me\n Per-occurrence metadata: $depth (seed = 1), $stop (interior|leaf|frontier|\n depth|cycle), $leaf/$frontier, $ordinal (a deterministic 1..N rank over the\n walk, ordered by depth then path \u2014 `order by $ordinal` for walk order,\n `where $ordinal <= N` for a deterministic budget cut), $key \u2014 usable in\n select/order by and the top-level post-walk where (a where conjunct that\n reads one filters the walk's RESULT; the other conjuncts remain the seed\n predicate), NOT metadata of the candidates a destination block's where reads,\n nor valid inside a consumer directive. Cyclic graphs are safe: a revisited\n node is admitted once as a `$stop == \"cycle\"` occurrence and never\n re-expanded. The default keeps one occurrence per distinct walk path;\n `follow distinct` dedups reached rows by identity.\n Destination blocks (OQX 0.20): a brace after ANY destination opens that\n destination's block \u2014 children { depth 2 }, refs(x) { depth 2 }, out_links\n collect { from dst depth 2 }, ^docs { where ^path in list(after) } \u2014 with the\n 0.17 body rules (where-first, projections) and two clauses of its own after\n `where`: frontier <pred> (occurrences reached through this destination that\n match are frontiers; ^ there is the walk's enclosing scope) and depth <n>\n (this destination expands a frontier row only while $depth < n). The body\n that carries the follow may write frontier <pred> too, after its where and\n before follow: it applies to the SEEDS (read like the body's where) \u2014 a\n matching seed stays in the result with $stop == \"frontier\" and is not\n expanded; each destination's frontier is its own. There is no options block;\n the old `by` is $key. A bare follow ^docs (no brace, no consumer) is an\n error naming both block spellings.\n Type-preserving relations: block.children, section.children, section.subsections;\n the citation graph is out_links collect { from dst } / in_links collect { from doc }.\n from links where dst_path == \"/notes/x.md\" inbound links to a doc, as rows\n select d: dst.title, k: dst_kind from links the destination document's title\n from docs where out_links exists { where dst.layer == \"draft\" } links into drafts\n select b: in_links collect distinct { from doc } from docs backlinks as { id, path }\n select doc_id, dst_path from links where predicate == \"depends_on\"\n from docs where not doc.in_links exists { } orphans (nothing links in)\n (The `graph` tool is a convenience wrapper that compiles to a follow query.)\n\n## semantic grain\n\nfrom docs ranks whole DOCUMENTS (one hit per file); from blocks ranks PASSAGES.\ntext()/where prune the candidate set; only order by reweights.\n\n## Examples\n\n from docs where layer == \"working\"\n from docs where path.startsWith(\"/guides/\") and updated_at >= \"2026-08-01\"\n select layer, tags from docs where \"pricing\" in list(tags)\n from docs where inline.owner == \"alice\"\n from docs where title.lower().contains(\"q3 plan\")\n from docs where format == \"yaml\"\n from docs where type == \"practitioner\" order by era desc limit 2\n from docs where nodes none { where kind == \"md:task\" and not checked }\n from docs where tags exists { where $it == \"tria-prima\" }\n select fm: entries(data) collect { k: $key, v: $it } from docs where path == \"/x.md\"\n select owner_id, owner: ^nodes single { where kind == \"person\" and attrs.id == ^owner_id } from docs\n from blocks where type == \"task\" and not checked and under_heading(\"Launch\") and doc.layer == \"working\"\n from blocks where type == \"paragraph\" and has_edge(\"references\", \"d_92aaaaa\")\n select path, $depth from docs where path == \"/timeline/review.md\" follow refs(before), refs(after)\n select path, next: ^docs collect { path where ^path in list(before) } from docs where type == \"milestone\"\n select path, n: size(^docs), repo: ^id from docs limit 1\n select p: data.path, t: data.title from docs where has(data.path)\n docs { type == \"substance\" and not verified }\n select subject, process: ^docs[slug == ^subject]!.path from docs where type == \"lab-note\"\n select path, back: nodes first { select p: 0^docs collect { path where ^^path in list(after) } values } from docs where type == \"milestone\"\n select path, prior: refs(before) collect { path, when } from docs where type == \"milestone\"\n from blocks order by semantic(\"identity preservation across edits\") desc limit 10\n select uri from links where dst_kind == \"external\"\n docs count { where layer == \"canon\" }\n\nCommon mistake: `$path`/`$id` (the 2.x spelling) \u2014 omgbase has no $ names; write\n`path`/`id`. Another: `where tags == \"x\"` on a list-valued key is false \u2014 write\n`\"x\" in tags`. Another: `select data.path` \u2014 alias it (`p: data.path`).\n";
1
+ export declare const QUERY_SYNTAX = "# query \u2014 OQX syntax reference\n\nThe `query` tool takes ONE plain OQX string (+ optional `limit`/`cursor`, and\n`bare: true` to drop the automatic `id`/`path` envelope \u2014 needs a `select`).\nThere is no {from, filter, order} envelope: every concern is a clause of the\nstring. Two rules tell the two syntaxes apart: DOT navigation belongs to the\nhost object model (`doc.layer`, `section.blocks`, `dst.title`); WHITESPACE\nquery directives belong to OQX \u2014 a nested query is `<receiver> collect|exists|\ncount|first|single { <block> }` (a postfix directive + a `{ \u2026 }` block), never a\nmethod. Its distinctive power is the receiver-constrained nested query that\ncorrelates to the current row: `from docs where nodes exists { where kind ==\n\"md:task\" }` returns only the docs that themselves contain a matching node.\n\n [select <items>] from <target> [where <pred>] [frontier <pred>] [follow <dest> [{ \u2026 }], \u2026]\n [order by <expr> [asc|desc], \u2026] [limit N] [offset N]\n <target> count|exists|none|first|single { <block> } (scalar/one-row form: a bare target at the root scope)\n\nCLAUSE ORDER IS FIXED: select, from, where, frontier, follow, order by, limit, offset \u2014\neach at most once; an out-of-order clause is a parse error naming the order.\nOnly `select` may drop its keyword, and only as the first clause\n(`path, era from docs where \u2026`). A top-level predicate needs `where`, because\n`where` follows `from` (`era > 1600 from docs` is the clause-order error); a\nblock may LEAD with a predicate (see Sugar), but a predicate after a projection\nstill needs the keyword (`{ name where kind == \"md:task\" }`, not\n`{ name, kind == \"md:task\" }`); `from docs count` is an error (write\n`docs count { \u2026 }`). `where` and later `select` items may use the same body's\n`select` aliases (`select path, old: era < 1000 from docs where old`; an alias\nshadows a same-named field there). `and` / `or` / `not` are the connectives;\nthe symbols `&&` / `||` / `!` are accepted synonyms (the words are canonical and\nwhat `print` writes).\n\n## Sugar (OQX 0.17)\n\nEvery form here is shorthand for an explicit directive (the AST is the explicit form):\n nodes { kind == \"md:task\" } \u2261 nodes collect { where kind == \"md:task\" } \u2014 a receiver block with\n no consumer is collect; a block whose LEADING expression is a predicate\n (comparison, call, !/is/not, in, literal, (\u2026), a consumer test \u2014 anything\n but a bare name, a dotted path or a ^lift) is where-first. Bare names still\n project: nodes { name } \u2261 nodes collect { name }; filter a bare field with\n nodes { is checked }. Wherever a value stands (0.20), call arguments included:\n size(children { is checked }); x distinct { \u2026 } \u2261 x collect distinct { \u2026 }. After a\n follow destination too: follow children { depth 2 } is that destination's block.\n (a, b) a tuple (0.20): two or more expressions, concatenated one level flat \u2014 a value\n (size((tags, aliases)), \"x\" in (tags, aliases)) and a receiver ((a, b) { \u2026 },\n follow (before, after) { depth 2 }); (a) alone is grouping\n refs(x)[0] \u2261 refs(x) first { offset 0 } positional (integer literal or ${binding});\n out of range \u21D2 absent; refs(x)[0].path navigates the row\n ^docs[path == ^company] \u2261 ^docs first { where path == ^company } first match or absent\n ^docs[path == ^company]! \u2261 \u2026 single { \u2026 } required: exactly one, else filter_invalid\n title! required: title, or an error naming the expression (and the row's $key \u2014 its id)\n \u2014 never a filter, never a coercion (0!, \"\"! are values); tightest: a!.b vs a.b!\n is x / not x truthiness of x, and its negation (prefix; `not` \u2261 `!`)\n x is y / x is not y identity ($key: a store row's id, else structural) \u2014 compares rows, which == does not;\n x is null = absent; for scalars is \u2261 ==; comparison precedence, no chaining\n a and b / a or b the connectives (\u2261 && / ||: same precedence, short-circuit, value: data.title or path coalesces)\n boss: ^docs[path == ^manager], bossName: boss.title a select item may use the items to its LEFT\n Reserved words (never a bare field name): from where select is not and or, true false null.\n Contextual words (limit order offset follow collect count first distinct desc by in frontier depth) parse as\n fields in expression position (select o: order from docs).\n\nResults are LEAN hits \u2014 { id, path } + whatever `select` projects (or `values`,\n`count`, `exists`, `none`). The envelope keys ARE the attributes: copy a hit's\n`id` straight into `where id == \"\u2026\"` (no translation); `select id, path` is simply\nthe envelope (no duplicate columns); any OTHER projection whose output key would\nbe `id` or `path` must be aliased \u2014 `select data.path` is refused (\"projection\n`path` collides with the hit envelope \u2014 alias it (`p: data.path`)\"); a row\nsurfacing as a value (an empty `collect { }`) is the same `{ id, path }`. Every\nother tool spells a row the same way (`docs_read` \u2192 `{ id, path, rev, properties,\nraw }`, `blocks_read` \u2192 `{ id, type, text, raw, hash, \u2026 }`, `docs_list` \u2192 `{ id,\npath, updated_at, blocks }`, a revision \u2192 `{ id, path, hash }`): hydrate by id via\nblocks_read/docs_read.\n\n## Paths\n\nEvery path the surface returns is `/`-rooted \u2014 the form a reference is\nwritten in (`[x](/projects/oqx.md)`, `before: [/timeline/kickoff.md]`): a\nhit's `path`, an edge's `dst_path`, every tool's paths. Every path it\naccepts tolerates both forms (`/a.md` or `a.md`): tool arguments, `refs(x)`,\n`within(...)`, and a string LITERAL compared with `path`/`dst_path` (bare, or\nthrough a row handle: `doc.path`) by `==`/`!=` or passed to their\n`.startsWith(...)` (it is rooted first, so `path == \"a.md\"` and `path == \"/a.md\"`\nboth match). A property holding a reference compares directly \u2014 and is never\nrooted: `where ^path in list(after)`, `where customer == ^path`,\n`where data.path == \"/x.md\"` (the author's `path:` key, as written) \u2014 no\n`\"/\" + ...` glue.\n\n## Targets & field namespaces\n\nTHE NAME RULE: `$` belongs to OQX \u2014 $it, $key, $depth, $stop, $leaf, $frontier,\n$ordinal are values the LANGUAGE injects into a scope; omgbase adds NO $ names\n(a `$id` in a query is an unknown name, absent). Every engine attribute is a BARE\nsnake_case name that WINS on collision \u2014 the convention the relations (children,\nblocks, out, in, doc, frontmatter, \u2026) always followed: a bare name that is an\nengine attribute reads the engine's value, never yours. Your data is bare too;\nwhere a key of yours collides with an engine name, reach it through a source\nhandle: `data.<k>` (the merged authored view \u2014 frontmatter + inline, exactly the\nread a bare non-colliding key performs), `frontmatter.<k>`, `inline.<k>`. So\n`path` is the engine's /-rooted location and `data.path` your `path:` key;\n`tags` is your tags \u222A the body #hashtags and `data.tags` the authored list alone;\n`title` the computed title (the first H1) and `data.title` your `title:`;\n`entries(data)` lists every authored top-level key. Same value, same name\neverywhere: a hit's `id` is docs_read's `id` and the `id` argument of blocks_read.\n\n Reserved bare names per kind (engine attributes; handles; self; relations):\n docs id path raw hash updated_at title tags format | data frontmatter inline | doc | blocks nodes out_links in_links revisions\n blocks id path doc_id raw hash updated_at type text attrs depth ordinal | block doc | children nodes out_links section\n nodes id path doc_id block_id kind name value attrs | section doc block | blocks subsections children\n links id path doc_id block_id via_id dst_id dst_path uri field dst_kind predicate provenance anchor | doc\n revisions id path rev seq doc_id commit ts origin actor reason hash is_current | doc\n A key of yours with any of these names is `data.<k>` (or frontmatter.<k> /\n inline.<k> by source; attrs.<k> on a block or node).\n UNKNOWN NAMES: a name that is none of the above AND that no object of the\n kind in this repository carries is reported before any row is read \u2014 on\n links as a filter_invalid error naming the fields; on docs/blocks/nodes the\n result gains `hints` (one line per name, nearest match when there is one)\n and the rows still come back; in a plan/apply/execute selector it is refused.\n A property some objects carry is known (partial presence is normal).\n\ndocs:\n - bare identifier = a document PROPERTY (frontmatter + inline `key:: value`,\n unioned; nested via dots: meta.owner). YAML/JSON docs\n expose the parsed object's keys the same way.\n - source handles = data.<k> (merged authored view) / frontmatter.<k> /\n inline.<k>; the whole bag as a collection via entries(data)\n / entries(frontmatter) / entries(inline) (see entries()).\n - attributes = id, path (/-rooted, see Paths), updated_at (ISO-8601,\n sorts chronologically), raw (the whole file, frontmatter\n included), hash (its sha256, 64 hex), title (the computed\n title: the first H1; data.title is the authored key), tags\n (authored tags \u222A body #hashtags, deduped, authored first;\n data.tags is the authored list), format (the doc's format \u2014\n \"markdown\"/\"yaml\"/\"json\"; present on EVERY doc, so\n has(format) is always true and `format == \"yaml\"` is the\n filter).\n - relations = nodes, blocks, doc.out_links / doc.in_links (a doc's\n links as rows; the documents at their other end are\n out_links collect distinct { from dst } and\n in_links collect distinct { from doc } \u2014 there is no\n out / in relation), revisions (the document's stored\n revisions, oldest first \u2014 see revisions below).\n\nblocks:\n - bare fields = doc_id (the owning doc), type, text (normalized), ordinal\n (0-based among siblings), depth (0 at the top level), and\n every attrs key FLATTENED onto the row (bare `checked`\n reads attrs.checked; `attrs.<k>` still works; the\n structural fields win on collision; absent \u21D2 false).\n - attributes = id, path (the owning doc's path), raw (the block's raw\n source \u2014 a container's raw holds its children), hash\n (its sha256 \u2014 the value update/split expect as\n expect.content_hash), updated_at.\n - reach-through = doc.<key> / doc.path / doc.id / doc.format = the\n CONTAINING doc (doc.id and doc.path cost nothing \u2014 they\n read the row's own doc_id / joined path, no lookup).\n - relations = block.children, block.nodes, block.out_links, section.\n NOTE: inside a `follow`, $depth/$ordinal are ALWAYS the walk's metadata; a\n block's own nesting is `depth` / `ordinal` (no $) everywhere.\n\nnodes:\n - bare fields = doc_id, block_id (null for a block-less node), kind\n (md:task / md:link / md:section / yaml:\u2026), name, value,\n + attrs keys flattened (checked, level).\n - attributes = id, path.\n - reach-through = doc.<key> / doc.id / doc.path, block.type / block.text\n / block.id / block.path.\n - relations = section.blocks, section.children, section.subsections.\n\nlinks: (the authored link graph as rows \u2014 one per open link: the relation a link\n establishes; the md:link NODE is its occurrence in the text and via_id\n points at it \u2014 a frontmatter link has a row and no node)\n - bare fields = doc_id (the SOURCE doc), block_id (the source block; null\n for a frontmatter edge), via_id, dst_id (the destination\n node id: a doc id, an external node id or phantom:<path>),\n dst_path (target doc path, /-rooted; NULL when\n dangling/external), uri (external URL; NULL otherwise),\n predicate (\"references\"/\"embeds\"/freeform), provenance\n (\"link\"/\"frontmatter\"/\"inline_field\"/\u2026), dst_kind\n (\"document\"/\"external\"/\"collection\"), anchor, field (the\n frontmatter key / inline field it was authored in).\n - attributes = id, path (the SOURCE doc's path); doc.<key> reaches the\n source document. There is no from_commit: a query sees\n open edges only (history is blocks_history/changes_since).\n - text()/semantic() are N/A on links.\n\nrevisions: (history as rows \u2014 one per stored revision of every document of the\n repository, deleted documents included: what docs_history lists, queryable)\n - bare fields = rev (= id), seq (1, 2, \u2026 per document), doc_id, commit,\n ts (the commit's time, sorts chronologically), origin\n (\"observed\"/\"api\"/\"import\"/\"projection\"), actor, reason,\n hash (the rendered file's sha256 \u2014 docs_history's hash),\n is_current (true for the document's current revision).\n - attributes = id (the revision id, r_\u2026), path (the path the revision\n was committed under \u2014 a move re-paths only the current\n revision, so earlier ones keep the old path). doc.<key>\n reaches the document's CURRENT row; absent for a deleted\n document, so where doc == null is the revisions of deleted documents.\n - on docs = revisions is a relation (oldest first): a document with\n more than one version is docs { revisions count { } > 1 }.\n - text()/semantic() are N/A on revisions. The body as of a revision is\n docs_read { path, at: \"<rev>\" } (docs_read_at is the same call).\n\n## Scoping (ADR-015; the root row since surface 2.0): bare names are LOCAL\n\n name the CURRENT row only \u2014 never falls through to an enclosing row\n or the repository; an absent field is simply absent.\n ^name one scope OUT (the enclosing row's fields/intrinsics/lifts);\n ^^name two scopes out. `^path` = the enclosing row's path.\n ^docs ^nodes ^blocks ^links ^revisions\n THE ROOT ROW (surface 2.0, oqx 0.18): the repository is the root\n scope's row, one scope out from a top-level row, so ^docs there is\n the whole documents scan (uncorrelated until you add a ^ predicate);\n one caret per enclosing block (^^docs from depth two), or the\n absolute 0^docs from ANY depth. ^id / 0^id = the repository id.\n ^$it = the root object: ^$it.docs \u2261 ^docs, entries(^$it) names the\n five collections. At the root scope itself a bare target is the scan\n (docs count { \u2026 }, from docs, entries(docs)).\n ERRORS: a bare `docs` INSIDE a block reads a property of the current\n row, which has none \u2014 refused (\"did you mean ^docs\"); `^docs` AT THE\n TOP LEVEL reaches past the root \u2014 refused (write the bare `docs`);\n so is `$repo` (surface < 2.0; the message names the replacement).\n nodes/blocks on a doc row are that doc's RELATIONS, not the root.\n $it the current item itself (a row, or each ELEMENT when the\n receiver is a list property); ^$it = the enclosing row.\n $value is NOT an intrinsic (since oqx 0.15): it reads a\n property literally named $value, absent when there is none.\n $key the row's identity (0.20): a store row's id (doc/block/node/edge), an entries(x)\n entry's key, a follow occurrence's walk identity; project $key: <expr> to rekey the\n rows a block yields (a destination block's $key: is not a column).\n\n## Scalar semantics (@omgbase/oqx)\n\n comparisons == != < <= > >= strict & typed (5 == \"5\" is false); either\n side may be a field (field-vs-field OK).\n absence null and a missing field are the same \"absent\" value; two absents\n are EQUAL, so `absent != \"x\"` is TRUE and `absent == null` is TRUE.\n Relational (< <= > >=) on an absent operand \u2192 FALSE. Bare `f` in\n boolean position uses JS truthiness (absent/false/0/\"\" \u21D2 false;\n NOTE: \"false\", [] and {} are truthy). has(f) = explicit presence.\n boolean and or not grouping ( \u2026 ) \u2014 && || ! are accepted synonyms\n arithmetic + - * / % (+ concatenates if either side is a string)\n membership x in y array \u2192 typed membership; string \u2192 substring;\n object \u2192 key exists; range \u2192 coverage. Any list\n property works directly: \"pricing\" in tags. list(f)\n coerces scalar-or-list (absent \u2192 []) \u2014 use it when a\n key is sometimes scalar, sometimes a list.\n ranges lo..hi (inclusive) lo...hi (exclusive hi) ..hi lo..\n era in 800..1680; works over ISO dates. range(prop) reads a\n range-shaped STRING property as an interval: \"2026-01-15\" in range(window).\n strings x.contains(\"s\") x.startsWith(\"p\") x.endsWith(\"s\") x.matches(\"^re$\")\n (real regex) x.lower() x.upper() size(x). ALL CASE-SENSITIVE \u2014\n fold with .lower(): title.lower().contains(\"aurora\").\n Infix regex: x ~ \"re\" is x.matches(\"re\"); x ~* \"re\" is the\n case-insensitive match; x !~ \"re\" and x !~* \"re\" negate them.\n Unanchored unless the pattern anchors; an absent x is false\n under ~ and TRUE under !~ (not SQL's NULL).\n functions has(f) size(x) list(x) entries(x) range(s)\n literals \"str\" 'str' 123 1.5 true false null\n determinism no now()/clock/random. Lists/structs are not literals; ternary is\n not supported. Errors surface as filter_invalid.\n scalars vs lists a list-authored key never == a scalar (tags == \"x\" is false\n when tags is a list) \u2014 use `\"x\" in tags` / `in list(tags)`.\n\n## Domain predicates (omgbase)\n\n text(\"terms\") FTS5 PRUNING predicate (docs match via their blocks, nodes\n via the node index); composes anywhere, incl. nested scopes.\n semantic(\"phrase\") embedding cosine SCORE (docs/blocks): threshold it\n (semantic(\"x\") > 0.6), project it, or `order by semantic(\"x\")\n desc` for top-K. Needs a provider that has embedded the repository; else provider_unavailable.\n blocks target only:\n under(id_or_heading) block in the containment subtree / section range\n under_heading(\"Launch\") an ancestor section heading contains the text (ci)\n under_kind(type[, name]) an ancestor block has that type (name: its text\n contains / its key equals name)\n within(\"path\" | \"d_..\") containing doc = id, exact path, or path glob (*);\n either path form\n yaml_path(\"a.b\") YAML docs: the block at that key path\n json_pointer(\"#/a/b\") JSON docs: the block at that pointer\n has_edge(\"pred\"[, target]) an open authored edge with that predicate leaves here\n has_anchor() block carries an authored ^ref\n parent_type() == \"x\" parent block's type (must be compared)\n child_count() > 0 number of direct children (must be compared)\n refs(x) the live documents a property's document references name:\n x is a string, a list or absent; each \"/a/b.md\", \"a/b.md\"\n or \"d_\u2026\" element resolves to that doc's row; dangling and\n non-string elements are dropped. Yields docs rows, so it is\n a source, a receiver or a follow destination:\n follow refs(before), refs(after) walks a timeline both ways.\n The reverse direction needs no function: a document's\n path is already the reference form, so\n ^docs { where ^path in list(after) } is\n \"the documents whose `after` names me\".\n A HIT IS A STORE ROW: a top-level row that is not a doc/block/node/edge fails\n (filter_invalid). `follow before` over a list of paths\n reaches the STRINGS \u2014 write `follow refs(before)`.\n\n## Nested queries & consumers\n\n <receiver> collect|exists|none|count|first|single { <block> }\n receiver = a relation (nodes, blocks, doc.out_links, section.blocks, \u2026), a\n reach-through row (dst, doc: one row \u2014 dst { title }), a\n list property (tags), entries(x), or a root collection (^docs; 0^docs at depth \u2265 2).\n block = [select \u2026] [from E] [where \u2026] [frontier \u2026] [follow \u2026] [order by \u2026] [limit N] [offset N]\n \u2014 the same fixed order as the top level (`from` optional; the\n receiver supplies the rows). A leading name/alias list is the\n projection (`select` dropped); a predicate always needs `where`.\n A `from E` inside a block RE-PROJECTS the rows through a relation\n (a typed flatMap): `docs collect { from nodes where kind == \"md:task\" }`\n starts at docs, projects each through `nodes`, and queries the\n resulting nodes; a scalar relation (`from doc`) contributes one\n row; a missing or non-navigable relation is a loud error, never a\n global scan.\n exists \u22651 row nodes exists { where kind == \"md:task\" and not checked }\n none 0 rows nodes none { where kind == \"md:task\" and not checked } (\"every task done\")\n count a number nodes count { where kind == \"md:task\" } >= 2\n collect rows (default) \u2014 in select for nested results; in where with a lift\n first / single zero-or-one (single errors on >1) \u2014 lookups in select\n distinct on any consumer: dedup by projected value \u2014 nodes count distinct { select kind }\n limit/offset bound the block's rows AFTER where/order/distinct, BEFORE the\n consumer reduces: nodes exists { offset 1 } = at least two;\n first { \u2026 offset 1 } = the second.\n lift `^name:` in a where-collect binds values outward:\n select path, open from docs where nodes collect { ^open: value where kind == \"md:task\" and not checked }\n joins ^<t> exists { where slug == ^ref } semi-join; not \u2026 exists anti-join;\n ^nodes single { where kind == \"person\" and attrs.id == ^owner_id } lookup;\n x in ^keys membership over a lifted set.\n\n## select \u2014 projection\n\n select a, alias: expr, nested: nodes collect { \u2026 }\n bare key \u2192 the attribute when it is one (id, path, title, \u2026), else the property\n (scalar-authored \u2192 scalar; list \u2192 array); data.<k> forces the property;\n a call/arithmetic needs an alias (n: size(tags)) unless in values mode;\n an output key of id/path other than the attribute itself needs an alias.\n raw whole file bytes (docs) \u2014 docs_read is cheaper for one doc.\n distinct select distinct type (dedup hits by projected value)\n values select <ONE item> values \u2192 bare values instead of records:\n select distinct type values from docs \u2192 values: [\"hub\",\"lab-note\",\u2026]\n select path values from docs \u2192 values: [\"/index.md\", \u2026]\n tags: tags collect { $it values } \u2192 a plain array\n h: nodes first { name values where kind == \"md:section\" order by first_ordinal }\n entries(x) a record as a collection ($key / $it per entry), key order:\n select fm: entries(data) collect { k: $key, v: $it }\n where entries(frontmatter) exists { where $key == \"era\" and $it > 1600 }\n entries(inline), entries(attrs), a nested map, or a list (index keys)\n $semantic_score is not a field \u2014 project semantic(\"\u2026\") under an alias instead.\n\n## order by, limit/offset, pagination\n\n order by era desc, path asc absent values sort LAST (asc); ties \u2192 (path, id)\n limit N / offset N define the result SET (integer literals);\n the tool's limit/cursor then page WITHIN it\n cursor opaque keyset on (path,id); a custom order by\n disables it (you get the top page + truncated)\n\n## Graph traversal (follow) and links\n\n The citation graph is the LINK ROWS walked through a destination block:\n dst is a link's destination document (absent for an external or dangling\n link \u2014 it then contributes no successor), doc its source.\n from docs where <seed> follow out_links collect { from dst } docs the seed links TO\n from docs where <seed> follow in_links collect { from doc } backlinks\n follow out_links collect { from dst depth 3 } bound (1..8, default 8) \u2014 a clause of the block\n follow out_links collect { from dst where layer == \"canon\" } keep only matching successors\n follow in_links collect { from doc where ^path in list(before) } ^ = the row being expanded\n (^^ = the walk's enclosing scope)\n follow out_links collect { from dst where predicate == \"depends_on\" } one predicate only\n follow out_links collect { from dst }, in_links collect { from doc }\n several destinations: their union\n (one step dedups by identity)\n follow ^docs { where out_links exists { where dst_path == ^^path } }\n a destination block over the root's\n documents, re-read per frontier row\n (^ = that row) = the backlinks walk\n follow out_links collect { from dst frontier type == \"practitioner\" } cut, keeping the frontier row\n from docs where type == \"process\" frontier !verified follow out_links collect { from dst }\n the BODY's frontier applies to the seeds:\n an unverified seed is kept, not expanded\n follow distinct out_links collect { from dst } / \u2026 { $key: group from dst } identity control ($key)\n follow refs(before), ^docs { where ^path in list(after) } forward over `before`, backward\n over every doc whose `after` names me\n Per-occurrence metadata: $depth (seed = 1), $stop (interior|leaf|frontier|\n depth|cycle), $leaf/$frontier, $ordinal (a deterministic 1..N rank over the\n walk, ordered by depth then path \u2014 `order by $ordinal` for walk order,\n `where $ordinal <= N` for a deterministic budget cut), $key \u2014 usable in\n select/order by and the top-level post-walk where (a where conjunct that\n reads one filters the walk's RESULT; the other conjuncts remain the seed\n predicate), NOT metadata of the candidates a destination block's where reads,\n nor valid inside a consumer directive. Cyclic graphs are safe: a revisited\n node is admitted once as a `$stop == \"cycle\"` occurrence and never\n re-expanded. The default keeps one occurrence per distinct walk path;\n `follow distinct` dedups reached rows by identity.\n Destination blocks (OQX 0.20): a brace after ANY destination opens that\n destination's block \u2014 children { depth 2 }, refs(x) { depth 2 }, out_links\n collect { from dst depth 2 }, ^docs { where ^path in list(after) } \u2014 with the\n 0.17 body rules (where-first, projections) and two clauses of its own after\n `where`: frontier <pred> (occurrences reached through this destination that\n match are frontiers; ^ there is the walk's enclosing scope) and depth <n>\n (this destination expands a frontier row only while $depth < n). The body\n that carries the follow may write frontier <pred> too, after its where and\n before follow: it applies to the SEEDS (read like the body's where) \u2014 a\n matching seed stays in the result with $stop == \"frontier\" and is not\n expanded; each destination's frontier is its own. There is no options block;\n the old `by` is $key. A bare follow ^docs (no brace, no consumer) is an\n error naming both block spellings.\n Type-preserving relations: block.children, section.children, section.subsections;\n the citation graph is out_links collect { from dst } / in_links collect { from doc }.\n from links where dst_path == \"/notes/x.md\" inbound links to a doc, as rows\n select d: dst.title, k: dst_kind from links the destination document's title\n from docs where out_links exists { where dst.layer == \"draft\" } links into drafts\n select b: in_links collect distinct { from doc } from docs backlinks as { id, path }\n select doc_id, dst_path from links where predicate == \"depends_on\"\n from docs where not doc.in_links exists { } orphans (nothing links in)\n (The `graph` tool is a convenience wrapper that compiles to a follow query.)\n\n## semantic grain\n\nfrom docs ranks whole DOCUMENTS (one hit per file); from blocks ranks PASSAGES.\ntext()/where prune the candidate set; only order by reweights.\n\n## Examples\n\n from docs where layer == \"working\"\n from docs where path.startsWith(\"/guides/\") and updated_at >= \"2026-08-01\"\n select layer, tags from docs where \"pricing\" in list(tags)\n from docs where inline.owner == \"alice\"\n from docs where title.lower().contains(\"q3 plan\")\n from docs where format == \"yaml\"\n from docs where type == \"practitioner\" order by era desc limit 2\n from docs where nodes none { where kind == \"md:task\" and not checked }\n from docs where tags exists { where $it == \"tria-prima\" }\n select fm: entries(data) collect { k: $key, v: $it } from docs where path == \"/x.md\"\n select owner_id, owner: ^nodes single { where kind == \"person\" and attrs.id == ^owner_id } from docs\n from blocks where type == \"task\" and not checked and under_heading(\"Launch\") and doc.layer == \"working\"\n from blocks where type == \"paragraph\" and has_edge(\"references\", \"d_92aaaaa\")\n select path, $depth from docs where path == \"/timeline/review.md\" follow refs(before), refs(after)\n select path, next: ^docs collect { path where ^path in list(before) } from docs where type == \"milestone\"\n select path, n: size(^docs), repo: ^id from docs limit 1\n select p: data.path, t: data.title from docs where has(data.path)\n docs { type == \"substance\" and not verified }\n select subject, process: ^docs[slug == ^subject]!.path from docs where type == \"lab-note\"\n select path, back: nodes first { select p: 0^docs collect { path where ^^path in list(after) } values } from docs where type == \"milestone\"\n select path, prior: refs(before) collect { path, when } from docs where type == \"milestone\"\n from blocks order by semantic(\"identity preservation across edits\") desc limit 10\n select uri from links where dst_kind == \"external\"\n docs count { where layer == \"canon\" }\n select seq, origin, ts, hash from revisions where path == \"/processes/calcination.md\" order by seq desc\n from docs where revisions count { where origin == \"api\" } > 0\n select p: path, d: doc.path from revisions where doc == null\n\nCommon mistake: `$path`/`$id` (the 2.x spelling) \u2014 omgbase has no $ names; write\n`path`/`id`. Another: `where tags == \"x\"` on a list-valued key is false \u2014 write\n`\"x\" in tags`. Another: `select data.path` \u2014 alias it (`p: data.path`).\n";
@@ -109,12 +109,19 @@ read a bare non-colliding key performs), \`frontmatter.<k>\`, \`inline.<k>\`. So
109
109
  everywhere: a hit's \`id\` is docs_read's \`id\` and the \`id\` argument of blocks_read.
110
110
 
111
111
  Reserved bare names per kind (engine attributes; handles; self; relations):
112
- docs id path raw hash updated_at title tags format | data frontmatter inline | doc | blocks nodes out in out_links in_links
112
+ docs id path raw hash updated_at title tags format | data frontmatter inline | doc | blocks nodes out_links in_links revisions
113
113
  blocks id path doc_id raw hash updated_at type text attrs depth ordinal | block doc | children nodes out_links section
114
114
  nodes id path doc_id block_id kind name value attrs | section doc block | blocks subsections children
115
115
  links id path doc_id block_id via_id dst_id dst_path uri field dst_kind predicate provenance anchor | doc
116
+ revisions id path rev seq doc_id commit ts origin actor reason hash is_current | doc
116
117
  A key of yours with any of these names is \`data.<k>\` (or frontmatter.<k> /
117
118
  inline.<k> by source; attrs.<k> on a block or node).
119
+ UNKNOWN NAMES: a name that is none of the above AND that no object of the
120
+ kind in this repository carries is reported before any row is read — on
121
+ links as a filter_invalid error naming the fields; on docs/blocks/nodes the
122
+ result gains \`hints\` (one line per name, nearest match when there is one)
123
+ and the rows still come back; in a plan/apply/execute selector it is refused.
124
+ A property some objects carry is known (partial presence is normal).
118
125
 
119
126
  docs:
120
127
  - bare identifier = a document PROPERTY (frontmatter + inline \`key:: value\`,
@@ -136,7 +143,8 @@ docs:
136
143
  links as rows; the documents at their other end are
137
144
  out_links collect distinct { from dst } and
138
145
  in_links collect distinct { from doc } — there is no
139
- out / in relation).
146
+ out / in relation), revisions (the document's stored
147
+ revisions, oldest first — see revisions below).
140
148
 
141
149
  blocks:
142
150
  - bare fields = doc_id (the owning doc), type, text (normalized), ordinal
@@ -181,20 +189,37 @@ links: (the authored link graph as rows — one per open link: the relation a l
181
189
  open edges only (history is blocks_history/changes_since).
182
190
  - text()/semantic() are N/A on links.
183
191
 
192
+ revisions: (history as rows — one per stored revision of every document of the
193
+ repository, deleted documents included: what docs_history lists, queryable)
194
+ - bare fields = rev (= id), seq (1, 2, … per document), doc_id, commit,
195
+ ts (the commit's time, sorts chronologically), origin
196
+ ("observed"/"api"/"import"/"projection"), actor, reason,
197
+ hash (the rendered file's sha256 — docs_history's hash),
198
+ is_current (true for the document's current revision).
199
+ - attributes = id (the revision id, r_…), path (the path the revision
200
+ was committed under — a move re-paths only the current
201
+ revision, so earlier ones keep the old path). doc.<key>
202
+ reaches the document's CURRENT row; absent for a deleted
203
+ document, so where doc == null is the revisions of deleted documents.
204
+ - on docs = revisions is a relation (oldest first): a document with
205
+ more than one version is docs { revisions count { } > 1 }.
206
+ - text()/semantic() are N/A on revisions. The body as of a revision is
207
+ docs_read { path, at: "<rev>" } (docs_read_at is the same call).
208
+
184
209
  ## Scoping (ADR-015; the root row since surface 2.0): bare names are LOCAL
185
210
 
186
211
  name the CURRENT row only — never falls through to an enclosing row
187
212
  or the repository; an absent field is simply absent.
188
213
  ^name one scope OUT (the enclosing row's fields/intrinsics/lifts);
189
214
  ^^name two scopes out. \`^path\` = the enclosing row's path.
190
- ^docs ^nodes ^blocks ^links
215
+ ^docs ^nodes ^blocks ^links ^revisions
191
216
  THE ROOT ROW (surface 2.0, oqx 0.18): the repository is the root
192
217
  scope's row, one scope out from a top-level row, so ^docs there is
193
218
  the whole documents scan (uncorrelated until you add a ^ predicate);
194
219
  one caret per enclosing block (^^docs from depth two), or the
195
220
  absolute 0^docs from ANY depth. ^id / 0^id = the repository id.
196
221
  ^$it = the root object: ^$it.docs ≡ ^docs, entries(^$it) names the
197
- four collections. At the root scope itself a bare target is the scan
222
+ five collections. At the root scope itself a bare target is the scan
198
223
  (docs count { … }, from docs, entries(docs)).
199
224
  ERRORS: a bare \`docs\` INSIDE a block reads a property of the current
200
225
  row, which has none — refused ("did you mean ^docs"); \`^docs\` AT THE
@@ -231,6 +256,10 @@ links: (the authored link graph as rows — one per open link: the relation a l
231
256
  strings x.contains("s") x.startsWith("p") x.endsWith("s") x.matches("^re$")
232
257
  (real regex) x.lower() x.upper() size(x). ALL CASE-SENSITIVE —
233
258
  fold with .lower(): title.lower().contains("aurora").
259
+ Infix regex: x ~ "re" is x.matches("re"); x ~* "re" is the
260
+ case-insensitive match; x !~ "re" and x !~* "re" negate them.
261
+ Unanchored unless the pattern anchors; an absent x is false
262
+ under ~ and TRUE under !~ (not SQL's NULL).
234
263
  functions has(f) size(x) list(x) entries(x) range(s)
235
264
  literals "str" 'str' 123 1.5 true false null
236
265
  determinism no now()/clock/random. Lists/structs are not literals; ternary is
@@ -422,6 +451,9 @@ text()/where prune the candidate set; only order by reweights.
422
451
  from blocks order by semantic("identity preservation across edits") desc limit 10
423
452
  select uri from links where dst_kind == "external"
424
453
  docs count { where layer == "canon" }
454
+ select seq, origin, ts, hash from revisions where path == "/processes/calcination.md" order by seq desc
455
+ from docs where revisions count { where origin == "api" } > 0
456
+ select p: path, d: doc.path from revisions where doc == null
425
457
 
426
458
  Common mistake: \`$path\`/\`$id\` (the 2.x spelling) — omgbase has no $ names; write
427
459
  \`path\`/\`id\`. Another: \`where tags == "x"\` on a list-valued key is false — write