@ai-matrx/records 0.99.14 → 0.99.16

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 (50) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/{client-BhrN1XK2.d.cts → client-D8vzRl-L.d.cts} +2 -83
  3. package/dist/{client-BTUMagai.d.ts → client-DuoWeGcM.d.ts} +2 -83
  4. package/dist/core/index.cjs +6 -6
  5. package/dist/core/index.cjs.map +1 -1
  6. package/dist/core/index.d.cts +4 -3
  7. package/dist/core/index.d.ts +4 -3
  8. package/dist/core/index.js +6 -6
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/data/index.cjs +6 -6
  11. package/dist/data/index.cjs.map +1 -1
  12. package/dist/data/index.d.cts +2 -1
  13. package/dist/data/index.d.ts +2 -1
  14. package/dist/data/index.js +6 -6
  15. package/dist/data/index.js.map +1 -1
  16. package/dist/{declareTable-D8Mq6wNq.d.ts → declareTable-DO8U62Pf.d.ts} +1 -1
  17. package/dist/{declareTable-BU3IURyS.d.cts → declareTable-T0LWvfIO.d.cts} +1 -1
  18. package/dist/index.d.cts +3 -2
  19. package/dist/index.d.ts +3 -2
  20. package/dist/questions/index.d.cts +2 -1
  21. package/dist/questions/index.d.ts +2 -1
  22. package/dist/react/index.cjs +20 -20
  23. package/dist/react/index.cjs.map +1 -1
  24. package/dist/react/index.js +18 -18
  25. package/dist/react/index.js.map +1 -1
  26. package/dist/scopes/index.cjs +2 -2
  27. package/dist/scopes/index.cjs.map +1 -1
  28. package/dist/scopes/index.js +2 -2
  29. package/dist/scopes/index.js.map +1 -1
  30. package/dist/setup/index.cjs +8 -8
  31. package/dist/setup/index.cjs.map +1 -1
  32. package/dist/setup/index.d.cts +2 -1
  33. package/dist/setup/index.d.ts +2 -1
  34. package/dist/setup/index.js +8 -8
  35. package/dist/setup/index.js.map +1 -1
  36. package/dist/table-kind/index.cjs +421 -0
  37. package/dist/table-kind/index.cjs.map +1 -0
  38. package/dist/table-kind/index.d.cts +83 -0
  39. package/dist/table-kind/index.d.ts +83 -0
  40. package/dist/table-kind/index.js +400 -0
  41. package/dist/table-kind/index.js.map +1 -0
  42. package/dist/typed-table/index.cjs +3 -3
  43. package/dist/typed-table/index.cjs.map +1 -1
  44. package/dist/typed-table/index.d.cts +3 -2
  45. package/dist/typed-table/index.d.ts +3 -2
  46. package/dist/typed-table/index.js +3 -3
  47. package/dist/typed-table/index.js.map +1 -1
  48. package/dist/views/index.d.cts +2 -1
  49. package/dist/views/index.d.ts +2 -1
  50. package/package.json +12 -2
@@ -83,6 +83,7 @@ var CONTEXT_FIELD_KINDS = [
83
83
  var SYSTEM_CONTEXT_TYPE_ID = "__system__";
84
84
 
85
85
  // src/scopes/codec.ts
86
+ var import_uuid = require("@ai-matrx/kit/uuid");
86
87
  var str = (v, fallback = "") => typeof v === "string" ? v : fallback;
87
88
  var strOrNull = (v) => typeof v === "string" ? v : null;
88
89
  var num = (v, fallback = 0) => {
@@ -298,7 +299,6 @@ function systemContextFieldFromStore(row, index) {
298
299
  item_class: strOrNull(row.item_class)
299
300
  };
300
301
  }
301
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
302
302
  function referencesOf(row) {
303
303
  const v = row.value;
304
304
  const list = Array.isArray(v) ? v : v == null ? [] : [v];
@@ -308,7 +308,7 @@ function referencesOf(row) {
308
308
  const out = [];
309
309
  for (const el of list) {
310
310
  let ref = null;
311
- if (typeof el === "string" && UUID.test(el)) ref = { id: el, type: toFile ? "file" : "scope" };
311
+ if (typeof el === "string" && (0, import_uuid.isUuidShape)(el)) ref = { id: el, type: toFile ? "file" : "scope" };
312
312
  else if (el && typeof el === "object" && typeof el.id === "string") {
313
313
  const token = String(el.token ?? "");
314
314
  const own = el.label;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/scopes/index.ts","../../src/scopes/types.ts","../../src/scopes/codec.ts","../../src/scopes/rules.ts","../../src/scopes/doors.ts","../../src/scopes/resolve.ts"],"sourcesContent":["// src/scopes/index.ts — @ai-matrx/records/scopes (HEADLESS)\n//\n// SCOPES ARE CUSTOM DATA: a scope type is a Table kept for context, a scope a Record of it, a context\n// field a Field (column), a value its cell. This section is the shapes, the doors (`client.scopes`,\n// built from the client's own door path), and the few rules a screen needs. Zero React, zero DOM.\n// Managing (building types, fields, scopes) and using (picking, reading values, sending to an agent)\n// both go through here; nothing outside this package calls a `custom.context_*` door.\n\nexport * from \"./types\";\nexport {\n createScopeDoors,\n SCOPES_PER_CALL,\n FIELD_KERNEL_ID,\n SCOPE_TYPES_PER_FIELDS_CALL,\n SCOPES_PER_VALUES_CALL,\n TYPE_SCOPES_PAGE,\n ARCHIVED_SCOPES_PAGE,\n type ScopeDoors,\n type ScopeDoorCall,\n} from \"./doors\";\nexport {\n contextFieldKind,\n contextFieldFromStore,\n systemContextFieldFromStore,\n type StoreSystemItemRow,\n contextValueFromStore,\n scopeFromStore,\n scopeTypeFromStore,\n scopeWithTypeFromStore,\n settingFromStore,\n referencesOf,\n referenceFence,\n referencesFromFence,\n contextValueWrite,\n completeWholeValues,\n incompleteSaveRefusal,\n INCOMPLETE_SAVE_REFUSAL,\n FILE_KERNEL_ID,\n type ReadContextFileText,\n} from \"./codec\";\nexport {\n canShapeScopeType,\n toSlug,\n toFieldKey,\n isValidSlug,\n isReservedSlug,\n sameSlug,\n resolveSlug,\n RESERVED_SCOPE_SLUGS,\n type ScopeSeatRole,\n} from \"./rules\";\nexport {\n joinFieldValues,\n hasCell,\n resolveScopeContext,\n toResolvedValue,\n type ScopeFieldValue,\n type ContextSource,\n type ContextSourceKind,\n type ContextSourceOrigin,\n type ResolvedValue,\n type ScopeContradiction,\n type ResolvedScopeContext,\n type ResolveScopeContextInput,\n} from \"./resolve\";\n","// src/scopes/types.ts — @ai-matrx/records/scopes\n//\n// SCOPES ARE CUSTOM DATA (Arman, 2026-10-09: \"Scopes are now nothing more than custom data… A scope\n// type is nothing more than a row [a custom Table flagged kept_for='context'], a context item is\n// nothing more than a column.\").\n//\n// scope type a Table of the store kept for context (`kept_for = 'context'`)\n// scope a Record of that Table\n// context field a Field (column) of that Table — what the old screens called a \"context item\"\n// context value the Record's cell under the Field's key\n//\n// These are the shapes the `custom.context_*` doors answer, in the store's words. Nothing here is a\n// row of the archived `context.*` tables, and nothing re-creates one: a value is the cell (`value`),\n// never a set of `value_text` / `value_number` / … columns; a field says `context_policy` and the\n// store's `sensitivity`, never the old `fetch_hint` words.\n\nimport type { Uuid } from \"../record\";\n\n/**\n * What a context field holds, as a person thinks of it — derived from the Field's behaviour, `multi`,\n * `format`, display format and `config.kind` (`contextFieldKind`). The value is always `value`; the\n * kind says how to read and edit it.\n */\nexport type ContextFieldKind =\n | \"string\"\n | \"markdown\"\n | \"email\"\n | \"url\"\n | \"phone\"\n | \"color\"\n | \"number\"\n | \"percent\"\n | \"currency\"\n | \"boolean\"\n | \"date\"\n | \"datetime\"\n | \"time\"\n | \"object\"\n | \"array\"\n | \"reference\"\n | \"document\";\n\nexport const CONTEXT_FIELD_KINDS: readonly ContextFieldKind[] = [\n \"string\",\n \"markdown\",\n \"email\",\n \"url\",\n \"phone\",\n \"color\",\n \"number\",\n \"percent\",\n \"currency\",\n \"boolean\",\n \"date\",\n \"datetime\",\n \"time\",\n \"object\",\n \"array\",\n \"reference\",\n \"document\",\n];\n\n/** The store's context policy on a Field: whether an agent receives it every turn, on request, or never. */\nexport type ContextPolicy = \"include\" | \"on_request\" | \"exclude\";\n\n/** The store's sensitivity words on a Field. */\nexport type ContextSensitivity = \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n/** A scope type: a Table kept for context. */\nexport interface ScopeType {\n id: Uuid;\n organization_id: Uuid;\n label_singular: string;\n label_plural: string;\n icon: string;\n color: string;\n /** The Table's slug in the store's grammar (`practice_areas`). */\n slug: string | null;\n description: string;\n sort_order: number;\n max_assignments_per_entity: number | null;\n default_variable_keys: string[];\n /** Who made the type: with the organization's owners and admins, they shape it (`canShapeScopeType`). */\n created_by: Uuid | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A scope type with its live scopes, as the tree doors answer it. */\nexport interface ScopeTypeWithScopes extends ScopeType {\n scopes: Scope[];\n}\n\n/** A scope: a Record of its type's Table. */\nexport interface Scope {\n id: Uuid;\n scope_type_id: Uuid;\n organization_id: Uuid;\n name: string;\n description: string;\n slug: string | null;\n sort_order: number;\n parent_scope_id: Uuid | null;\n /** Free settings keys of the scope (each a Field of its Table the scope door derived). */\n settings: Record<string, unknown>;\n created_by: Uuid | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A scope with its type's presentation (`custom.context_scopes`). */\nexport interface ScopeWithType extends Scope {\n scope_type: ScopeTypeLabel | null;\n}\n\n/** The presentation of a scope type: what a chip or a breadcrumb shows. */\nexport interface ScopeTypeLabel {\n id: Uuid;\n /** The type's slug in the store's grammar (`practice_areas`), when it has one. */\n slug: string | null;\n label_singular: string;\n label_plural: string;\n icon: string | null;\n color: string | null;\n}\n\n/** A scope type that was archived, with how many scopes went with it. */\nexport interface ArchivedScopeType {\n id: Uuid;\n organization_id: Uuid;\n label_singular: string;\n label_plural: string;\n icon: string;\n color: string;\n archived_at: string;\n created_by: Uuid | null;\n archived_scope_count: number;\n}\n\n/** A scope that was archived (a Record in the archive of its type's Table). */\nexport interface ArchivedScope {\n id: Uuid;\n name: string | null;\n slug: string | null;\n archived_at: string | null;\n}\n\n/** A context field: a Field (column) of a scope type's Table. */\nexport interface ContextField {\n id: Uuid;\n scope_type_id: Uuid;\n organization_id: Uuid;\n key: string;\n label: string;\n description: string;\n kind: ContextFieldKind;\n /** The Field's own words, for a caller that needs them (`type` is the store's behaviour word). */\n type: string;\n multi: boolean;\n format: string | null;\n config: Record<string, unknown>;\n relation_target: Uuid | null;\n /** Its place among the type's context fields, from 0. */\n sort: number;\n context_policy: ContextPolicy;\n sensitivity: ContextSensitivity;\n source: string;\n status: string;\n status_note: string | null;\n category: string | null;\n tags: string[];\n max_items: number;\n custom_component: unknown;\n reference_source: unknown;\n allowed_scope_type_ids: Uuid[] | null;\n allowed_reference_types: string[] | null;\n review_interval_days: number | null;\n depends_on: string[];\n /** The store's clock on this Field. */\n version: number;\n created_by: Uuid | null;\n created_at: string;\n updated_at: string;\n}\n\n/** One thing a reference cell points at. */\nexport interface ContextReference {\n /** The record id (for a file: the File record's id). */\n id: Uuid;\n /** What it is: `scope`, `file`, `table`, or another entity token. */\n type: string;\n /** Its name, where the door named it to this caller. */\n label?: string;\n /** For a file: the `files.files` id a viewer opens. */\n file_id?: Uuid;\n}\n\n/** The cell holds only the first words of a text kept as a file, and the whole could not be read. */\nexport interface IncompleteValue {\n /** The cell's own first words. */\n head: string;\n /** The whole text's length in characters, when known. */\n chars: number | null;\n /** The file holding the whole text, when it has one yet. */\n file_id: Uuid | null;\n /** Why the whole text is not here, in one sentence. */\n why: string;\n}\n\n/** A context value: one cell of a scope's Record. */\nexport interface ContextValue {\n scope_id: Uuid;\n field_id: Uuid;\n key: string;\n kind: ContextFieldKind;\n /**\n * THE CELL, as the store holds it (a text, a number, a boolean, an ISO date, a list, an object).\n * A reference or document cell is its `references` (ids here). A text kept as a file is its whole\n * text when the read could open the file (`completeWholeValues`), else the first words and `incomplete`.\n */\n value: unknown;\n /** A reference / document cell, decoded: what it points at, with names the caller may see. */\n references: ContextReference[];\n /** The version a PERSON made (system rewrites never move it). */\n version: number;\n set_at: string | null;\n source_type: string | null;\n authored_by: Uuid | null;\n /** The pointer to the file holding a text too big for one cell, when the cell holds only its start. */\n whole_value: StoreWholeValue | null;\n /** Present only when `value` is not the whole text — never save it back as the value. */\n incomplete: IncompleteValue | null;\n}\n\n/** The file fields of a whole-value pointer, as `custom.context_values` answers them. */\nexport interface StoreWholeValue {\n kind: string;\n file_id?: Uuid | null;\n file_record?: Uuid | null;\n bytes?: number | null;\n chars?: number | null;\n sha256?: string | null;\n shown_chars?: number | null;\n mime?: string | null;\n pending?: boolean | null;\n in_value?: boolean | null;\n}\n\n/** The scope types of some organizations, without their scopes, and how many each holds. */\nexport interface ScopeTypeSkeleton {\n types: ScopeType[];\n /** type id → how many scopes the caller sees in it; null when asked without counts. */\n counts: Record<Uuid, number> | null;\n}\n\n/** One page of one type's scopes. */\nexport interface ScopePage {\n scopes: Scope[];\n total: number;\n next_offset: number | null;\n}\n\n/**\n * The pseudo scope-type id a System Context field carries. System Context (what is simply TRUE on the\n * platform) has no scope type; its fields share this sentinel so a holder can keep them beside a\n * type's fields. A client-side key only — a binding to one of these carries `scope_type_id: null`.\n */\nexport const SYSTEM_CONTEXT_TYPE_ID = \"__system__\";\n\n/** What a System Context item is: a curated fact, an ambient fact of the moment, or a dataset. */\nexport type SystemContextItemClass = \"curated\" | \"ambient\" | \"dataset\" | (string & {});\n\n/**\n * A System Context item (`custom.context_system_items`), as a `ContextField` of the\n * `SYSTEM_CONTEXT_TYPE_ID` pseudo-type, plus its class.\n */\nexport interface SystemContextField extends ContextField {\n item_class: SystemContextItemClass | null;\n}\n\n/** One column of a table template. */\nexport interface TableTemplateField {\n field_name: string;\n display_name: string;\n data_type: string;\n field_order: number;\n is_required: boolean;\n}\n\n/**\n * A table template (a `custom.template` of kind `table`) a scope's dataset field may lock its\n * table's columns to: the organization's own or a platform one, as `custom.table_templates` answers it.\n */\nexport interface TableTemplate {\n id: Uuid;\n organization_id: Uuid | null;\n name: string;\n description: string;\n version: number;\n is_platform: boolean;\n fields: TableTemplateField[];\n}\n\n/** One scope template of the gallery, as `custom.context_templates` answers it. */\nexport interface ScopeTemplate {\n [key: string]: unknown;\n}\n\n// ─── writes ──────────────────────────────────────────────────────────────────────────────────────\n\n/** A new scope type, or the parts of one to change (`undefined` = leave as it is). */\nexport interface ScopeTypeSpec {\n label_singular?: string;\n label_plural?: string;\n icon?: string;\n color?: string;\n description?: string;\n sort_order?: number;\n max_assignments_per_entity?: number | null;\n default_variable_keys?: string[];\n /** Any spelling; the package writes it in the store's grammar. Absent on create = from the label. */\n slug?: string;\n}\n\n/** A new scope, or the parts of one to change. */\nexport interface ScopeSpec {\n name?: string;\n description?: string;\n settings?: Record<string, unknown>;\n parent_scope_id?: Uuid | null;\n slug?: string;\n sort_order?: number;\n}\n\n/** A new context field, or the parts of one to change (`null` clears). */\nexport interface ContextFieldSpec {\n key?: string;\n label?: string;\n kind?: ContextFieldKind;\n description?: string;\n category?: string | null;\n context_policy?: ContextPolicy;\n sensitivity?: ContextSensitivity;\n tags?: string[];\n sort?: number;\n status?: string;\n status_note?: string | null;\n custom_component?: unknown;\n review_interval_days?: number | null;\n allowed_reference_types?: string[] | null;\n max_items?: number | null;\n allowed_scope_type_ids?: Uuid[] | null;\n reference_source?: unknown;\n}\n\n/** One cell to write. `value` is the cell as `ContextValue.value` reads it; a reference cell takes `references`. */\nexport interface ContextValueWrite {\n scope_id: Uuid;\n field_id: Uuid;\n kind: ContextFieldKind;\n value?: unknown;\n /** A reference / document cell: the things it points at (replaces the cell). */\n references?: ContextReference[];\n /** Who wrote it: `manual` from a person's own edit (the store's default is `ai_enriched`). */\n source_type?: string;\n change_summary?: string;\n}\n\n/** What a written cell answers. */\nexport interface ContextValueWritten {\n scope_id: Uuid;\n field_id: Uuid;\n version: number;\n source_type: string;\n}\n","// src/scopes/codec.ts — @ai-matrx/records/scopes\n//\n// THE ONE PLACE THE SCOPE DOORS' WORDS ARE READ AND WRITTEN.\n//\n// The `custom.context_*` doors answer the store's rows (a Table, a Record, a Field document, a\n// cell) and, for the write doors, still TAKE a few of the words the old screens wrote\n// (`display_name`, `value_type`, `fetch_hint`, `value_text`…) and answer the field they wrote in\n// those words. That grammar is the door's contract, so it is spoken here, once, and never by a\n// caller: everything above this file holds `ScopeType`, `Scope`, `ContextField` and `ContextValue`.\n// The server's reader (aidream `matrx_records/store/scopes.py`) reads the same doors.\n\nimport type { Uuid } from \"../record\";\nimport type {\n ArchivedScopeType,\n ContextField,\n ContextFieldKind,\n ContextFieldSpec,\n ContextPolicy,\n ContextReference,\n ContextSensitivity,\n ContextValue,\n ContextValueWrite,\n Scope,\n ScopeType,\n ScopeTypeLabel,\n ScopeWithType,\n StoreWholeValue,\n SystemContextField,\n} from \"./types\";\nimport { SYSTEM_CONTEXT_TYPE_ID } from \"./types\";\n\n// ─── the doors' answers ─────────────────────────────────────────────────────────────────────────\n\n/** A scope type as the tree doors answer it. */\nexport interface StoreTypeRow {\n id: string;\n organization_id: string;\n label_singular?: string | null;\n label_plural?: string | null;\n name?: string | null;\n icon?: string | null;\n color?: string | null;\n slug?: string | null;\n description?: string | null;\n sort_order?: number | null;\n max_assignments_per_entity?: number | null;\n default_variable_keys?: string[] | null;\n created_by?: string | null;\n created_at?: string | null;\n updated_at?: string | null;\n scope_count?: number | null;\n}\n\n/** A scope as the tree and scope doors answer it. */\nexport interface StoreScopeRow {\n id: string;\n scope_type_id: string;\n organization_id: string;\n name?: string | null;\n description?: string | null;\n slug?: string | null;\n sort_order?: number | string | null;\n parent_scope_id?: string | null;\n settings?: Record<string, unknown> | null;\n created_by?: string | null;\n created_at?: string | null;\n updated_at?: string | null;\n scope_type?: (Partial<StoreTypeRow> & { id: string }) | null;\n}\n\n/** A Field document, as `custom.context_items` / `custom.context_values` answer it. */\nexport interface StoreFieldDoc {\n key?: string;\n label?: string;\n type?: string;\n multi?: boolean | null;\n format?: string | null;\n display_format?: { id?: string } | null;\n config?: ({ kind?: string } & Record<string, unknown>) | null;\n relation_target?: string | null;\n sort?: number | string | null;\n description?: string | null;\n sensitivity?: string | null;\n context_policy?: string | null;\n source?: string | null;\n status?: string | null;\n status_note?: string | null;\n category?: string | null;\n tags?: string[] | null;\n max_items?: number | null;\n custom_component?: unknown;\n reference_source?: unknown;\n allowed_scope_type_ids?: string[] | null;\n allowed_reference_types?: string[] | null;\n review_interval_days?: number | null;\n depends_on?: string[] | null;\n [extra: string]: unknown;\n}\n\n/** What the store remembers about a field it moved from the old tables and could not type. */\nexport interface StoreCarried {\n value_type?: string;\n as_text?: boolean;\n is_active?: boolean;\n}\n\n/** A context field as `custom.context_items` answers it. */\nexport interface StoreItemRow {\n id: string;\n scope_type_id: string;\n organization_id: string;\n data: StoreFieldDoc;\n carried?: StoreCarried | null;\n created_by?: string | null;\n created_at?: string | null;\n updated_at?: string | null;\n version?: number | null;\n}\n\n/** A cell as `custom.context_values` answers it. */\nexport interface StoreValueRow {\n scope_id: string;\n context_item_id: string;\n key: string;\n value: unknown;\n field?: (Pick<StoreFieldDoc, \"type\" | \"multi\" | \"format\" | \"display_format\" | \"config\" | \"relation_target\"> & {\n carried?: StoreCarried | null;\n }) | null;\n version?: number | null;\n store_version?: number | null;\n set_at?: string | null;\n source_type?: string | null;\n value_id?: string | null;\n authored_by?: string | null;\n labels?: Record<string, string> | null;\n files?: Record<string, string> | null;\n whole_value?: StoreWholeValue | null;\n}\n\n/** An archived scope type as `custom.context_archived_types` answers it. */\nexport interface StoreArchivedTypeRow {\n id: string;\n organization_id: string;\n label_singular?: string | null;\n label_plural?: string | null;\n icon?: string | null;\n color?: string | null;\n deleted_at?: string | null;\n created_by?: string | null;\n archived_scope_count?: number | null;\n}\n\n// ─── reading ────────────────────────────────────────────────────────────────────────────────────\n\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\nconst strOrNull = (v: unknown): string | null => (typeof v === \"string\" ? v : null);\nconst num = (v: unknown, fallback = 0): number => {\n const n = typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : NaN;\n return Number.isFinite(n) ? n : fallback;\n};\n\nexport function scopeTypeFromStore(row: StoreTypeRow): ScopeType {\n const singular = row.label_singular ?? row.name ?? \"\";\n return {\n id: row.id,\n organization_id: row.organization_id,\n label_singular: singular,\n label_plural: row.label_plural ?? singular,\n icon: row.icon ?? \"folder\",\n color: row.color ?? \"\",\n slug: row.slug ?? null,\n description: row.description ?? \"\",\n sort_order: num(row.sort_order),\n max_assignments_per_entity: row.max_assignments_per_entity ?? null,\n default_variable_keys: Array.isArray(row.default_variable_keys) ? row.default_variable_keys : [],\n created_by: row.created_by ?? null,\n created_at: row.created_at ?? \"\",\n updated_at: row.updated_at ?? \"\",\n };\n}\n\nexport function scopeTypeLabelFromStore(t: Partial<StoreTypeRow> & { id: string }): ScopeTypeLabel {\n const singular = t.label_singular ?? t.name ?? \"\";\n return { id: t.id, slug: t.slug ?? null, label_singular: singular, label_plural: t.label_plural ?? singular, icon: t.icon ?? null, color: t.color ?? null };\n}\n\n/**\n * A settings value as it was written. The scope door keeps a list-of-objects setting (a class's exam\n * dates) as a list of their JSON texts (`custom._ctx_words`); read back, each is the object again.\n */\nexport function settingFromStore(value: unknown): unknown {\n if (!Array.isArray(value)) return value;\n return value.map((el) => {\n if (typeof el !== \"string\") return el;\n const t = el.trim();\n if (!(t.startsWith(\"{\") && t.endsWith(\"}\")) && !(t.startsWith(\"[\") && t.endsWith(\"]\"))) return el;\n try {\n return JSON.parse(t) as unknown;\n } catch {\n return el;\n }\n });\n}\n\nexport function scopeFromStore(row: StoreScopeRow): Scope {\n const settings: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row.settings ?? {})) settings[k] = settingFromStore(v);\n return {\n id: row.id,\n scope_type_id: row.scope_type_id,\n organization_id: row.organization_id,\n name: row.name ?? \"\",\n description: row.description ?? \"\",\n slug: row.slug ?? null,\n sort_order: num(row.sort_order),\n parent_scope_id: row.parent_scope_id ?? null,\n settings,\n created_by: row.created_by ?? null,\n created_at: row.created_at ?? \"\",\n updated_at: row.updated_at ?? \"\",\n };\n}\n\nexport function scopeWithTypeFromStore(row: StoreScopeRow): ScopeWithType {\n return { ...scopeFromStore(row), scope_type: row.scope_type ? scopeTypeLabelFromStore(row.scope_type) : null };\n}\n\nexport function archivedScopeTypeFromStore(row: StoreArchivedTypeRow): ArchivedScopeType {\n const singular = row.label_singular ?? \"\";\n return {\n id: row.id,\n organization_id: row.organization_id,\n label_singular: singular,\n label_plural: row.label_plural ?? singular,\n icon: row.icon ?? \"folder\",\n color: row.color ?? \"\",\n archived_at: row.deleted_at ?? \"\",\n created_by: row.created_by ?? null,\n archived_scope_count: row.archived_scope_count ?? 0,\n };\n}\n\n/** The file kernel: a relation at it is a document (a file), never a reference to a row. */\nexport const FILE_KERNEL_ID = \"11111111-0000-4000-8000-000000000006\";\n\nconst KINDS = new Set<string>([\n \"string\", \"markdown\", \"email\", \"url\", \"phone\", \"color\", \"number\", \"percent\", \"currency\", \"boolean\",\n \"date\", \"datetime\", \"time\", \"object\", \"array\", \"reference\", \"document\",\n]);\n\n/** What a Field holds, as a person thinks of it. */\nexport function contextFieldKind(\n doc: Pick<StoreFieldDoc, \"type\" | \"multi\" | \"format\" | \"display_format\" | \"config\" | \"relation_target\">,\n carried?: StoreCarried | null,\n): ContextFieldKind {\n // A field the store landed as text keeps the word it had (custom._ctx_store_item carries it).\n if (carried?.as_text && carried.value_type && KINDS.has(carried.value_type)) return carried.value_type as ContextFieldKind;\n const behavior = String(doc.type ?? \"text\");\n const fmt = doc.format ? String(doc.format) : \"\";\n const shown = doc.display_format && typeof doc.display_format === \"object\" ? String(doc.display_format.id ?? \"\") : \"\";\n const kind = String(doc.config?.kind ?? \"\");\n const multi = Boolean(doc.multi);\n if (behavior === \"boolean\") return \"boolean\";\n if (behavior === \"relation\") return doc.relation_target === FILE_KERNEL_ID && !multi ? \"document\" : \"reference\";\n if (behavior === \"range\") {\n if (kind === \"date\") return \"date\";\n if (kind === \"datetime\") return \"datetime\";\n if (fmt === \"percent\" || fmt === \"currency\") return fmt;\n return \"number\";\n }\n if (behavior === \"text\") {\n if (multi) return \"array\";\n if (fmt === \"json\") return \"object\";\n for (const word of [fmt, shown]) {\n if (word === \"time\" || word === \"email\" || word === \"url\" || word === \"phone\" || word === \"color\" || word === \"markdown\") return word;\n }\n }\n return \"string\";\n}\n\nconst POLICIES = new Set<string>([\"include\", \"on_request\", \"exclude\"]);\nconst SENSITIVITIES = new Set<string>([\"public\", \"internal\", \"confidential\", \"restricted\"]);\n\nexport function contextFieldFromStore(row: StoreItemRow): ContextField {\n const d = row.data ?? {};\n const key = str(d.key);\n const policy = str(d.context_policy, \"include\");\n const sensitivity = str(d.sensitivity, \"internal\");\n return {\n id: row.id,\n scope_type_id: row.scope_type_id,\n organization_id: row.organization_id,\n key,\n label: str(d.label, key),\n description: str(d.description),\n kind: contextFieldKind(d, row.carried),\n type: str(d.type, \"text\"),\n multi: Boolean(d.multi),\n format: strOrNull(d.format),\n config: (d.config ?? {}) as Record<string, unknown>,\n relation_target: strOrNull(d.relation_target),\n // The store's sort counts the scope's own two columns first (custom._ctx_store_item: + 2).\n sort: Math.max(0, num(d.sort) - 2),\n context_policy: (POLICIES.has(policy) ? policy : \"include\") as ContextPolicy,\n sensitivity: (SENSITIVITIES.has(sensitivity) ? sensitivity : \"internal\") as ContextSensitivity,\n source: str(d.source, \"manual\"),\n status: str(d.status, \"active\"),\n status_note: strOrNull(d.status_note),\n category: strOrNull(d.category),\n tags: Array.isArray(d.tags) ? d.tags : [],\n max_items: typeof d.max_items === \"number\" ? d.max_items : 1,\n custom_component: d.custom_component ?? null,\n reference_source: d.reference_source ?? null,\n allowed_scope_type_ids: Array.isArray(d.allowed_scope_type_ids) ? d.allowed_scope_type_ids : null,\n allowed_reference_types: Array.isArray(d.allowed_reference_types) ? d.allowed_reference_types : null,\n review_interval_days: typeof d.review_interval_days === \"number\" ? d.review_interval_days : null,\n depends_on: Array.isArray(d.depends_on) ? d.depends_on : [],\n version: num(row.version, 1),\n created_by: row.created_by ?? null,\n created_at: row.created_at ?? \"\",\n updated_at: row.updated_at ?? \"\",\n };\n}\n\n// The write doors still speak three old words for a field; these are their meanings, both ways.\nconst POLICY_TO_DOOR: Record<ContextPolicy, string> = { include: \"always\", on_request: \"on_demand\", exclude: \"never\" };\nconst POLICY_FROM_DOOR: Record<string, ContextPolicy> = { always: \"include\", on_demand: \"on_request\", never: \"exclude\" };\nconst SENSITIVITY_TO_DOOR: Record<ContextSensitivity, string> = {\n public: \"public\",\n internal: \"internal\",\n confidential: \"restricted\",\n restricted: \"privileged\",\n};\nconst SENSITIVITY_FROM_DOOR: Record<string, ContextSensitivity> = {\n public: \"public\",\n internal: \"internal\",\n restricted: \"confidential\",\n privileged: \"restricted\",\n};\n\n/** The field a write door answered (`custom.context_item_row_of`), as a `ContextField`. */\nexport function contextFieldFromWriteAnswer(row: Record<string, unknown>, organizationId: Uuid): ContextField {\n const key = str(row.key);\n const kind = str(row.value_type, \"string\");\n return {\n id: str(row.id),\n scope_type_id: str(row.scope_type_id),\n organization_id: organizationId,\n key,\n label: str(row.display_name, key),\n description: str(row.description),\n kind: (KINDS.has(kind) ? kind : \"string\") as ContextFieldKind,\n type: \"\",\n multi: kind === \"array\",\n format: null,\n config: {},\n relation_target: null,\n sort: num(row.sort_order),\n context_policy: POLICY_FROM_DOOR[str(row.fetch_hint)] ?? \"include\",\n sensitivity: SENSITIVITY_FROM_DOOR[str(row.sensitivity)] ?? \"internal\",\n source: \"manual\",\n status: str(row.status, \"active\"),\n status_note: strOrNull(row.status_note),\n category: strOrNull(row.category),\n tags: Array.isArray(row.tags) ? (row.tags as string[]) : [],\n max_items: typeof row.max_items === \"number\" ? row.max_items : 1,\n custom_component: row.custom_component ?? null,\n reference_source: row.reference_source ?? null,\n allowed_scope_type_ids: Array.isArray(row.allowed_scope_type_ids) ? (row.allowed_scope_type_ids as string[]) : null,\n allowed_reference_types: Array.isArray(row.allowed_reference_types) ? (row.allowed_reference_types as string[]) : null,\n review_interval_days: typeof row.review_interval_days === \"number\" ? row.review_interval_days : null,\n depends_on: Array.isArray(row.depends_on) ? (row.depends_on as string[]) : [],\n version: num(row.version, 1),\n created_by: strOrNull(row.created_by),\n created_at: str(row.created_at),\n updated_at: str(row.updated_at),\n };\n}\n\n/** A System Context item, as `custom.context_system_items` answers it (the door's own words). */\nexport interface StoreSystemItemRow {\n id?: string | null;\n key?: string | null;\n display_name?: string | null;\n description?: string | null;\n item_class?: string | null;\n value_type?: string | null;\n sensitivity?: string | null;\n sort_order?: number | null;\n}\n\n/** A System Context item as a field of the `SYSTEM_CONTEXT_TYPE_ID` pseudo-type, with its class. */\nexport function systemContextFieldFromStore(row: StoreSystemItemRow, index: number): SystemContextField {\n const key = str(row.key);\n const kind = str(row.value_type, \"string\");\n return {\n id: str(row.id),\n scope_type_id: SYSTEM_CONTEXT_TYPE_ID,\n organization_id: \"\",\n key,\n label: str(row.display_name, key),\n description: str(row.description),\n kind: (KINDS.has(kind) ? kind : \"string\") as ContextFieldKind,\n type: \"system\",\n multi: kind === \"array\",\n format: null,\n config: {},\n relation_target: null,\n sort: typeof row.sort_order === \"number\" ? row.sort_order : index,\n context_policy: \"include\",\n // The system table keeps the old sensitivity words (`restricted`/`privileged`), like the write doors.\n sensitivity: SENSITIVITY_FROM_DOOR[str(row.sensitivity)] ?? \"public\",\n source: \"system\",\n status: \"active\",\n status_note: null,\n category: null,\n tags: [],\n max_items: 0,\n custom_component: null,\n reference_source: null,\n allowed_scope_type_ids: null,\n allowed_reference_types: null,\n review_interval_days: null,\n depends_on: [],\n version: 0,\n created_by: null,\n created_at: \"\",\n updated_at: \"\",\n item_class: strOrNull(row.item_class),\n };\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** A reference / document cell's targets, with the names and files the door gave this caller. */\nexport function referencesOf(row: Pick<StoreValueRow, \"value\" | \"field\" | \"labels\" | \"files\">): ContextReference[] {\n const v = row.value;\n const list = Array.isArray(v) ? v : v == null ? [] : [v];\n const labels = row.labels ?? {};\n const files = row.files ?? {};\n const toFile = row.field?.relation_target === FILE_KERNEL_ID;\n const out: ContextReference[] = [];\n for (const el of list) {\n let ref: ContextReference | null = null;\n if (typeof el === \"string\" && UUID.test(el)) ref = { id: el, type: toFile ? \"file\" : \"scope\" };\n else if (el && typeof el === \"object\" && typeof (el as { id?: unknown }).id === \"string\") {\n const token = String((el as { token?: unknown }).token ?? \"\");\n const own = (el as { label?: unknown }).label;\n ref = { id: (el as { id: string }).id, type: token === \"dataset\" ? \"table\" : token || (toFile ? \"file\" : \"scope\") };\n // A reference outside the scope system carries its own label in the store; the door names scopes only.\n if (typeof own === \"string\" && own) ref.label = own;\n }\n if (!ref) continue;\n const label = labels[ref.id];\n if (label) ref.label = label;\n const fileId = files[ref.id];\n if (fileId) ref.file_id = fileId;\n out.push(ref);\n }\n return out;\n}\n\n/** One cell, as a `ContextValue` (its whole text not yet read — see `completeWholeValues`). */\nexport function contextValueFromStore(row: StoreValueRow): ContextValue {\n const kind = contextFieldKind(row.field ?? {}, row.field?.carried);\n const carriedText = Boolean(row.field?.carried?.as_text);\n const isRef = !carriedText && (kind === \"reference\" || kind === \"document\");\n return {\n scope_id: row.scope_id,\n field_id: row.context_item_id,\n key: row.key,\n kind,\n value: row.value ?? null,\n references: isRef ? referencesOf(row) : [],\n version: num(row.version, 1),\n set_at: row.set_at ?? null,\n source_type: row.source_type ?? null,\n authored_by: row.authored_by ?? null,\n whole_value: row.whole_value ?? null,\n incomplete: null,\n };\n}\n\n// ─── whole texts kept as files ──────────────────────────────────────────────────────────────────\n\n/** Reads a file's whole text as the person (the host's one file reader). */\nexport type ReadContextFileText = (fileId: Uuid) => Promise<string>;\n\nasync function sha256Hex(text: string): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * A CELL THAT HOLDS ONLY THE FIRST WORDS OF A TEXT KEPT AS A FILE GETS ITS WHOLE TEXT.\n *\n * The store keeps a value over its one-cell ceiling as a file and the cell holds its first words;\n * `custom.context_values` names the file (`whole_value`). Each such value is given the file's whole\n * text — read once per file through the host's reader, checked against the size and SHA-256 the\n * pointer names. A file that cannot be read, or does not match, leaves the first words AND sets\n * `incomplete` (with why) — never the first words passed off as the value. Mutates `values`.\n */\nexport async function completeWholeValues(values: ContextValue[], read: ReadContextFileText | null): Promise<void> {\n const texts = new Map<string, Promise<string>>();\n await Promise.all(\n values.map(async (cell) => {\n const w = cell.whole_value;\n if (!w || w.in_value || typeof cell.value !== \"string\") return;\n const head = cell.value;\n const chars = typeof w.chars === \"number\" ? w.chars : null;\n const incomplete = (fileId: string | null, why: string): void => {\n cell.incomplete = { head, chars, file_id: fileId, why };\n };\n if (!w.file_id) return incomplete(null, \"The rest of this text is still being saved.\");\n if (!read) return incomplete(w.file_id, \"This place cannot open the file that holds the whole text.\");\n if (!texts.has(w.file_id)) texts.set(w.file_id, read(w.file_id));\n try {\n const text = await texts.get(w.file_id)!;\n if (chars !== null && [...text].length !== chars) {\n return incomplete(w.file_id, `The file holds ${[...text].length} characters, not ${chars}.`);\n }\n if (w.sha256) {\n const sha = await sha256Hex(text);\n if (sha === null) return incomplete(w.file_id, \"This browser cannot check the file.\");\n if (sha !== w.sha256) return incomplete(w.file_id, \"The file's content is not the text the cell points at.\");\n }\n cell.value = text;\n } catch (thrown) {\n incomplete(w.file_id, thrown instanceof Error ? thrown.message : String(thrown));\n }\n }),\n );\n}\n\n/** The refusal a person sees when saving would cut a value that was not read whole. */\nexport const INCOMPLETE_SAVE_REFUSAL = \"Only the start of this value loaded. Paste the whole text to replace it.\";\n\n/**\n * The refusal sentence when saving `draft` over a cell that was not read whole would cut the real\n * value — else `null`. Refused: the first words unchanged, and a draft built on them that is shorter\n * than the whole. Allowed: a draft that replaces the text, an explicit clear.\n */\nexport function incompleteSaveRefusal(cell: Pick<ContextValue, \"incomplete\"> | undefined, draft: unknown): string | null {\n const incomplete = cell?.incomplete;\n if (!incomplete || typeof draft !== \"string\" || draft === \"\") return null;\n if (draft === incomplete.head) return INCOMPLETE_SAVE_REFUSAL;\n if (incomplete.head && draft.startsWith(incomplete.head)) {\n const whole = incomplete.chars ?? Number.POSITIVE_INFINITY;\n if ([...draft].length < whole) return INCOMPLETE_SAVE_REFUSAL;\n }\n return null;\n}\n\n// ─── writing ────────────────────────────────────────────────────────────────────────────────────\n\n/** Drop keys whose value is `undefined`, keep `null` (a clear). */\nexport function definedOnly(fields: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(fields)) if (v !== undefined) out[k] = v;\n return out;\n}\n\n/** A field spec in the words `custom.context_item_write` takes. */\nexport function fieldSpecForDoor(spec: ContextFieldSpec): Record<string, unknown> {\n return definedOnly({\n key: spec.key,\n display_name: spec.label,\n value_type: spec.kind,\n description: spec.description,\n category: spec.category,\n fetch_hint: spec.context_policy ? POLICY_TO_DOOR[spec.context_policy] : undefined,\n sensitivity: spec.sensitivity ? SENSITIVITY_TO_DOOR[spec.sensitivity] : undefined,\n tags: spec.tags,\n sort_order: spec.sort,\n status: spec.status,\n status_note: spec.status_note,\n custom_component: spec.custom_component,\n review_interval_days: spec.review_interval_days,\n allowed_reference_types: spec.allowed_reference_types,\n max_items: spec.max_items,\n allowed_scope_type_ids: spec.allowed_scope_type_ids,\n reference_source: spec.reference_source,\n });\n}\n\n/** The canonical reference fence (the same grammar `@ai-matrx/agents/envelope` builds). */\nexport function referenceFence(references: readonly ContextReference[]): string {\n const kinds = [...new Set(references.map((r) => r.type))];\n const type = kinds.length === 1 ? kinds[0]! : \"mixed\";\n const items = references.map((r) => {\n if (r.type === \"file\" && r.file_id) return r.label ? { file_id: r.file_id, label: r.label } : { file_id: r.file_id };\n const item: { id: string; label?: string; type?: string } = { id: r.id };\n if (r.label) item.label = r.label;\n if (kinds.length > 1) item.type = r.type;\n return item;\n });\n return \"```matrx\\n\" + JSON.stringify({ matrx_version: 1, kind: \"reference\", type, items }, null, 2) + \"\\n```\";\n}\n\nconst FENCE_BODY = /```matrx[^\\n]*\\n([\\s\\S]*?)\\n?```/;\n\n/**\n * The things a reference fence points at (the inverse of `referenceFence`). Reads the canonical\n * grammar `{ kind: \"reference\", type, items }`, with or without the ```matrx wrapper; anything that\n * is not a reference fence answers `[]`.\n */\nexport function referencesFromFence(text: string | null | undefined): ContextReference[] {\n if (typeof text !== \"string\" || text.trim() === \"\") return [];\n const body = FENCE_BODY.exec(text)?.[1] ?? text;\n let parsed: unknown;\n try {\n parsed = JSON.parse(body.trim());\n } catch {\n return [];\n }\n if (!parsed || typeof parsed !== \"object\") return [];\n const fence = parsed as { kind?: unknown; type?: unknown; items?: unknown };\n if (fence.kind !== \"reference\" || !Array.isArray(fence.items)) return [];\n const noun = typeof fence.type === \"string\" ? fence.type : \"\";\n return fence.items.flatMap((raw): ContextReference[] => {\n if (!raw || typeof raw !== \"object\") return [];\n const item = raw as { id?: unknown; file_id?: unknown; label?: unknown; type?: unknown };\n const label = typeof item.label === \"string\" && item.label ? { label: item.label } : {};\n if (typeof item.file_id === \"string\" && item.file_id) {\n return [{ id: typeof item.id === \"string\" ? item.id : item.file_id, type: \"file\", file_id: item.file_id, ...label }];\n }\n if (typeof item.id !== \"string\" || !item.id) return [];\n const type = typeof item.type === \"string\" && item.type ? item.type : noun || \"scope\";\n return [{ id: item.id, type, ...label }];\n });\n}\n\nconst isContextReference = (v: unknown): v is ContextReference =>\n !!v && typeof v === \"object\" && typeof (v as { id?: unknown }).id === \"string\" && typeof (v as { type?: unknown }).type === \"string\";\n\n/**\n * THE ONE WRITE AN EDIT BECOMES: an editor's raw value for `field` on `scopeId`, as a\n * `ContextValueWrite`. A reference / document field takes a fence (what the reference picker edits)\n * or a list of `ContextReference`s and writes `references`; a clear (`null`, `undefined`, `\"\"`)\n * writes no references. Any other field writes `value`, with `\"\"` and `undefined` a clear (`null`).\n * Written by a person (`source_type: \"manual\"`) unless `options` says otherwise.\n */\nexport function contextValueWrite(\n field: Pick<ContextField, \"id\" | \"kind\">,\n scopeId: Uuid,\n raw: unknown,\n options: { source_type?: string; change_summary?: string } = {},\n): ContextValueWrite {\n const base: ContextValueWrite = {\n scope_id: scopeId,\n field_id: field.id,\n kind: field.kind,\n source_type: options.source_type ?? \"manual\",\n ...(options.change_summary ? { change_summary: options.change_summary } : {}),\n };\n if (field.kind === \"reference\" || field.kind === \"document\") {\n if (typeof raw === \"string\") return { ...base, references: referencesFromFence(raw) };\n if (Array.isArray(raw)) {\n return {\n ...base,\n references: raw.flatMap((el): ContextReference[] =>\n isContextReference(el) ? [el] : typeof el === \"string\" ? referencesFromFence(el) : [],\n ),\n };\n }\n return { ...base, references: [] };\n }\n return { ...base, value: raw === \"\" || raw === undefined ? null : raw };\n}\n\n/**\n * One cell in the payload `custom.context_value_write` takes: the value lands in the slot the door\n * reads for the field's kind; a reference cell is the canonical fence the door's reference rule reads.\n */\nexport function valuePayloadForDoor(write: ContextValueWrite): Record<string, unknown> {\n const base: Record<string, unknown> = definedOnly({\n scope_id: write.scope_id,\n context_item_id: write.field_id,\n source_type: write.source_type,\n change_summary: write.change_summary,\n });\n const v = write.value;\n if (write.kind === \"reference\" || write.kind === \"document\") {\n if (write.references) return { ...base, value_text: write.references.length ? referenceFence(write.references) : null };\n // A document cell may also be written as a url.\n if (write.kind === \"document\" && typeof v === \"string\") return { ...base, value_document_url: v || null };\n return { ...base, value_text: typeof v === \"string\" ? v || null : null };\n }\n if (v === null || v === undefined || v === \"\") {\n return { ...base, value_text: null };\n }\n switch (write.kind) {\n case \"number\":\n case \"percent\":\n return typeof v === \"number\" ? { ...base, value_number: v } : { ...base, value_text: String(v) };\n case \"currency\":\n return typeof v === \"object\" ? { ...base, value_json: v } : typeof v === \"number\" ? { ...base, value_number: v } : { ...base, value_text: String(v) };\n case \"boolean\":\n return typeof v === \"boolean\" ? { ...base, value_boolean: v } : { ...base, value_text: String(v) };\n case \"date\":\n return { ...base, value_date: String(v) };\n case \"datetime\":\n return { ...base, value_timestamp: String(v) };\n case \"time\":\n return { ...base, value_time: String(v) };\n case \"object\":\n case \"array\":\n return typeof v === \"object\" ? { ...base, value_json: v } : { ...base, value_text: String(v) };\n default:\n return typeof v === \"object\" ? { ...base, value_json: v } : { ...base, value_text: String(v) };\n }\n}\n","// src/scopes/rules.ts — @ai-matrx/records/scopes\n//\n// The few rules a screen needs BEFORE it asks a door, each a mirror of what the door itself decides\n// (the door is the authority; this only spares a person a button that would be refused).\n\nimport type { RecordsResult } from \"../results\";\nimport type { Uuid } from \"../record\";\n\n/** An organization role, as `iam.organization_member` holds it. */\nexport type ScopeSeatRole = \"owner\" | \"admin\" | \"member\" | string;\n\n/**\n * WHO MAY CHANGE A SCOPE TYPE'S STRUCTURE — rename it, add/edit/archive its fields, archive or restore\n * it: an organization owner or admin, or the person who made the type. Every member works the DATA\n * (adds, renames, archives and restores scopes, writes values). Arman 2026-10-07: \"structure is the\n * org admins' and the creator's\". Mirrors `custom.context_type_write` / `_archive` / `_restore` and\n * `custom.context_item_write` / `_archive` / `_restore`.\n */\nexport function canShapeScopeType(\n role: ScopeSeatRole | null | undefined,\n userId: Uuid | null | undefined,\n type: { created_by?: Uuid | null } | null | undefined,\n): boolean {\n if (role === \"owner\" || role === \"admin\") return true;\n return !!userId && !!type?.created_by && type.created_by === userId;\n}\n\n/** Display name → kebab URL slug. */\nexport function toSlug(name: string): string {\n return name\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\n/** Display name → snake_case field key. */\nexport function toFieldKey(name: string): string {\n return name\n .toLowerCase()\n .trim()\n .replace(/[\\s-]+/g, \"_\")\n .replace(/[^a-z0-9_]/g, \"\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\n/** True when `s` is a clean slug: a-z, 0-9, single hyphens or underscores between words. */\nexport function isValidSlug(s: string): boolean {\n return /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s);\n}\n\n/** Route segments that are literal pages of the scope screens; no slug may equal one. */\nexport const RESERVED_SCOPE_SLUGS: ReadonlySet<string> = new Set([\"context-items\", \"scopes\", \"edit\", \"manage\", \"new\", \"settings\"]);\n\nexport function isReservedSlug(s: string): boolean {\n return RESERVED_SCOPE_SLUGS.has(s.toLowerCase().replace(/_/g, \"-\"));\n}\n\n/**\n * Two slugs name the same thing when they differ only by `-` ↔ `_` (the store's Table grammar is\n * `practice_areas`; a link a person typed may say `practice-areas`).\n */\nexport function sameSlug(a: string | null | undefined, b: string | null | undefined): boolean {\n if (!a || !b) return false;\n return a.toLowerCase().replace(/_/g, \"-\") === b.toLowerCase().replace(/_/g, \"-\");\n}\n\n/** The slug a write sends: the one supplied, else one made from the name; refused when unusable. */\nexport function resolveSlug(supplied: string | undefined, fallbackName: string): RecordsResult<string> {\n const slug = supplied?.trim() || toSlug(fallbackName);\n if (!slug || !isValidSlug(slug)) {\n return {\n ok: false,\n error: { code: \"invalid_argument\", message: \"Use letters, numbers and single hyphens for the short name.\" },\n };\n }\n if (isReservedSlug(slug)) {\n return { ok: false, error: { code: \"invalid_argument\", message: `\"${slug}\" is a page name here. Pick another short name.` } };\n }\n return { ok: true, data: slug };\n}\n","// src/scopes/doors.ts — @ai-matrx/records/scopes\n//\n// THE SCOPE DOORS, ONE CALL EACH, THROUGH THE RECORDS CLIENT'S OWN DOOR PATH.\n//\n// `client.scopes` is built from the same `callDoor` every other method of the client uses, so a scope\n// read gets what every store read gets: the schema said out loud, one request in flight per question,\n// a door the store lacks refused as `door_absent` (never an empty list), and every refusal in the\n// store's own words (`RecordsError`). Nothing here talks to Supabase itself.\n//\n// The doors take explicit organizations (a scope read spans every organization the person belongs\n// to; a write names its own), so the client's `organizationId` is never used here.\n\nimport type { RecordsErrorCode, RecordsResult } from \"../results\";\nimport type { Uuid } from \"../record\";\nimport {\n archivedScopeTypeFromStore,\n completeWholeValues,\n contextFieldFromStore,\n contextValueFromStore,\n definedOnly,\n fieldSpecForDoor,\n scopeFromStore,\n scopeTypeFromStore,\n scopeWithTypeFromStore,\n systemContextFieldFromStore,\n valuePayloadForDoor,\n type ReadContextFileText,\n type StoreArchivedTypeRow,\n type StoreItemRow,\n type StoreScopeRow,\n type StoreSystemItemRow,\n type StoreTypeRow,\n type StoreValueRow,\n} from \"./codec\";\nimport { resolveSlug } from \"./rules\";\nimport type {\n ArchivedScope,\n ArchivedScopeType,\n ContextField,\n ContextFieldSpec,\n ContextValue,\n ContextValueWrite,\n ContextValueWritten,\n Scope,\n ScopePage,\n ScopeSpec,\n ScopeTemplate,\n ScopeType,\n ScopeTypeSkeleton,\n ScopeTypeSpec,\n ScopeTypeWithScopes,\n ScopeWithType,\n SystemContextField,\n TableTemplate,\n} from \"./types\";\n\n/** The client's one door call (`callDoor` in core/client.ts). */\nexport type ScopeDoorCall = <T>(door: string, args: Record<string, unknown>, where: string) => Promise<RecordsResult<T>>;\n\n/** The kernel Table every Field is a record of. */\nexport const FIELD_KERNEL_ID = \"11111111-0000-4000-8000-000000000002\";\n\n/** How many ids one call of each batched door takes. */\nexport const SCOPES_PER_CALL = 500;\nexport const SCOPE_TYPES_PER_FIELDS_CALL = 100;\n/** `custom.context_values` refuses more than this many scopes in one call. */\nexport const SCOPES_PER_VALUES_CALL = 200;\n/** One page of a type's scopes (the door's default; it answers at most 1000). */\nexport const TYPE_SCOPES_PAGE = 200;\n/** The archive answers at most this many rows a call (`custom.page_size` ceiling). */\nexport const ARCHIVED_SCOPES_PAGE = 200;\n\nexport interface ScopeDoors {\n // ── reads ──────────────────────────────────────────────────────────────────────────────────\n /** Every live scope type of these organizations, each with its live scopes. */\n tree(organizationIds: readonly Uuid[]): Promise<RecordsResult<ScopeTypeWithScopes[]>>;\n /** The scope types of these organizations without their scopes (the first paint), with or without counts. */\n types(organizationIds: readonly Uuid[], options?: { withCounts?: boolean }): Promise<RecordsResult<ScopeTypeSkeleton>>;\n /** One page of one type's scopes, in the tree's order. */\n typeScopesPage(scopeTypeId: Uuid, offset?: number, limit?: number): Promise<RecordsResult<ScopePage>>;\n /** The scopes whose name holds `query` (case-insensitive), across these organizations. */\n search(organizationIds: readonly Uuid[], query: string, limit?: number): Promise<RecordsResult<{ scopes: Scope[]; total: number }>>;\n /** Scopes by id, each with its type's label, in whichever organization each lives. */\n scopes(ids: readonly Uuid[]): Promise<RecordsResult<ScopeWithType[]>>;\n /**\n * The context fields (columns) of these scope types, each type's fields in their order (`sort`,\n * then label) as the door answers them.\n */\n fields(scopeTypeIds: readonly Uuid[]): Promise<RecordsResult<ContextField[]>>;\n /**\n * One context field by its id, read in whichever of these organizations holds it (a Field is a\n * record of the field kernel; its scope type is the Table it is defined on). Refused `not_found`\n * when no organization answers it.\n */\n field(fieldId: Uuid, organizationIds: readonly Uuid[]): Promise<RecordsResult<ContextField>>;\n /**\n * The cells of these scopes. A text kept as a file is read whole through `readFileText`; without\n * one (or when the file cannot be read) the cell keeps its first words and says so (`incomplete`).\n */\n values(scopeIds: readonly Uuid[], options?: { readFileText?: ReadContextFileText | null }): Promise<RecordsResult<ContextValue[]>>;\n /** The archived scope types of one organization. */\n archivedTypes(organizationId: Uuid): Promise<RecordsResult<ArchivedScopeType[]>>;\n /** Of these scope ids, the ones that are ARCHIVED scopes of this type. */\n archivedScopesOfType(organizationId: Uuid, scopeTypeId: Uuid, wanted: ReadonlySet<Uuid>): Promise<RecordsResult<ArchivedScope[]>>;\n /** The System Context items (not scopes: the platform's own ambient context). */\n systemItems(): Promise<RecordsResult<SystemContextField[]>>;\n /** The table templates an organization's scope dataset fields may use (its own and the platform's). */\n tableTemplates(organizationId: Uuid): Promise<RecordsResult<TableTemplate[]>>;\n /** The scope templates of the gallery. */\n templates(): Promise<RecordsResult<ScopeTemplate[]>>;\n\n // ── writes ─────────────────────────────────────────────────────────────────────────────────\n /** A new scope type in `organizationId`. */\n createType(organizationId: Uuid, spec: ScopeTypeSpec): Promise<RecordsResult<ScopeType>>;\n /** Change a scope type (only the keys given). */\n updateType(typeId: Uuid, spec: ScopeTypeSpec): Promise<RecordsResult<ScopeType>>;\n /** Archive a scope type; its scopes and fields come back with a restore. */\n archiveType(typeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n restoreType(typeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n /** A new scope of `typeId` in `organizationId`. */\n createScope(organizationId: Uuid, typeId: Uuid, spec: ScopeSpec): Promise<RecordsResult<Scope>>;\n updateScope(scopeId: Uuid, spec: ScopeSpec): Promise<RecordsResult<Scope>>;\n archiveScope(scopeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n restoreScope(scopeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n /** A new context field (column) on a scope type. Answers the field as the read door does. */\n createField(scopeTypeId: Uuid, spec: ContextFieldSpec): Promise<RecordsResult<ContextField>>;\n /** Change a context field (`null` clears a key). Answers the field as the read door does. */\n updateField(fieldId: Uuid, scopeTypeId: Uuid, spec: ContextFieldSpec): Promise<RecordsResult<ContextField>>;\n archiveField(fieldId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n restoreField(fieldId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n /** Write one cell. */\n writeValue(write: ContextValueWrite): Promise<RecordsResult<ContextValueWritten>>;\n}\n\nconst uniq = (ids: readonly string[]): string[] => [...new Set(ids.filter(Boolean))];\n\n/** The ids in batches of `size`, each batch one call, answers concatenated in order. */\nasync function inBatches<T>(\n ids: readonly string[],\n size: number,\n call: (batch: string[]) => Promise<RecordsResult<T[] | null>>,\n): Promise<RecordsResult<T[]>> {\n const unique = uniq(ids);\n const batches: string[][] = [];\n for (let i = 0; i < unique.length; i += size) batches.push(unique.slice(i, i + size));\n const answers = await Promise.all(batches.map(call));\n const out: T[] = [];\n for (const a of answers) {\n if (!a.ok) return a;\n out.push(...(a.data ?? []));\n }\n return { ok: true, data: out };\n}\n\n/** A write door's answer: `{ ok, writer, row, store }`. */\ninterface WriteAnswer {\n ok?: boolean;\n row?: Record<string, unknown> | null;\n}\n\nfunction noRow<T>(door: string): RecordsResult<T> {\n return { ok: false, error: { code: \"internal\", message: `${door} answered without the row it wrote.`, diagnostic: `@ai-matrx/records/scopes: ${door}` } };\n}\n\n/** The value door answers its own envelope; its codes, as the package's. */\nconst VALUE_DOOR_CODES: Record<string, RecordsErrorCode> = {\n unauthorized: \"door\",\n forbidden: \"door\",\n forbidden_org: \"door\",\n not_found: \"not_found\",\n invalid_argument: \"invalid_argument\",\n conflict: \"stale_write\",\n unavailable: \"not_supported\",\n};\n\nexport function createScopeDoors(call: ScopeDoorCall): ScopeDoors {\n async function write(door: string, args: Record<string, unknown>): Promise<RecordsResult<Record<string, unknown>>> {\n const res = await call<WriteAnswer>(door, args, `scopes.${door}`);\n if (!res.ok) return res;\n const row = res.data?.row;\n if (!row || typeof row !== \"object\") return noRow(door);\n return { ok: true, data: row };\n }\n\n async function archiveOrRestore(door: string, args: Record<string, unknown>, id: Uuid): Promise<RecordsResult<{ id: Uuid }>> {\n const res = await call<unknown>(door, args, `scopes.${door}`);\n return res.ok ? { ok: true, data: { id } } : res;\n }\n\n async function fieldById(scopeTypeId: Uuid, fieldId: Uuid, door: string): Promise<RecordsResult<ContextField>> {\n const fields = await doors.fields([scopeTypeId]);\n if (!fields.ok) return fields;\n const field = fields.data.find((f) => f.id === fieldId);\n return field ? { ok: true, data: field } : noRow(door);\n }\n\n const doors: ScopeDoors = {\n async tree(organizationIds) {\n const ids = uniq(organizationIds);\n if (ids.length === 0) return { ok: true, data: [] };\n const res = await call<{ types?: StoreTypeRow[]; scopes?: StoreScopeRow[] } | null>(\"context_tree\", { p_organization_ids: ids }, \"scopes.tree\");\n if (!res.ok) return res;\n const byType = new Map<string, Scope[]>();\n for (const s of res.data?.scopes ?? []) {\n const scope = scopeFromStore(s);\n const list = byType.get(scope.scope_type_id) ?? [];\n list.push(scope);\n byType.set(scope.scope_type_id, list);\n }\n return { ok: true, data: (res.data?.types ?? []).map((t) => ({ ...scopeTypeFromStore(t), scopes: byType.get(t.id) ?? [] })) };\n },\n\n async types(organizationIds, options) {\n const withCounts = options?.withCounts ?? true;\n const ids = uniq(organizationIds);\n if (ids.length === 0) return { ok: true, data: { types: [], counts: withCounts ? {} : null } };\n const res = await call<{ types?: StoreTypeRow[] } | null>(\"context_tree_types\", { p_organization_ids: ids, p_with_counts: withCounts }, \"scopes.types\");\n if (!res.ok) return res;\n const rows = res.data?.types ?? [];\n const counts: Record<string, number> | null = withCounts ? {} : null;\n if (counts) for (const r of rows) counts[r.id] = Number(r.scope_count ?? 0);\n return { ok: true, data: { types: rows.map(scopeTypeFromStore), counts } };\n },\n\n async typeScopesPage(scopeTypeId, offset = 0, limit = TYPE_SCOPES_PAGE) {\n const res = await call<{ scopes?: StoreScopeRow[]; total?: number; next_offset?: number | null } | null>(\n \"context_tree_type_scopes\",\n { p_scope_type_id: scopeTypeId, p_offset: offset, p_limit: limit },\n \"scopes.typeScopesPage\",\n );\n if (!res.ok) return res;\n return {\n ok: true,\n data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0), next_offset: res.data?.next_offset ?? null },\n };\n },\n\n async search(organizationIds, query, limit = 100) {\n const ids = uniq(organizationIds);\n const q = query.trim();\n if (ids.length === 0 || q === \"\") return { ok: true, data: { scopes: [], total: 0 } };\n const res = await call<{ scopes?: StoreScopeRow[]; total?: number } | null>(\n \"context_tree_search\",\n { p_organization_ids: ids, p_query: q, p_limit: limit },\n \"scopes.search\",\n );\n if (!res.ok) return res;\n return { ok: true, data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0) } };\n },\n\n async scopes(ids) {\n const res = await inBatches(ids, SCOPES_PER_CALL, (batch) => call<StoreScopeRow[]>(\"context_scopes\", { p_scope_ids: batch }, \"scopes.scopes\"));\n return res.ok ? { ok: true, data: res.data.map(scopeWithTypeFromStore) } : res;\n },\n\n async fields(scopeTypeIds) {\n const res = await inBatches(scopeTypeIds, SCOPE_TYPES_PER_FIELDS_CALL, (batch) =>\n call<StoreItemRow[]>(\"context_items\", { p_scope_type_ids: batch }, \"scopes.fields\"),\n );\n return res.ok ? { ok: true, data: res.data.map(contextFieldFromStore) } : res;\n },\n\n async field(fieldId, organizationIds) {\n const orgs = uniq(organizationIds);\n const answers = await Promise.all(\n orgs.map((org) =>\n call<Array<{ id: string; document?: { entity_definition_id?: unknown } | null }> | null>(\n \"read_records_by_ids\",\n { p_organization_id: org, p_table_id: FIELD_KERNEL_ID, p_record_ids: [fieldId], p_by_id: false },\n \"scopes.field\",\n ),\n ),\n );\n let refusal: RecordsResult<ContextField> | null = null;\n for (const answer of answers) {\n if (!answer.ok) {\n refusal ??= answer;\n continue;\n }\n const typeId = answer.data?.find((r) => r.id === fieldId)?.document?.entity_definition_id;\n if (typeof typeId !== \"string\") continue;\n const fields = await doors.fields([typeId]);\n if (!fields.ok) return fields;\n const field = fields.data.find((f) => f.id === fieldId);\n if (field) return { ok: true, data: field };\n }\n return (\n refusal ?? {\n ok: false,\n error: { code: \"not_found\", message: \"This context field could not be found.\", diagnostic: `@ai-matrx/records/scopes: field ${fieldId}` },\n }\n );\n },\n\n async values(scopeIds, options) {\n const res = await inBatches(scopeIds, SCOPES_PER_VALUES_CALL, (batch) =>\n call<StoreValueRow[]>(\"context_values\", { p_scope_ids: batch }, \"scopes.values\"),\n );\n if (!res.ok) return res;\n const cells = res.data.map(contextValueFromStore);\n await completeWholeValues(cells, options?.readFileText ?? null);\n return { ok: true, data: cells };\n },\n\n async archivedTypes(organizationId) {\n const res = await call<StoreArchivedTypeRow[] | null>(\"context_archived_types\", { p_organization_id: organizationId }, \"scopes.archivedTypes\");\n return res.ok ? { ok: true, data: (res.data ?? []).map(archivedScopeTypeFromStore) } : res;\n },\n\n async archivedScopesOfType(organizationId, scopeTypeId, wanted) {\n const out: ArchivedScope[] = [];\n for (let offset = 0; out.length < wanted.size; offset += ARCHIVED_SCOPES_PAGE) {\n const res = await call<Array<{ id: string; document?: { name?: unknown; slug?: unknown } | null; archived_at?: string | null }> | null>(\n \"read_records_archived\",\n { p_organization_id: organizationId, p_table_id: scopeTypeId, p_lane: \"org\", p_by_id: false, p_limit: ARCHIVED_SCOPES_PAGE, p_offset: offset },\n \"scopes.archivedScopesOfType\",\n );\n if (!res.ok) return res;\n const rows = res.data ?? [];\n for (const r of rows) {\n if (!wanted.has(r.id)) continue;\n out.push({\n id: r.id,\n name: typeof r.document?.name === \"string\" ? r.document.name : null,\n slug: typeof r.document?.slug === \"string\" ? r.document.slug : null,\n archived_at: r.archived_at ?? null,\n });\n }\n if (rows.length < ARCHIVED_SCOPES_PAGE) break;\n }\n return { ok: true, data: out };\n },\n\n async systemItems() {\n const res = await call<StoreSystemItemRow[] | null>(\"context_system_items\", {}, \"scopes.systemItems\");\n return res.ok ? { ok: true, data: (res.data ?? []).map(systemContextFieldFromStore) } : res;\n },\n\n async tableTemplates(organizationId) {\n const res = await call<TableTemplate[] | null>(\"table_templates\", { p_org_id: organizationId }, \"scopes.tableTemplates\");\n return res.ok ? { ok: true, data: Array.isArray(res.data) ? res.data : [] } : res;\n },\n\n async templates() {\n const res = await call<ScopeTemplate[] | null>(\"context_templates\", {}, \"scopes.templates\");\n return res.ok ? { ok: true, data: res.data ?? [] } : res;\n },\n\n async createType(organizationId, spec) {\n const slug = resolveSlug(spec.slug, spec.label_plural || spec.label_singular || \"\");\n if (!slug.ok) return slug;\n const res = await write(\"context_type_write\", {\n p_organization_id: organizationId,\n p_type_id: null,\n p_spec: definedOnly({\n label_singular: spec.label_singular,\n label_plural: spec.label_plural,\n icon: spec.icon ?? \"folder\",\n description: spec.description ?? \"\",\n sort_order: spec.sort_order ?? 0,\n max_assignments: spec.max_assignments_per_entity ?? undefined,\n default_variable_keys: spec.default_variable_keys ?? [],\n color: spec.color,\n slug: slug.data,\n }),\n });\n return res.ok ? { ok: true, data: scopeTypeFromStore(res.data as unknown as StoreTypeRow) } : res;\n },\n\n async updateType(typeId, spec) {\n let slug: string | undefined;\n if (spec.slug !== undefined) {\n const resolved = resolveSlug(spec.slug, spec.label_plural ?? spec.label_singular ?? \"\");\n if (!resolved.ok) return resolved;\n slug = resolved.data;\n }\n const res = await write(\"context_type_write\", {\n p_organization_id: null,\n p_type_id: typeId,\n p_spec: definedOnly({\n label_singular: spec.label_singular,\n label_plural: spec.label_plural,\n icon: spec.icon,\n description: spec.description,\n sort_order: spec.sort_order,\n max_assignments: spec.max_assignments_per_entity,\n color: spec.color,\n slug,\n }),\n });\n return res.ok ? { ok: true, data: scopeTypeFromStore(res.data as unknown as StoreTypeRow) } : res;\n },\n\n archiveType: (typeId) => archiveOrRestore(\"context_type_archive\", { p_type_id: typeId }, typeId),\n restoreType: (typeId) => archiveOrRestore(\"context_type_restore\", { p_type_id: typeId }, typeId),\n\n async createScope(organizationId, typeId, spec) {\n const slug = resolveSlug(spec.slug, spec.name ?? \"\");\n if (!slug.ok) return slug;\n const res = await write(\"context_scope_write\", {\n p_organization_id: organizationId,\n p_scope_id: null,\n p_type_id: typeId,\n p_spec: definedOnly({\n name: spec.name,\n parent_scope_id: spec.parent_scope_id,\n description: spec.description ?? \"\",\n settings: spec.settings ?? {},\n slug: slug.data,\n sort_order: spec.sort_order,\n }),\n });\n return res.ok ? { ok: true, data: scopeFromStore(res.data as unknown as StoreScopeRow) } : res;\n },\n\n async updateScope(scopeId, spec) {\n let slug: string | undefined;\n if (spec.slug !== undefined) {\n const resolved = resolveSlug(spec.slug, spec.name ?? \"\");\n if (!resolved.ok) return resolved;\n slug = resolved.data;\n }\n const res = await write(\"context_scope_write\", {\n p_organization_id: null,\n p_scope_id: scopeId,\n p_type_id: null,\n p_spec: definedOnly({ name: spec.name, description: spec.description, settings: spec.settings, slug, sort_order: spec.sort_order }),\n });\n return res.ok ? { ok: true, data: scopeFromStore(res.data as unknown as StoreScopeRow) } : res;\n },\n\n archiveScope: (scopeId) => archiveOrRestore(\"context_scope_archive\", { p_scope_id: scopeId }, scopeId),\n restoreScope: (scopeId) => archiveOrRestore(\"context_scope_restore\", { p_scope_id: scopeId }, scopeId),\n\n async createField(scopeTypeId, spec) {\n const res = await write(\"context_item_write\", {\n p_item_id: null,\n p_scope_type_id: scopeTypeId,\n p_spec: fieldSpecForDoor({ kind: \"string\", description: \"\", context_policy: \"on_request\", sensitivity: \"internal\", tags: [], ...spec }),\n });\n if (!res.ok) return res;\n return fieldById(scopeTypeId, String(res.data.id), \"context_item_write\");\n },\n\n async updateField(fieldId, scopeTypeId, spec) {\n const res = await write(\"context_item_write\", { p_item_id: fieldId, p_scope_type_id: null, p_spec: fieldSpecForDoor(spec) });\n if (!res.ok) return res;\n return fieldById(scopeTypeId, fieldId, \"context_item_write\");\n },\n\n archiveField: (fieldId) => archiveOrRestore(\"context_item_archive\", { p_item_id: fieldId }, fieldId),\n restoreField: (fieldId) => archiveOrRestore(\"context_item_restore\", { p_item_id: fieldId }, fieldId),\n\n async writeValue(cell) {\n const res = await call<{ ok?: boolean; data?: { version?: number; source_type?: string }; error?: { code?: string; message?: string } } | null>(\n \"context_value_write\",\n { p_payload: { source_type: \"ai_enriched\", ...valuePayloadForDoor(cell) } },\n \"scopes.writeValue\",\n );\n if (!res.ok) return res;\n const envelope = res.data ?? {};\n if (!envelope.ok) {\n const code = VALUE_DOOR_CODES[envelope.error?.code ?? \"\"] ?? \"internal\";\n return { ok: false, error: { code, message: envelope.error?.message ?? \"The value was not saved.\" } };\n }\n return {\n ok: true,\n data: {\n scope_id: cell.scope_id,\n field_id: cell.field_id,\n version: Number(envelope.data?.version ?? 1),\n source_type: String(envelope.data?.source_type ?? cell.source_type ?? \"ai_enriched\"),\n },\n };\n },\n };\n return doors;\n}\n","// src/scopes/resolve.ts — @ai-matrx/records/scopes (HEADLESS, pure)\n//\n// The two pure joins every scope screen and chat need, so no host re-derives them:\n//\n// joinFieldValues a scope type's context fields beside one scope's values (one row per field)\n// resolveScopeContext local-vs-global resolution: which scope's cell wins each field\n//\n// Resolution rule: sources are ranked closer-first — local task (1000), local project (1100), local\n// scopes (1200…), global task (2000), global project (2100), global scopes (2200…). The first SCOPE\n// source holding a value for a field owns it. A contradiction is the same scope type selected\n// globally and tagged locally with a DIFFERENT scope; it is informational and never blocks.\n\nimport type { Uuid } from \"../record\";\nimport { referenceFence } from \"./codec\";\nimport type { ContextField, ContextFieldKind, ContextReference, ContextValue, Scope } from \"./types\";\n\n/** One context field of a scope type beside the scope's value for it (`value` null = empty). */\nexport interface ScopeFieldValue {\n field: ContextField;\n value: ContextValue | null;\n has_value: boolean;\n}\n\n/** A scope type's fields beside one scope's values, in the fields' order. */\nexport function joinFieldValues(\n fields: readonly ContextField[],\n values: Readonly<Record<Uuid, ContextValue | undefined>>,\n): ScopeFieldValue[] {\n return fields.map((field) => {\n const value = values[field.id] ?? null;\n return { field, value, has_value: value !== null && hasCell(value) };\n });\n}\n\n/** Whether a value holds anything: a reference cell its references, any other cell a non-empty value. */\nexport function hasCell(value: Pick<ContextValue, \"kind\" | \"value\" | \"references\">): boolean {\n if (value.kind === \"reference\" || value.kind === \"document\") return value.references.length > 0;\n const v = value.value;\n if (v === null || v === undefined) return false;\n if (typeof v === \"string\") return v.length > 0;\n if (Array.isArray(v)) return v.length > 0;\n return true;\n}\n\nexport type ContextSourceKind = \"scope\" | \"project\" | \"task\";\nexport type ContextSourceOrigin = \"local\" | \"global\";\n\n/** One contributor to a resolved context. Lower `priority` = closer to the action. */\nexport interface ContextSource {\n kind: ContextSourceKind;\n id: Uuid;\n origin: ContextSourceOrigin;\n priority: number;\n}\n\n/** A resolved cell. A reference cell's `value` is its `referenceFence(references)`. */\nexport interface ResolvedValue {\n field_id: Uuid;\n key: string;\n label: string;\n kind: ContextFieldKind;\n value: unknown;\n references: ContextReference[];\n version: number;\n}\n\nexport interface ScopeContradiction {\n scope_type_id: Uuid;\n global_scope_id: Uuid;\n local_scope_id: Uuid;\n}\n\nexport interface ResolvedScopeContext {\n /** field id → the winning cell. */\n values: Record<Uuid, ResolvedValue>;\n /** field id → the source that won it. */\n sourcePerKey: Record<Uuid, ContextSource>;\n contradictions: ScopeContradiction[];\n /** Every contributing source, closest first. */\n activeScopes: ContextSource[];\n}\n\nexport interface ResolveScopeContextInput {\n /** Finds a scope (for its type) by id; a scope it cannot find contributes nothing locally. */\n scopeById: (id: Uuid) => Pick<Scope, \"id\" | \"scope_type_id\"> | undefined;\n local?: { taskId?: Uuid | null; projectId?: Uuid | null; scopeIds?: readonly Uuid[] };\n global?: { taskId?: Uuid | null; projectId?: Uuid | null; scopeIds?: readonly Uuid[] };\n /** scope id → its values by field id; a scope whose values are not read yet is absent. */\n valuesByScope: Readonly<Record<Uuid, Readonly<Record<Uuid, ContextValue>> | undefined>>;\n /** field id → its field, for the label (a field not here resolves with an empty label). */\n fieldById?: (id: Uuid) => Pick<ContextField, \"label\"> | undefined;\n}\n\n/** Local-vs-global resolution of the active scopes' values (see the header for the rule). */\nexport function resolveScopeContext(input: ResolveScopeContextInput): ResolvedScopeContext {\n const { scopeById, valuesByScope } = input;\n const local = input.local ?? {};\n const global = input.global ?? {};\n const localScopeIds = local.scopeIds ?? [];\n const sources: ContextSource[] = [];\n\n if (local.taskId) sources.push({ kind: \"task\", id: local.taskId, origin: \"local\", priority: 1000 });\n if (local.projectId) sources.push({ kind: \"project\", id: local.projectId, origin: \"local\", priority: 1100 });\n let localPri = 1200;\n const localScopeTypeIds = new Set<Uuid>();\n for (const sid of localScopeIds) {\n const scope = scopeById(sid);\n if (!scope) continue;\n localScopeTypeIds.add(scope.scope_type_id);\n sources.push({ kind: \"scope\", id: sid, origin: \"local\", priority: localPri++ });\n }\n\n if (global.taskId) sources.push({ kind: \"task\", id: global.taskId, origin: \"global\", priority: 2000 });\n if (global.projectId) sources.push({ kind: \"project\", id: global.projectId, origin: \"global\", priority: 2100 });\n let globalPri = 2200;\n const contradictions: ScopeContradiction[] = [];\n for (const scopeId of global.scopeIds ?? []) {\n if (!scopeId) continue;\n const typeId = scopeById(scopeId)?.scope_type_id ?? null;\n if (typeId && localScopeTypeIds.has(typeId)) {\n const localId = localScopeIds.find((sid) => scopeById(sid)?.scope_type_id === typeId);\n if (localId && localId !== scopeId) {\n contradictions.push({ scope_type_id: typeId, global_scope_id: scopeId, local_scope_id: localId });\n }\n }\n sources.push({ kind: \"scope\", id: scopeId, origin: \"global\", priority: globalPri++ });\n }\n\n const sorted = sources.slice().sort((a, b) => a.priority - b.priority);\n const values: Record<Uuid, ResolvedValue> = {};\n const sourcePerKey: Record<Uuid, ContextSource> = {};\n for (const source of sorted) {\n if (source.kind !== \"scope\") continue;\n const cells = valuesByScope[source.id];\n if (!cells) continue;\n for (const fieldId of Object.keys(cells)) {\n if (values[fieldId]) continue;\n const cell = cells[fieldId]!;\n if (!hasCell(cell)) continue;\n values[fieldId] = toResolvedValue(cell, input.fieldById?.(fieldId)?.label ?? \"\");\n sourcePerKey[fieldId] = source;\n }\n }\n return { values, sourcePerKey, contradictions, activeScopes: sorted };\n}\n\n/** One cell as a resolved value: a reference cell's `value` is its fence. */\nexport function toResolvedValue(cell: ContextValue, label = \"\"): ResolvedValue {\n const isRef = cell.kind === \"reference\" || cell.kind === \"document\";\n return {\n field_id: cell.field_id,\n key: cell.key,\n label,\n kind: cell.kind,\n value: isRef ? referenceFence(cell.references) : cell.value,\n references: cell.references,\n version: cell.version,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0CO,IAAM,sBAAmD;AAAA,EAC9D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA+MO,IAAM,yBAAyB;;;ACjHtC,IAAM,MAAM,CAAC,GAAY,WAAW,OAAgB,OAAO,MAAM,WAAW,IAAI;AAChF,IAAM,YAAY,CAAC,MAA+B,OAAO,MAAM,WAAW,IAAI;AAC9E,IAAM,MAAM,CAAC,GAAY,WAAW,MAAc;AAChD,QAAM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O,MAAM,OAAO;AAC1B,UAAI,CAAC,QAAQ,IAAI,EAAG;AACpB,aAAO,OAAO,IAAI,gBAAgB,MAAM,MAAM,YAAY,OAAO,GAAG,SAAS,EAAE;AAC/E,mBAAa,OAAO,IAAI;AAAA,IAC1B;AAAA,EACF;AACA,SAAO,EAAE,QAAQ,cAAc,gBAAgB,cAAc,OAAO;AACtE;AAGO,SAAS,gBAAgB,MAAoB,QAAQ,IAAmB;AAC7E,QAAM,QAAQ,KAAK,SAAS,eAAe,KAAK,SAAS;AACzD,SAAO;AAAA,IACL,UAAU,KAAK;AAAA,IACf,KAAK,KAAK;AAAA,IACV;AAAA,IACA,MAAM,KAAK;AAAA,IACX,OAAO,QAAQ,eAAe,KAAK,UAAU,IAAI,KAAK;AAAA,IACtD,YAAY,KAAK;AAAA,IACjB,SAAS,KAAK;AAAA,EAChB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/scopes/index.ts","../../src/scopes/types.ts","../../src/scopes/codec.ts","../../src/scopes/rules.ts","../../src/scopes/doors.ts","../../src/scopes/resolve.ts"],"sourcesContent":["// src/scopes/index.ts — @ai-matrx/records/scopes (HEADLESS)\n//\n// SCOPES ARE CUSTOM DATA: a scope type is a Table kept for context, a scope a Record of it, a context\n// field a Field (column), a value its cell. This section is the shapes, the doors (`client.scopes`,\n// built from the client's own door path), and the few rules a screen needs. Zero React, zero DOM.\n// Managing (building types, fields, scopes) and using (picking, reading values, sending to an agent)\n// both go through here; nothing outside this package calls a `custom.context_*` door.\n\nexport * from \"./types\";\nexport {\n createScopeDoors,\n SCOPES_PER_CALL,\n FIELD_KERNEL_ID,\n SCOPE_TYPES_PER_FIELDS_CALL,\n SCOPES_PER_VALUES_CALL,\n TYPE_SCOPES_PAGE,\n ARCHIVED_SCOPES_PAGE,\n type ScopeDoors,\n type ScopeDoorCall,\n} from \"./doors\";\nexport {\n contextFieldKind,\n contextFieldFromStore,\n systemContextFieldFromStore,\n type StoreSystemItemRow,\n contextValueFromStore,\n scopeFromStore,\n scopeTypeFromStore,\n scopeWithTypeFromStore,\n settingFromStore,\n referencesOf,\n referenceFence,\n referencesFromFence,\n contextValueWrite,\n completeWholeValues,\n incompleteSaveRefusal,\n INCOMPLETE_SAVE_REFUSAL,\n FILE_KERNEL_ID,\n type ReadContextFileText,\n} from \"./codec\";\nexport {\n canShapeScopeType,\n toSlug,\n toFieldKey,\n isValidSlug,\n isReservedSlug,\n sameSlug,\n resolveSlug,\n RESERVED_SCOPE_SLUGS,\n type ScopeSeatRole,\n} from \"./rules\";\nexport {\n joinFieldValues,\n hasCell,\n resolveScopeContext,\n toResolvedValue,\n type ScopeFieldValue,\n type ContextSource,\n type ContextSourceKind,\n type ContextSourceOrigin,\n type ResolvedValue,\n type ScopeContradiction,\n type ResolvedScopeContext,\n type ResolveScopeContextInput,\n} from \"./resolve\";\n","// src/scopes/types.ts — @ai-matrx/records/scopes\n//\n// SCOPES ARE CUSTOM DATA (Arman, 2026-10-09: \"Scopes are now nothing more than custom data… A scope\n// type is nothing more than a row [a custom Table flagged kept_for='context'], a context item is\n// nothing more than a column.\").\n//\n// scope type a Table of the store kept for context (`kept_for = 'context'`)\n// scope a Record of that Table\n// context field a Field (column) of that Table — what the old screens called a \"context item\"\n// context value the Record's cell under the Field's key\n//\n// These are the shapes the `custom.context_*` doors answer, in the store's words. Nothing here is a\n// row of the archived `context.*` tables, and nothing re-creates one: a value is the cell (`value`),\n// never a set of `value_text` / `value_number` / … columns; a field says `context_policy` and the\n// store's `sensitivity`, never the old `fetch_hint` words.\n\nimport type { Uuid } from \"../record\";\n\n/**\n * What a context field holds, as a person thinks of it — derived from the Field's behaviour, `multi`,\n * `format`, display format and `config.kind` (`contextFieldKind`). The value is always `value`; the\n * kind says how to read and edit it.\n */\nexport type ContextFieldKind =\n | \"string\"\n | \"markdown\"\n | \"email\"\n | \"url\"\n | \"phone\"\n | \"color\"\n | \"number\"\n | \"percent\"\n | \"currency\"\n | \"boolean\"\n | \"date\"\n | \"datetime\"\n | \"time\"\n | \"object\"\n | \"array\"\n | \"reference\"\n | \"document\";\n\nexport const CONTEXT_FIELD_KINDS: readonly ContextFieldKind[] = [\n \"string\",\n \"markdown\",\n \"email\",\n \"url\",\n \"phone\",\n \"color\",\n \"number\",\n \"percent\",\n \"currency\",\n \"boolean\",\n \"date\",\n \"datetime\",\n \"time\",\n \"object\",\n \"array\",\n \"reference\",\n \"document\",\n];\n\n/** The store's context policy on a Field: whether an agent receives it every turn, on request, or never. */\nexport type ContextPolicy = \"include\" | \"on_request\" | \"exclude\";\n\n/** The store's sensitivity words on a Field. */\nexport type ContextSensitivity = \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n/** A scope type: a Table kept for context. */\nexport interface ScopeType {\n id: Uuid;\n organization_id: Uuid;\n label_singular: string;\n label_plural: string;\n icon: string;\n color: string;\n /** The Table's slug in the store's grammar (`practice_areas`). */\n slug: string | null;\n description: string;\n sort_order: number;\n max_assignments_per_entity: number | null;\n default_variable_keys: string[];\n /** Who made the type: with the organization's owners and admins, they shape it (`canShapeScopeType`). */\n created_by: Uuid | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A scope type with its live scopes, as the tree doors answer it. */\nexport interface ScopeTypeWithScopes extends ScopeType {\n scopes: Scope[];\n}\n\n/** A scope: a Record of its type's Table. */\nexport interface Scope {\n id: Uuid;\n scope_type_id: Uuid;\n organization_id: Uuid;\n name: string;\n description: string;\n slug: string | null;\n sort_order: number;\n parent_scope_id: Uuid | null;\n /** Free settings keys of the scope (each a Field of its Table the scope door derived). */\n settings: Record<string, unknown>;\n created_by: Uuid | null;\n created_at: string;\n updated_at: string;\n}\n\n/** A scope with its type's presentation (`custom.context_scopes`). */\nexport interface ScopeWithType extends Scope {\n scope_type: ScopeTypeLabel | null;\n}\n\n/** The presentation of a scope type: what a chip or a breadcrumb shows. */\nexport interface ScopeTypeLabel {\n id: Uuid;\n /** The type's slug in the store's grammar (`practice_areas`), when it has one. */\n slug: string | null;\n label_singular: string;\n label_plural: string;\n icon: string | null;\n color: string | null;\n}\n\n/** A scope type that was archived, with how many scopes went with it. */\nexport interface ArchivedScopeType {\n id: Uuid;\n organization_id: Uuid;\n label_singular: string;\n label_plural: string;\n icon: string;\n color: string;\n archived_at: string;\n created_by: Uuid | null;\n archived_scope_count: number;\n}\n\n/** A scope that was archived (a Record in the archive of its type's Table). */\nexport interface ArchivedScope {\n id: Uuid;\n name: string | null;\n slug: string | null;\n archived_at: string | null;\n}\n\n/** A context field: a Field (column) of a scope type's Table. */\nexport interface ContextField {\n id: Uuid;\n scope_type_id: Uuid;\n organization_id: Uuid;\n key: string;\n label: string;\n description: string;\n kind: ContextFieldKind;\n /** The Field's own words, for a caller that needs them (`type` is the store's behaviour word). */\n type: string;\n multi: boolean;\n format: string | null;\n config: Record<string, unknown>;\n relation_target: Uuid | null;\n /** Its place among the type's context fields, from 0. */\n sort: number;\n context_policy: ContextPolicy;\n sensitivity: ContextSensitivity;\n source: string;\n status: string;\n status_note: string | null;\n category: string | null;\n tags: string[];\n max_items: number;\n custom_component: unknown;\n reference_source: unknown;\n allowed_scope_type_ids: Uuid[] | null;\n allowed_reference_types: string[] | null;\n review_interval_days: number | null;\n depends_on: string[];\n /** The store's clock on this Field. */\n version: number;\n created_by: Uuid | null;\n created_at: string;\n updated_at: string;\n}\n\n/** One thing a reference cell points at. */\nexport interface ContextReference {\n /** The record id (for a file: the File record's id). */\n id: Uuid;\n /** What it is: `scope`, `file`, `table`, or another entity token. */\n type: string;\n /** Its name, where the door named it to this caller. */\n label?: string;\n /** For a file: the `files.files` id a viewer opens. */\n file_id?: Uuid;\n}\n\n/** The cell holds only the first words of a text kept as a file, and the whole could not be read. */\nexport interface IncompleteValue {\n /** The cell's own first words. */\n head: string;\n /** The whole text's length in characters, when known. */\n chars: number | null;\n /** The file holding the whole text, when it has one yet. */\n file_id: Uuid | null;\n /** Why the whole text is not here, in one sentence. */\n why: string;\n}\n\n/** A context value: one cell of a scope's Record. */\nexport interface ContextValue {\n scope_id: Uuid;\n field_id: Uuid;\n key: string;\n kind: ContextFieldKind;\n /**\n * THE CELL, as the store holds it (a text, a number, a boolean, an ISO date, a list, an object).\n * A reference or document cell is its `references` (ids here). A text kept as a file is its whole\n * text when the read could open the file (`completeWholeValues`), else the first words and `incomplete`.\n */\n value: unknown;\n /** A reference / document cell, decoded: what it points at, with names the caller may see. */\n references: ContextReference[];\n /** The version a PERSON made (system rewrites never move it). */\n version: number;\n set_at: string | null;\n source_type: string | null;\n authored_by: Uuid | null;\n /** The pointer to the file holding a text too big for one cell, when the cell holds only its start. */\n whole_value: StoreWholeValue | null;\n /** Present only when `value` is not the whole text — never save it back as the value. */\n incomplete: IncompleteValue | null;\n}\n\n/** The file fields of a whole-value pointer, as `custom.context_values` answers them. */\nexport interface StoreWholeValue {\n kind: string;\n file_id?: Uuid | null;\n file_record?: Uuid | null;\n bytes?: number | null;\n chars?: number | null;\n sha256?: string | null;\n shown_chars?: number | null;\n mime?: string | null;\n pending?: boolean | null;\n in_value?: boolean | null;\n}\n\n/** The scope types of some organizations, without their scopes, and how many each holds. */\nexport interface ScopeTypeSkeleton {\n types: ScopeType[];\n /** type id → how many scopes the caller sees in it; null when asked without counts. */\n counts: Record<Uuid, number> | null;\n}\n\n/** One page of one type's scopes. */\nexport interface ScopePage {\n scopes: Scope[];\n total: number;\n next_offset: number | null;\n}\n\n/**\n * The pseudo scope-type id a System Context field carries. System Context (what is simply TRUE on the\n * platform) has no scope type; its fields share this sentinel so a holder can keep them beside a\n * type's fields. A client-side key only — a binding to one of these carries `scope_type_id: null`.\n */\nexport const SYSTEM_CONTEXT_TYPE_ID = \"__system__\";\n\n/** What a System Context item is: a curated fact, an ambient fact of the moment, or a dataset. */\nexport type SystemContextItemClass = \"curated\" | \"ambient\" | \"dataset\" | (string & {});\n\n/**\n * A System Context item (`custom.context_system_items`), as a `ContextField` of the\n * `SYSTEM_CONTEXT_TYPE_ID` pseudo-type, plus its class.\n */\nexport interface SystemContextField extends ContextField {\n item_class: SystemContextItemClass | null;\n}\n\n/** One column of a table template. */\nexport interface TableTemplateField {\n field_name: string;\n display_name: string;\n data_type: string;\n field_order: number;\n is_required: boolean;\n}\n\n/**\n * A table template (a `custom.template` of kind `table`) a scope's dataset field may lock its\n * table's columns to: the organization's own or a platform one, as `custom.table_templates` answers it.\n */\nexport interface TableTemplate {\n id: Uuid;\n organization_id: Uuid | null;\n name: string;\n description: string;\n version: number;\n is_platform: boolean;\n fields: TableTemplateField[];\n}\n\n/** One scope template of the gallery, as `custom.context_templates` answers it. */\nexport interface ScopeTemplate {\n [key: string]: unknown;\n}\n\n// ─── writes ──────────────────────────────────────────────────────────────────────────────────────\n\n/** A new scope type, or the parts of one to change (`undefined` = leave as it is). */\nexport interface ScopeTypeSpec {\n label_singular?: string;\n label_plural?: string;\n icon?: string;\n color?: string;\n description?: string;\n sort_order?: number;\n max_assignments_per_entity?: number | null;\n default_variable_keys?: string[];\n /** Any spelling; the package writes it in the store's grammar. Absent on create = from the label. */\n slug?: string;\n}\n\n/** A new scope, or the parts of one to change. */\nexport interface ScopeSpec {\n name?: string;\n description?: string;\n settings?: Record<string, unknown>;\n parent_scope_id?: Uuid | null;\n slug?: string;\n sort_order?: number;\n}\n\n/** A new context field, or the parts of one to change (`null` clears). */\nexport interface ContextFieldSpec {\n key?: string;\n label?: string;\n kind?: ContextFieldKind;\n description?: string;\n category?: string | null;\n context_policy?: ContextPolicy;\n sensitivity?: ContextSensitivity;\n tags?: string[];\n sort?: number;\n status?: string;\n status_note?: string | null;\n custom_component?: unknown;\n review_interval_days?: number | null;\n allowed_reference_types?: string[] | null;\n max_items?: number | null;\n allowed_scope_type_ids?: Uuid[] | null;\n reference_source?: unknown;\n}\n\n/** One cell to write. `value` is the cell as `ContextValue.value` reads it; a reference cell takes `references`. */\nexport interface ContextValueWrite {\n scope_id: Uuid;\n field_id: Uuid;\n kind: ContextFieldKind;\n value?: unknown;\n /** A reference / document cell: the things it points at (replaces the cell). */\n references?: ContextReference[];\n /** Who wrote it: `manual` from a person's own edit (the store's default is `ai_enriched`). */\n source_type?: string;\n change_summary?: string;\n}\n\n/** What a written cell answers. */\nexport interface ContextValueWritten {\n scope_id: Uuid;\n field_id: Uuid;\n version: number;\n source_type: string;\n}\n","// src/scopes/codec.ts — @ai-matrx/records/scopes\n//\n// THE ONE PLACE THE SCOPE DOORS' WORDS ARE READ AND WRITTEN.\n//\n// The `custom.context_*` doors answer the store's rows (a Table, a Record, a Field document, a\n// cell) and, for the write doors, still TAKE a few of the words the old screens wrote\n// (`display_name`, `value_type`, `fetch_hint`, `value_text`…) and answer the field they wrote in\n// those words. That grammar is the door's contract, so it is spoken here, once, and never by a\n// caller: everything above this file holds `ScopeType`, `Scope`, `ContextField` and `ContextValue`.\n// The server's reader (aidream `matrx_records/store/scopes.py`) reads the same doors.\n\nimport type { Uuid } from \"../record\";\nimport type {\n ArchivedScopeType,\n ContextField,\n ContextFieldKind,\n ContextFieldSpec,\n ContextPolicy,\n ContextReference,\n ContextSensitivity,\n ContextValue,\n ContextValueWrite,\n Scope,\n ScopeType,\n ScopeTypeLabel,\n ScopeWithType,\n StoreWholeValue,\n SystemContextField,\n} from \"./types\";\nimport { SYSTEM_CONTEXT_TYPE_ID } from \"./types\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n// ─── the doors' answers ─────────────────────────────────────────────────────────────────────────\n\n/** A scope type as the tree doors answer it. */\nexport interface StoreTypeRow {\n id: string;\n organization_id: string;\n label_singular?: string | null;\n label_plural?: string | null;\n name?: string | null;\n icon?: string | null;\n color?: string | null;\n slug?: string | null;\n description?: string | null;\n sort_order?: number | null;\n max_assignments_per_entity?: number | null;\n default_variable_keys?: string[] | null;\n created_by?: string | null;\n created_at?: string | null;\n updated_at?: string | null;\n scope_count?: number | null;\n}\n\n/** A scope as the tree and scope doors answer it. */\nexport interface StoreScopeRow {\n id: string;\n scope_type_id: string;\n organization_id: string;\n name?: string | null;\n description?: string | null;\n slug?: string | null;\n sort_order?: number | string | null;\n parent_scope_id?: string | null;\n settings?: Record<string, unknown> | null;\n created_by?: string | null;\n created_at?: string | null;\n updated_at?: string | null;\n scope_type?: (Partial<StoreTypeRow> & { id: string }) | null;\n}\n\n/** A Field document, as `custom.context_items` / `custom.context_values` answer it. */\nexport interface StoreFieldDoc {\n key?: string;\n label?: string;\n type?: string;\n multi?: boolean | null;\n format?: string | null;\n display_format?: { id?: string } | null;\n config?: ({ kind?: string } & Record<string, unknown>) | null;\n relation_target?: string | null;\n sort?: number | string | null;\n description?: string | null;\n sensitivity?: string | null;\n context_policy?: string | null;\n source?: string | null;\n status?: string | null;\n status_note?: string | null;\n category?: string | null;\n tags?: string[] | null;\n max_items?: number | null;\n custom_component?: unknown;\n reference_source?: unknown;\n allowed_scope_type_ids?: string[] | null;\n allowed_reference_types?: string[] | null;\n review_interval_days?: number | null;\n depends_on?: string[] | null;\n [extra: string]: unknown;\n}\n\n/** What the store remembers about a field it moved from the old tables and could not type. */\nexport interface StoreCarried {\n value_type?: string;\n as_text?: boolean;\n is_active?: boolean;\n}\n\n/** A context field as `custom.context_items` answers it. */\nexport interface StoreItemRow {\n id: string;\n scope_type_id: string;\n organization_id: string;\n data: StoreFieldDoc;\n carried?: StoreCarried | null;\n created_by?: string | null;\n created_at?: string | null;\n updated_at?: string | null;\n version?: number | null;\n}\n\n/** A cell as `custom.context_values` answers it. */\nexport interface StoreValueRow {\n scope_id: string;\n context_item_id: string;\n key: string;\n value: unknown;\n field?: (Pick<StoreFieldDoc, \"type\" | \"multi\" | \"format\" | \"display_format\" | \"config\" | \"relation_target\"> & {\n carried?: StoreCarried | null;\n }) | null;\n version?: number | null;\n store_version?: number | null;\n set_at?: string | null;\n source_type?: string | null;\n value_id?: string | null;\n authored_by?: string | null;\n labels?: Record<string, string> | null;\n files?: Record<string, string> | null;\n whole_value?: StoreWholeValue | null;\n}\n\n/** An archived scope type as `custom.context_archived_types` answers it. */\nexport interface StoreArchivedTypeRow {\n id: string;\n organization_id: string;\n label_singular?: string | null;\n label_plural?: string | null;\n icon?: string | null;\n color?: string | null;\n deleted_at?: string | null;\n created_by?: string | null;\n archived_scope_count?: number | null;\n}\n\n// ─── reading ────────────────────────────────────────────────────────────────────────────────────\n\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\nconst strOrNull = (v: unknown): string | null => (typeof v === \"string\" ? v : null);\nconst num = (v: unknown, fallback = 0): number => {\n const n = typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : NaN;\n return Number.isFinite(n) ? n : fallback;\n};\n\nexport function scopeTypeFromStore(row: StoreTypeRow): ScopeType {\n const singular = row.label_singular ?? row.name ?? \"\";\n return {\n id: row.id,\n organization_id: row.organization_id,\n label_singular: singular,\n label_plural: row.label_plural ?? singular,\n icon: row.icon ?? \"folder\",\n color: row.color ?? \"\",\n slug: row.slug ?? null,\n description: row.description ?? \"\",\n sort_order: num(row.sort_order),\n max_assignments_per_entity: row.max_assignments_per_entity ?? null,\n default_variable_keys: Array.isArray(row.default_variable_keys) ? row.default_variable_keys : [],\n created_by: row.created_by ?? null,\n created_at: row.created_at ?? \"\",\n updated_at: row.updated_at ?? \"\",\n };\n}\n\nexport function scopeTypeLabelFromStore(t: Partial<StoreTypeRow> & { id: string }): ScopeTypeLabel {\n const singular = t.label_singular ?? t.name ?? \"\";\n return { id: t.id, slug: t.slug ?? null, label_singular: singular, label_plural: t.label_plural ?? singular, icon: t.icon ?? null, color: t.color ?? null };\n}\n\n/**\n * A settings value as it was written. The scope door keeps a list-of-objects setting (a class's exam\n * dates) as a list of their JSON texts (`custom._ctx_words`); read back, each is the object again.\n */\nexport function settingFromStore(value: unknown): unknown {\n if (!Array.isArray(value)) return value;\n return value.map((el) => {\n if (typeof el !== \"string\") return el;\n const t = el.trim();\n if (!(t.startsWith(\"{\") && t.endsWith(\"}\")) && !(t.startsWith(\"[\") && t.endsWith(\"]\"))) return el;\n try {\n return JSON.parse(t) as unknown;\n } catch {\n return el;\n }\n });\n}\n\nexport function scopeFromStore(row: StoreScopeRow): Scope {\n const settings: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row.settings ?? {})) settings[k] = settingFromStore(v);\n return {\n id: row.id,\n scope_type_id: row.scope_type_id,\n organization_id: row.organization_id,\n name: row.name ?? \"\",\n description: row.description ?? \"\",\n slug: row.slug ?? null,\n sort_order: num(row.sort_order),\n parent_scope_id: row.parent_scope_id ?? null,\n settings,\n created_by: row.created_by ?? null,\n created_at: row.created_at ?? \"\",\n updated_at: row.updated_at ?? \"\",\n };\n}\n\nexport function scopeWithTypeFromStore(row: StoreScopeRow): ScopeWithType {\n return { ...scopeFromStore(row), scope_type: row.scope_type ? scopeTypeLabelFromStore(row.scope_type) : null };\n}\n\nexport function archivedScopeTypeFromStore(row: StoreArchivedTypeRow): ArchivedScopeType {\n const singular = row.label_singular ?? \"\";\n return {\n id: row.id,\n organization_id: row.organization_id,\n label_singular: singular,\n label_plural: row.label_plural ?? singular,\n icon: row.icon ?? \"folder\",\n color: row.color ?? \"\",\n archived_at: row.deleted_at ?? \"\",\n created_by: row.created_by ?? null,\n archived_scope_count: row.archived_scope_count ?? 0,\n };\n}\n\n/** The file kernel: a relation at it is a document (a file), never a reference to a row. */\nexport const FILE_KERNEL_ID = \"11111111-0000-4000-8000-000000000006\";\n\nconst KINDS = new Set<string>([\n \"string\", \"markdown\", \"email\", \"url\", \"phone\", \"color\", \"number\", \"percent\", \"currency\", \"boolean\",\n \"date\", \"datetime\", \"time\", \"object\", \"array\", \"reference\", \"document\",\n]);\n\n/** What a Field holds, as a person thinks of it. */\nexport function contextFieldKind(\n doc: Pick<StoreFieldDoc, \"type\" | \"multi\" | \"format\" | \"display_format\" | \"config\" | \"relation_target\">,\n carried?: StoreCarried | null,\n): ContextFieldKind {\n // A field the store landed as text keeps the word it had (custom._ctx_store_item carries it).\n if (carried?.as_text && carried.value_type && KINDS.has(carried.value_type)) return carried.value_type as ContextFieldKind;\n const behavior = String(doc.type ?? \"text\");\n const fmt = doc.format ? String(doc.format) : \"\";\n const shown = doc.display_format && typeof doc.display_format === \"object\" ? String(doc.display_format.id ?? \"\") : \"\";\n const kind = String(doc.config?.kind ?? \"\");\n const multi = Boolean(doc.multi);\n if (behavior === \"boolean\") return \"boolean\";\n if (behavior === \"relation\") return doc.relation_target === FILE_KERNEL_ID && !multi ? \"document\" : \"reference\";\n if (behavior === \"range\") {\n if (kind === \"date\") return \"date\";\n if (kind === \"datetime\") return \"datetime\";\n if (fmt === \"percent\" || fmt === \"currency\") return fmt;\n return \"number\";\n }\n if (behavior === \"text\") {\n if (multi) return \"array\";\n if (fmt === \"json\") return \"object\";\n for (const word of [fmt, shown]) {\n if (word === \"time\" || word === \"email\" || word === \"url\" || word === \"phone\" || word === \"color\" || word === \"markdown\") return word;\n }\n }\n return \"string\";\n}\n\nconst POLICIES = new Set<string>([\"include\", \"on_request\", \"exclude\"]);\nconst SENSITIVITIES = new Set<string>([\"public\", \"internal\", \"confidential\", \"restricted\"]);\n\nexport function contextFieldFromStore(row: StoreItemRow): ContextField {\n const d = row.data ?? {};\n const key = str(d.key);\n const policy = str(d.context_policy, \"include\");\n const sensitivity = str(d.sensitivity, \"internal\");\n return {\n id: row.id,\n scope_type_id: row.scope_type_id,\n organization_id: row.organization_id,\n key,\n label: str(d.label, key),\n description: str(d.description),\n kind: contextFieldKind(d, row.carried),\n type: str(d.type, \"text\"),\n multi: Boolean(d.multi),\n format: strOrNull(d.format),\n config: (d.config ?? {}) as Record<string, unknown>,\n relation_target: strOrNull(d.relation_target),\n // The store's sort counts the scope's own two columns first (custom._ctx_store_item: + 2).\n sort: Math.max(0, num(d.sort) - 2),\n context_policy: (POLICIES.has(policy) ? policy : \"include\") as ContextPolicy,\n sensitivity: (SENSITIVITIES.has(sensitivity) ? sensitivity : \"internal\") as ContextSensitivity,\n source: str(d.source, \"manual\"),\n status: str(d.status, \"active\"),\n status_note: strOrNull(d.status_note),\n category: strOrNull(d.category),\n tags: Array.isArray(d.tags) ? d.tags : [],\n max_items: typeof d.max_items === \"number\" ? d.max_items : 1,\n custom_component: d.custom_component ?? null,\n reference_source: d.reference_source ?? null,\n allowed_scope_type_ids: Array.isArray(d.allowed_scope_type_ids) ? d.allowed_scope_type_ids : null,\n allowed_reference_types: Array.isArray(d.allowed_reference_types) ? d.allowed_reference_types : null,\n review_interval_days: typeof d.review_interval_days === \"number\" ? d.review_interval_days : null,\n depends_on: Array.isArray(d.depends_on) ? d.depends_on : [],\n version: num(row.version, 1),\n created_by: row.created_by ?? null,\n created_at: row.created_at ?? \"\",\n updated_at: row.updated_at ?? \"\",\n };\n}\n\n// The write doors still speak three old words for a field; these are their meanings, both ways.\nconst POLICY_TO_DOOR: Record<ContextPolicy, string> = { include: \"always\", on_request: \"on_demand\", exclude: \"never\" };\nconst POLICY_FROM_DOOR: Record<string, ContextPolicy> = { always: \"include\", on_demand: \"on_request\", never: \"exclude\" };\nconst SENSITIVITY_TO_DOOR: Record<ContextSensitivity, string> = {\n public: \"public\",\n internal: \"internal\",\n confidential: \"restricted\",\n restricted: \"privileged\",\n};\nconst SENSITIVITY_FROM_DOOR: Record<string, ContextSensitivity> = {\n public: \"public\",\n internal: \"internal\",\n restricted: \"confidential\",\n privileged: \"restricted\",\n};\n\n/** The field a write door answered (`custom.context_item_row_of`), as a `ContextField`. */\nexport function contextFieldFromWriteAnswer(row: Record<string, unknown>, organizationId: Uuid): ContextField {\n const key = str(row.key);\n const kind = str(row.value_type, \"string\");\n return {\n id: str(row.id),\n scope_type_id: str(row.scope_type_id),\n organization_id: organizationId,\n key,\n label: str(row.display_name, key),\n description: str(row.description),\n kind: (KINDS.has(kind) ? kind : \"string\") as ContextFieldKind,\n type: \"\",\n multi: kind === \"array\",\n format: null,\n config: {},\n relation_target: null,\n sort: num(row.sort_order),\n context_policy: POLICY_FROM_DOOR[str(row.fetch_hint)] ?? \"include\",\n sensitivity: SENSITIVITY_FROM_DOOR[str(row.sensitivity)] ?? \"internal\",\n source: \"manual\",\n status: str(row.status, \"active\"),\n status_note: strOrNull(row.status_note),\n category: strOrNull(row.category),\n tags: Array.isArray(row.tags) ? (row.tags as string[]) : [],\n max_items: typeof row.max_items === \"number\" ? row.max_items : 1,\n custom_component: row.custom_component ?? null,\n reference_source: row.reference_source ?? null,\n allowed_scope_type_ids: Array.isArray(row.allowed_scope_type_ids) ? (row.allowed_scope_type_ids as string[]) : null,\n allowed_reference_types: Array.isArray(row.allowed_reference_types) ? (row.allowed_reference_types as string[]) : null,\n review_interval_days: typeof row.review_interval_days === \"number\" ? row.review_interval_days : null,\n depends_on: Array.isArray(row.depends_on) ? (row.depends_on as string[]) : [],\n version: num(row.version, 1),\n created_by: strOrNull(row.created_by),\n created_at: str(row.created_at),\n updated_at: str(row.updated_at),\n };\n}\n\n/** A System Context item, as `custom.context_system_items` answers it (the door's own words). */\nexport interface StoreSystemItemRow {\n id?: string | null;\n key?: string | null;\n display_name?: string | null;\n description?: string | null;\n item_class?: string | null;\n value_type?: string | null;\n sensitivity?: string | null;\n sort_order?: number | null;\n}\n\n/** A System Context item as a field of the `SYSTEM_CONTEXT_TYPE_ID` pseudo-type, with its class. */\nexport function systemContextFieldFromStore(row: StoreSystemItemRow, index: number): SystemContextField {\n const key = str(row.key);\n const kind = str(row.value_type, \"string\");\n return {\n id: str(row.id),\n scope_type_id: SYSTEM_CONTEXT_TYPE_ID,\n organization_id: \"\",\n key,\n label: str(row.display_name, key),\n description: str(row.description),\n kind: (KINDS.has(kind) ? kind : \"string\") as ContextFieldKind,\n type: \"system\",\n multi: kind === \"array\",\n format: null,\n config: {},\n relation_target: null,\n sort: typeof row.sort_order === \"number\" ? row.sort_order : index,\n context_policy: \"include\",\n // The system table keeps the old sensitivity words (`restricted`/`privileged`), like the write doors.\n sensitivity: SENSITIVITY_FROM_DOOR[str(row.sensitivity)] ?? \"public\",\n source: \"system\",\n status: \"active\",\n status_note: null,\n category: null,\n tags: [],\n max_items: 0,\n custom_component: null,\n reference_source: null,\n allowed_scope_type_ids: null,\n allowed_reference_types: null,\n review_interval_days: null,\n depends_on: [],\n version: 0,\n created_by: null,\n created_at: \"\",\n updated_at: \"\",\n item_class: strOrNull(row.item_class),\n };\n}\n\n\n/** A reference / document cell's targets, with the names and files the door gave this caller. */\nexport function referencesOf(row: Pick<StoreValueRow, \"value\" | \"field\" | \"labels\" | \"files\">): ContextReference[] {\n const v = row.value;\n const list = Array.isArray(v) ? v : v == null ? [] : [v];\n const labels = row.labels ?? {};\n const files = row.files ?? {};\n const toFile = row.field?.relation_target === FILE_KERNEL_ID;\n const out: ContextReference[] = [];\n for (const el of list) {\n let ref: ContextReference | null = null;\n if (typeof el === \"string\" && isUuidShape(el)) ref = { id: el, type: toFile ? \"file\" : \"scope\" };\n else if (el && typeof el === \"object\" && typeof (el as { id?: unknown }).id === \"string\") {\n const token = String((el as { token?: unknown }).token ?? \"\");\n const own = (el as { label?: unknown }).label;\n ref = { id: (el as { id: string }).id, type: token === \"dataset\" ? \"table\" : token || (toFile ? \"file\" : \"scope\") };\n // A reference outside the scope system carries its own label in the store; the door names scopes only.\n if (typeof own === \"string\" && own) ref.label = own;\n }\n if (!ref) continue;\n const label = labels[ref.id];\n if (label) ref.label = label;\n const fileId = files[ref.id];\n if (fileId) ref.file_id = fileId;\n out.push(ref);\n }\n return out;\n}\n\n/** One cell, as a `ContextValue` (its whole text not yet read — see `completeWholeValues`). */\nexport function contextValueFromStore(row: StoreValueRow): ContextValue {\n const kind = contextFieldKind(row.field ?? {}, row.field?.carried);\n const carriedText = Boolean(row.field?.carried?.as_text);\n const isRef = !carriedText && (kind === \"reference\" || kind === \"document\");\n return {\n scope_id: row.scope_id,\n field_id: row.context_item_id,\n key: row.key,\n kind,\n value: row.value ?? null,\n references: isRef ? referencesOf(row) : [],\n version: num(row.version, 1),\n set_at: row.set_at ?? null,\n source_type: row.source_type ?? null,\n authored_by: row.authored_by ?? null,\n whole_value: row.whole_value ?? null,\n incomplete: null,\n };\n}\n\n// ─── whole texts kept as files ──────────────────────────────────────────────────────────────────\n\n/** Reads a file's whole text as the person (the host's one file reader). */\nexport type ReadContextFileText = (fileId: Uuid) => Promise<string>;\n\nasync function sha256Hex(text: string): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) return null;\n const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * A CELL THAT HOLDS ONLY THE FIRST WORDS OF A TEXT KEPT AS A FILE GETS ITS WHOLE TEXT.\n *\n * The store keeps a value over its one-cell ceiling as a file and the cell holds its first words;\n * `custom.context_values` names the file (`whole_value`). Each such value is given the file's whole\n * text — read once per file through the host's reader, checked against the size and SHA-256 the\n * pointer names. A file that cannot be read, or does not match, leaves the first words AND sets\n * `incomplete` (with why) — never the first words passed off as the value. Mutates `values`.\n */\nexport async function completeWholeValues(values: ContextValue[], read: ReadContextFileText | null): Promise<void> {\n const texts = new Map<string, Promise<string>>();\n await Promise.all(\n values.map(async (cell) => {\n const w = cell.whole_value;\n if (!w || w.in_value || typeof cell.value !== \"string\") return;\n const head = cell.value;\n const chars = typeof w.chars === \"number\" ? w.chars : null;\n const incomplete = (fileId: string | null, why: string): void => {\n cell.incomplete = { head, chars, file_id: fileId, why };\n };\n if (!w.file_id) return incomplete(null, \"The rest of this text is still being saved.\");\n if (!read) return incomplete(w.file_id, \"This place cannot open the file that holds the whole text.\");\n if (!texts.has(w.file_id)) texts.set(w.file_id, read(w.file_id));\n try {\n const text = await texts.get(w.file_id)!;\n if (chars !== null && [...text].length !== chars) {\n return incomplete(w.file_id, `The file holds ${[...text].length} characters, not ${chars}.`);\n }\n if (w.sha256) {\n const sha = await sha256Hex(text);\n if (sha === null) return incomplete(w.file_id, \"This browser cannot check the file.\");\n if (sha !== w.sha256) return incomplete(w.file_id, \"The file's content is not the text the cell points at.\");\n }\n cell.value = text;\n } catch (thrown) {\n incomplete(w.file_id, thrown instanceof Error ? thrown.message : String(thrown));\n }\n }),\n );\n}\n\n/** The refusal a person sees when saving would cut a value that was not read whole. */\nexport const INCOMPLETE_SAVE_REFUSAL = \"Only the start of this value loaded. Paste the whole text to replace it.\";\n\n/**\n * The refusal sentence when saving `draft` over a cell that was not read whole would cut the real\n * value — else `null`. Refused: the first words unchanged, and a draft built on them that is shorter\n * than the whole. Allowed: a draft that replaces the text, an explicit clear.\n */\nexport function incompleteSaveRefusal(cell: Pick<ContextValue, \"incomplete\"> | undefined, draft: unknown): string | null {\n const incomplete = cell?.incomplete;\n if (!incomplete || typeof draft !== \"string\" || draft === \"\") return null;\n if (draft === incomplete.head) return INCOMPLETE_SAVE_REFUSAL;\n if (incomplete.head && draft.startsWith(incomplete.head)) {\n const whole = incomplete.chars ?? Number.POSITIVE_INFINITY;\n if ([...draft].length < whole) return INCOMPLETE_SAVE_REFUSAL;\n }\n return null;\n}\n\n// ─── writing ────────────────────────────────────────────────────────────────────────────────────\n\n/** Drop keys whose value is `undefined`, keep `null` (a clear). */\nexport function definedOnly(fields: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(fields)) if (v !== undefined) out[k] = v;\n return out;\n}\n\n/** A field spec in the words `custom.context_item_write` takes. */\nexport function fieldSpecForDoor(spec: ContextFieldSpec): Record<string, unknown> {\n return definedOnly({\n key: spec.key,\n display_name: spec.label,\n value_type: spec.kind,\n description: spec.description,\n category: spec.category,\n fetch_hint: spec.context_policy ? POLICY_TO_DOOR[spec.context_policy] : undefined,\n sensitivity: spec.sensitivity ? SENSITIVITY_TO_DOOR[spec.sensitivity] : undefined,\n tags: spec.tags,\n sort_order: spec.sort,\n status: spec.status,\n status_note: spec.status_note,\n custom_component: spec.custom_component,\n review_interval_days: spec.review_interval_days,\n allowed_reference_types: spec.allowed_reference_types,\n max_items: spec.max_items,\n allowed_scope_type_ids: spec.allowed_scope_type_ids,\n reference_source: spec.reference_source,\n });\n}\n\n/** The canonical reference fence (the same grammar `@ai-matrx/agents/envelope` builds). */\nexport function referenceFence(references: readonly ContextReference[]): string {\n const kinds = [...new Set(references.map((r) => r.type))];\n const type = kinds.length === 1 ? kinds[0]! : \"mixed\";\n const items = references.map((r) => {\n if (r.type === \"file\" && r.file_id) return r.label ? { file_id: r.file_id, label: r.label } : { file_id: r.file_id };\n const item: { id: string; label?: string; type?: string } = { id: r.id };\n if (r.label) item.label = r.label;\n if (kinds.length > 1) item.type = r.type;\n return item;\n });\n return \"```matrx\\n\" + JSON.stringify({ matrx_version: 1, kind: \"reference\", type, items }, null, 2) + \"\\n```\";\n}\n\nconst FENCE_BODY = /```matrx[^\\n]*\\n([\\s\\S]*?)\\n?```/;\n\n/**\n * The things a reference fence points at (the inverse of `referenceFence`). Reads the canonical\n * grammar `{ kind: \"reference\", type, items }`, with or without the ```matrx wrapper; anything that\n * is not a reference fence answers `[]`.\n */\nexport function referencesFromFence(text: string | null | undefined): ContextReference[] {\n if (typeof text !== \"string\" || text.trim() === \"\") return [];\n const body = FENCE_BODY.exec(text)?.[1] ?? text;\n let parsed: unknown;\n try {\n parsed = JSON.parse(body.trim());\n } catch {\n return [];\n }\n if (!parsed || typeof parsed !== \"object\") return [];\n const fence = parsed as { kind?: unknown; type?: unknown; items?: unknown };\n if (fence.kind !== \"reference\" || !Array.isArray(fence.items)) return [];\n const noun = typeof fence.type === \"string\" ? fence.type : \"\";\n return fence.items.flatMap((raw): ContextReference[] => {\n if (!raw || typeof raw !== \"object\") return [];\n const item = raw as { id?: unknown; file_id?: unknown; label?: unknown; type?: unknown };\n const label = typeof item.label === \"string\" && item.label ? { label: item.label } : {};\n if (typeof item.file_id === \"string\" && item.file_id) {\n return [{ id: typeof item.id === \"string\" ? item.id : item.file_id, type: \"file\", file_id: item.file_id, ...label }];\n }\n if (typeof item.id !== \"string\" || !item.id) return [];\n const type = typeof item.type === \"string\" && item.type ? item.type : noun || \"scope\";\n return [{ id: item.id, type, ...label }];\n });\n}\n\nconst isContextReference = (v: unknown): v is ContextReference =>\n !!v && typeof v === \"object\" && typeof (v as { id?: unknown }).id === \"string\" && typeof (v as { type?: unknown }).type === \"string\";\n\n/**\n * THE ONE WRITE AN EDIT BECOMES: an editor's raw value for `field` on `scopeId`, as a\n * `ContextValueWrite`. A reference / document field takes a fence (what the reference picker edits)\n * or a list of `ContextReference`s and writes `references`; a clear (`null`, `undefined`, `\"\"`)\n * writes no references. Any other field writes `value`, with `\"\"` and `undefined` a clear (`null`).\n * Written by a person (`source_type: \"manual\"`) unless `options` says otherwise.\n */\nexport function contextValueWrite(\n field: Pick<ContextField, \"id\" | \"kind\">,\n scopeId: Uuid,\n raw: unknown,\n options: { source_type?: string; change_summary?: string } = {},\n): ContextValueWrite {\n const base: ContextValueWrite = {\n scope_id: scopeId,\n field_id: field.id,\n kind: field.kind,\n source_type: options.source_type ?? \"manual\",\n ...(options.change_summary ? { change_summary: options.change_summary } : {}),\n };\n if (field.kind === \"reference\" || field.kind === \"document\") {\n if (typeof raw === \"string\") return { ...base, references: referencesFromFence(raw) };\n if (Array.isArray(raw)) {\n return {\n ...base,\n references: raw.flatMap((el): ContextReference[] =>\n isContextReference(el) ? [el] : typeof el === \"string\" ? referencesFromFence(el) : [],\n ),\n };\n }\n return { ...base, references: [] };\n }\n return { ...base, value: raw === \"\" || raw === undefined ? null : raw };\n}\n\n/**\n * One cell in the payload `custom.context_value_write` takes: the value lands in the slot the door\n * reads for the field's kind; a reference cell is the canonical fence the door's reference rule reads.\n */\nexport function valuePayloadForDoor(write: ContextValueWrite): Record<string, unknown> {\n const base: Record<string, unknown> = definedOnly({\n scope_id: write.scope_id,\n context_item_id: write.field_id,\n source_type: write.source_type,\n change_summary: write.change_summary,\n });\n const v = write.value;\n if (write.kind === \"reference\" || write.kind === \"document\") {\n if (write.references) return { ...base, value_text: write.references.length ? referenceFence(write.references) : null };\n // A document cell may also be written as a url.\n if (write.kind === \"document\" && typeof v === \"string\") return { ...base, value_document_url: v || null };\n return { ...base, value_text: typeof v === \"string\" ? v || null : null };\n }\n if (v === null || v === undefined || v === \"\") {\n return { ...base, value_text: null };\n }\n switch (write.kind) {\n case \"number\":\n case \"percent\":\n return typeof v === \"number\" ? { ...base, value_number: v } : { ...base, value_text: String(v) };\n case \"currency\":\n return typeof v === \"object\" ? { ...base, value_json: v } : typeof v === \"number\" ? { ...base, value_number: v } : { ...base, value_text: String(v) };\n case \"boolean\":\n return typeof v === \"boolean\" ? { ...base, value_boolean: v } : { ...base, value_text: String(v) };\n case \"date\":\n return { ...base, value_date: String(v) };\n case \"datetime\":\n return { ...base, value_timestamp: String(v) };\n case \"time\":\n return { ...base, value_time: String(v) };\n case \"object\":\n case \"array\":\n return typeof v === \"object\" ? { ...base, value_json: v } : { ...base, value_text: String(v) };\n default:\n return typeof v === \"object\" ? { ...base, value_json: v } : { ...base, value_text: String(v) };\n }\n}\n","// src/scopes/rules.ts — @ai-matrx/records/scopes\n//\n// The few rules a screen needs BEFORE it asks a door, each a mirror of what the door itself decides\n// (the door is the authority; this only spares a person a button that would be refused).\n\nimport type { RecordsResult } from \"../results\";\nimport type { Uuid } from \"../record\";\n\n/** An organization role, as `iam.organization_member` holds it. */\nexport type ScopeSeatRole = \"owner\" | \"admin\" | \"member\" | string;\n\n/**\n * WHO MAY CHANGE A SCOPE TYPE'S STRUCTURE — rename it, add/edit/archive its fields, archive or restore\n * it: an organization owner or admin, or the person who made the type. Every member works the DATA\n * (adds, renames, archives and restores scopes, writes values). Arman 2026-10-07: \"structure is the\n * org admins' and the creator's\". Mirrors `custom.context_type_write` / `_archive` / `_restore` and\n * `custom.context_item_write` / `_archive` / `_restore`.\n */\nexport function canShapeScopeType(\n role: ScopeSeatRole | null | undefined,\n userId: Uuid | null | undefined,\n type: { created_by?: Uuid | null } | null | undefined,\n): boolean {\n if (role === \"owner\" || role === \"admin\") return true;\n return !!userId && !!type?.created_by && type.created_by === userId;\n}\n\n/** Display name → kebab URL slug. */\nexport function toSlug(name: string): string {\n return name\n .toLowerCase()\n .trim()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\n/** Display name → snake_case field key. */\nexport function toFieldKey(name: string): string {\n return name\n .toLowerCase()\n .trim()\n .replace(/[\\s-]+/g, \"_\")\n .replace(/[^a-z0-9_]/g, \"\")\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n}\n\n/** True when `s` is a clean slug: a-z, 0-9, single hyphens or underscores between words. */\nexport function isValidSlug(s: string): boolean {\n return /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s);\n}\n\n/** Route segments that are literal pages of the scope screens; no slug may equal one. */\nexport const RESERVED_SCOPE_SLUGS: ReadonlySet<string> = new Set([\"context-items\", \"scopes\", \"edit\", \"manage\", \"new\", \"settings\"]);\n\nexport function isReservedSlug(s: string): boolean {\n return RESERVED_SCOPE_SLUGS.has(s.toLowerCase().replace(/_/g, \"-\"));\n}\n\n/**\n * Two slugs name the same thing when they differ only by `-` ↔ `_` (the store's Table grammar is\n * `practice_areas`; a link a person typed may say `practice-areas`).\n */\nexport function sameSlug(a: string | null | undefined, b: string | null | undefined): boolean {\n if (!a || !b) return false;\n return a.toLowerCase().replace(/_/g, \"-\") === b.toLowerCase().replace(/_/g, \"-\");\n}\n\n/** The slug a write sends: the one supplied, else one made from the name; refused when unusable. */\nexport function resolveSlug(supplied: string | undefined, fallbackName: string): RecordsResult<string> {\n const slug = supplied?.trim() || toSlug(fallbackName);\n if (!slug || !isValidSlug(slug)) {\n return {\n ok: false,\n error: { code: \"invalid_argument\", message: \"Use letters, numbers and single hyphens for the short name.\" },\n };\n }\n if (isReservedSlug(slug)) {\n return { ok: false, error: { code: \"invalid_argument\", message: `\"${slug}\" is a page name here. Pick another short name.` } };\n }\n return { ok: true, data: slug };\n}\n","// src/scopes/doors.ts — @ai-matrx/records/scopes\n//\n// THE SCOPE DOORS, ONE CALL EACH, THROUGH THE RECORDS CLIENT'S OWN DOOR PATH.\n//\n// `client.scopes` is built from the same `callDoor` every other method of the client uses, so a scope\n// read gets what every store read gets: the schema said out loud, one request in flight per question,\n// a door the store lacks refused as `door_absent` (never an empty list), and every refusal in the\n// store's own words (`RecordsError`). Nothing here talks to Supabase itself.\n//\n// The doors take explicit organizations (a scope read spans every organization the person belongs\n// to; a write names its own), so the client's `organizationId` is never used here.\n\nimport type { RecordsErrorCode, RecordsResult } from \"../results\";\nimport type { Uuid } from \"../record\";\nimport {\n archivedScopeTypeFromStore,\n completeWholeValues,\n contextFieldFromStore,\n contextValueFromStore,\n definedOnly,\n fieldSpecForDoor,\n scopeFromStore,\n scopeTypeFromStore,\n scopeWithTypeFromStore,\n systemContextFieldFromStore,\n valuePayloadForDoor,\n type ReadContextFileText,\n type StoreArchivedTypeRow,\n type StoreItemRow,\n type StoreScopeRow,\n type StoreSystemItemRow,\n type StoreTypeRow,\n type StoreValueRow,\n} from \"./codec\";\nimport { resolveSlug } from \"./rules\";\nimport type {\n ArchivedScope,\n ArchivedScopeType,\n ContextField,\n ContextFieldSpec,\n ContextValue,\n ContextValueWrite,\n ContextValueWritten,\n Scope,\n ScopePage,\n ScopeSpec,\n ScopeTemplate,\n ScopeType,\n ScopeTypeSkeleton,\n ScopeTypeSpec,\n ScopeTypeWithScopes,\n ScopeWithType,\n SystemContextField,\n TableTemplate,\n} from \"./types\";\n\n/** The client's one door call (`callDoor` in core/client.ts). */\nexport type ScopeDoorCall = <T>(door: string, args: Record<string, unknown>, where: string) => Promise<RecordsResult<T>>;\n\n/** The kernel Table every Field is a record of. */\nexport const FIELD_KERNEL_ID = \"11111111-0000-4000-8000-000000000002\";\n\n/** How many ids one call of each batched door takes. */\nexport const SCOPES_PER_CALL = 500;\nexport const SCOPE_TYPES_PER_FIELDS_CALL = 100;\n/** `custom.context_values` refuses more than this many scopes in one call. */\nexport const SCOPES_PER_VALUES_CALL = 200;\n/** One page of a type's scopes (the door's default; it answers at most 1000). */\nexport const TYPE_SCOPES_PAGE = 200;\n/** The archive answers at most this many rows a call (`custom.page_size` ceiling). */\nexport const ARCHIVED_SCOPES_PAGE = 200;\n\nexport interface ScopeDoors {\n // ── reads ──────────────────────────────────────────────────────────────────────────────────\n /** Every live scope type of these organizations, each with its live scopes. */\n tree(organizationIds: readonly Uuid[]): Promise<RecordsResult<ScopeTypeWithScopes[]>>;\n /** The scope types of these organizations without their scopes (the first paint), with or without counts. */\n types(organizationIds: readonly Uuid[], options?: { withCounts?: boolean }): Promise<RecordsResult<ScopeTypeSkeleton>>;\n /** One page of one type's scopes, in the tree's order. */\n typeScopesPage(scopeTypeId: Uuid, offset?: number, limit?: number): Promise<RecordsResult<ScopePage>>;\n /** The scopes whose name holds `query` (case-insensitive), across these organizations. */\n search(organizationIds: readonly Uuid[], query: string, limit?: number): Promise<RecordsResult<{ scopes: Scope[]; total: number }>>;\n /** Scopes by id, each with its type's label, in whichever organization each lives. */\n scopes(ids: readonly Uuid[]): Promise<RecordsResult<ScopeWithType[]>>;\n /**\n * The context fields (columns) of these scope types, each type's fields in their order (`sort`,\n * then label) as the door answers them.\n */\n fields(scopeTypeIds: readonly Uuid[]): Promise<RecordsResult<ContextField[]>>;\n /**\n * One context field by its id, read in whichever of these organizations holds it (a Field is a\n * record of the field kernel; its scope type is the Table it is defined on). Refused `not_found`\n * when no organization answers it.\n */\n field(fieldId: Uuid, organizationIds: readonly Uuid[]): Promise<RecordsResult<ContextField>>;\n /**\n * The cells of these scopes. A text kept as a file is read whole through `readFileText`; without\n * one (or when the file cannot be read) the cell keeps its first words and says so (`incomplete`).\n */\n values(scopeIds: readonly Uuid[], options?: { readFileText?: ReadContextFileText | null }): Promise<RecordsResult<ContextValue[]>>;\n /** The archived scope types of one organization. */\n archivedTypes(organizationId: Uuid): Promise<RecordsResult<ArchivedScopeType[]>>;\n /** Of these scope ids, the ones that are ARCHIVED scopes of this type. */\n archivedScopesOfType(organizationId: Uuid, scopeTypeId: Uuid, wanted: ReadonlySet<Uuid>): Promise<RecordsResult<ArchivedScope[]>>;\n /** The System Context items (not scopes: the platform's own ambient context). */\n systemItems(): Promise<RecordsResult<SystemContextField[]>>;\n /** The table templates an organization's scope dataset fields may use (its own and the platform's). */\n tableTemplates(organizationId: Uuid): Promise<RecordsResult<TableTemplate[]>>;\n /** The scope templates of the gallery. */\n templates(): Promise<RecordsResult<ScopeTemplate[]>>;\n\n // ── writes ─────────────────────────────────────────────────────────────────────────────────\n /** A new scope type in `organizationId`. */\n createType(organizationId: Uuid, spec: ScopeTypeSpec): Promise<RecordsResult<ScopeType>>;\n /** Change a scope type (only the keys given). */\n updateType(typeId: Uuid, spec: ScopeTypeSpec): Promise<RecordsResult<ScopeType>>;\n /** Archive a scope type; its scopes and fields come back with a restore. */\n archiveType(typeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n restoreType(typeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n /** A new scope of `typeId` in `organizationId`. */\n createScope(organizationId: Uuid, typeId: Uuid, spec: ScopeSpec): Promise<RecordsResult<Scope>>;\n updateScope(scopeId: Uuid, spec: ScopeSpec): Promise<RecordsResult<Scope>>;\n archiveScope(scopeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n restoreScope(scopeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n /** A new context field (column) on a scope type. Answers the field as the read door does. */\n createField(scopeTypeId: Uuid, spec: ContextFieldSpec): Promise<RecordsResult<ContextField>>;\n /** Change a context field (`null` clears a key). Answers the field as the read door does. */\n updateField(fieldId: Uuid, scopeTypeId: Uuid, spec: ContextFieldSpec): Promise<RecordsResult<ContextField>>;\n archiveField(fieldId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n restoreField(fieldId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n /** Write one cell. */\n writeValue(write: ContextValueWrite): Promise<RecordsResult<ContextValueWritten>>;\n}\n\nconst uniq = (ids: readonly string[]): string[] => [...new Set(ids.filter(Boolean))];\n\n/** The ids in batches of `size`, each batch one call, answers concatenated in order. */\nasync function inBatches<T>(\n ids: readonly string[],\n size: number,\n call: (batch: string[]) => Promise<RecordsResult<T[] | null>>,\n): Promise<RecordsResult<T[]>> {\n const unique = uniq(ids);\n const batches: string[][] = [];\n for (let i = 0; i < unique.length; i += size) batches.push(unique.slice(i, i + size));\n const answers = await Promise.all(batches.map(call));\n const out: T[] = [];\n for (const a of answers) {\n if (!a.ok) return a;\n out.push(...(a.data ?? []));\n }\n return { ok: true, data: out };\n}\n\n/** A write door's answer: `{ ok, writer, row, store }`. */\ninterface WriteAnswer {\n ok?: boolean;\n row?: Record<string, unknown> | null;\n}\n\nfunction noRow<T>(door: string): RecordsResult<T> {\n return { ok: false, error: { code: \"internal\", message: `${door} answered without the row it wrote.`, diagnostic: `@ai-matrx/records/scopes: ${door}` } };\n}\n\n/** The value door answers its own envelope; its codes, as the package's. */\nconst VALUE_DOOR_CODES: Record<string, RecordsErrorCode> = {\n unauthorized: \"door\",\n forbidden: \"door\",\n forbidden_org: \"door\",\n not_found: \"not_found\",\n invalid_argument: \"invalid_argument\",\n conflict: \"stale_write\",\n unavailable: \"not_supported\",\n};\n\nexport function createScopeDoors(call: ScopeDoorCall): ScopeDoors {\n async function write(door: string, args: Record<string, unknown>): Promise<RecordsResult<Record<string, unknown>>> {\n const res = await call<WriteAnswer>(door, args, `scopes.${door}`);\n if (!res.ok) return res;\n const row = res.data?.row;\n if (!row || typeof row !== \"object\") return noRow(door);\n return { ok: true, data: row };\n }\n\n async function archiveOrRestore(door: string, args: Record<string, unknown>, id: Uuid): Promise<RecordsResult<{ id: Uuid }>> {\n const res = await call<unknown>(door, args, `scopes.${door}`);\n return res.ok ? { ok: true, data: { id } } : res;\n }\n\n async function fieldById(scopeTypeId: Uuid, fieldId: Uuid, door: string): Promise<RecordsResult<ContextField>> {\n const fields = await doors.fields([scopeTypeId]);\n if (!fields.ok) return fields;\n const field = fields.data.find((f) => f.id === fieldId);\n return field ? { ok: true, data: field } : noRow(door);\n }\n\n const doors: ScopeDoors = {\n async tree(organizationIds) {\n const ids = uniq(organizationIds);\n if (ids.length === 0) return { ok: true, data: [] };\n const res = await call<{ types?: StoreTypeRow[]; scopes?: StoreScopeRow[] } | null>(\"context_tree\", { p_organization_ids: ids }, \"scopes.tree\");\n if (!res.ok) return res;\n const byType = new Map<string, Scope[]>();\n for (const s of res.data?.scopes ?? []) {\n const scope = scopeFromStore(s);\n const list = byType.get(scope.scope_type_id) ?? [];\n list.push(scope);\n byType.set(scope.scope_type_id, list);\n }\n return { ok: true, data: (res.data?.types ?? []).map((t) => ({ ...scopeTypeFromStore(t), scopes: byType.get(t.id) ?? [] })) };\n },\n\n async types(organizationIds, options) {\n const withCounts = options?.withCounts ?? true;\n const ids = uniq(organizationIds);\n if (ids.length === 0) return { ok: true, data: { types: [], counts: withCounts ? {} : null } };\n const res = await call<{ types?: StoreTypeRow[] } | null>(\"context_tree_types\", { p_organization_ids: ids, p_with_counts: withCounts }, \"scopes.types\");\n if (!res.ok) return res;\n const rows = res.data?.types ?? [];\n const counts: Record<string, number> | null = withCounts ? {} : null;\n if (counts) for (const r of rows) counts[r.id] = Number(r.scope_count ?? 0);\n return { ok: true, data: { types: rows.map(scopeTypeFromStore), counts } };\n },\n\n async typeScopesPage(scopeTypeId, offset = 0, limit = TYPE_SCOPES_PAGE) {\n const res = await call<{ scopes?: StoreScopeRow[]; total?: number; next_offset?: number | null } | null>(\n \"context_tree_type_scopes\",\n { p_scope_type_id: scopeTypeId, p_offset: offset, p_limit: limit },\n \"scopes.typeScopesPage\",\n );\n if (!res.ok) return res;\n return {\n ok: true,\n data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0), next_offset: res.data?.next_offset ?? null },\n };\n },\n\n async search(organizationIds, query, limit = 100) {\n const ids = uniq(organizationIds);\n const q = query.trim();\n if (ids.length === 0 || q === \"\") return { ok: true, data: { scopes: [], total: 0 } };\n const res = await call<{ scopes?: StoreScopeRow[]; total?: number } | null>(\n \"context_tree_search\",\n { p_organization_ids: ids, p_query: q, p_limit: limit },\n \"scopes.search\",\n );\n if (!res.ok) return res;\n return { ok: true, data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0) } };\n },\n\n async scopes(ids) {\n const res = await inBatches(ids, SCOPES_PER_CALL, (batch) => call<StoreScopeRow[]>(\"context_scopes\", { p_scope_ids: batch }, \"scopes.scopes\"));\n return res.ok ? { ok: true, data: res.data.map(scopeWithTypeFromStore) } : res;\n },\n\n async fields(scopeTypeIds) {\n const res = await inBatches(scopeTypeIds, SCOPE_TYPES_PER_FIELDS_CALL, (batch) =>\n call<StoreItemRow[]>(\"context_items\", { p_scope_type_ids: batch }, \"scopes.fields\"),\n );\n return res.ok ? { ok: true, data: res.data.map(contextFieldFromStore) } : res;\n },\n\n async field(fieldId, organizationIds) {\n const orgs = uniq(organizationIds);\n const answers = await Promise.all(\n orgs.map((org) =>\n call<Array<{ id: string; document?: { entity_definition_id?: unknown } | null }> | null>(\n \"read_records_by_ids\",\n { p_organization_id: org, p_table_id: FIELD_KERNEL_ID, p_record_ids: [fieldId], p_by_id: false },\n \"scopes.field\",\n ),\n ),\n );\n let refusal: RecordsResult<ContextField> | null = null;\n for (const answer of answers) {\n if (!answer.ok) {\n refusal ??= answer;\n continue;\n }\n const typeId = answer.data?.find((r) => r.id === fieldId)?.document?.entity_definition_id;\n if (typeof typeId !== \"string\") continue;\n const fields = await doors.fields([typeId]);\n if (!fields.ok) return fields;\n const field = fields.data.find((f) => f.id === fieldId);\n if (field) return { ok: true, data: field };\n }\n return (\n refusal ?? {\n ok: false,\n error: { code: \"not_found\", message: \"This context field could not be found.\", diagnostic: `@ai-matrx/records/scopes: field ${fieldId}` },\n }\n );\n },\n\n async values(scopeIds, options) {\n const res = await inBatches(scopeIds, SCOPES_PER_VALUES_CALL, (batch) =>\n call<StoreValueRow[]>(\"context_values\", { p_scope_ids: batch }, \"scopes.values\"),\n );\n if (!res.ok) return res;\n const cells = res.data.map(contextValueFromStore);\n await completeWholeValues(cells, options?.readFileText ?? null);\n return { ok: true, data: cells };\n },\n\n async archivedTypes(organizationId) {\n const res = await call<StoreArchivedTypeRow[] | null>(\"context_archived_types\", { p_organization_id: organizationId }, \"scopes.archivedTypes\");\n return res.ok ? { ok: true, data: (res.data ?? []).map(archivedScopeTypeFromStore) } : res;\n },\n\n async archivedScopesOfType(organizationId, scopeTypeId, wanted) {\n const out: ArchivedScope[] = [];\n for (let offset = 0; out.length < wanted.size; offset += ARCHIVED_SCOPES_PAGE) {\n const res = await call<Array<{ id: string; document?: { name?: unknown; slug?: unknown } | null; archived_at?: string | null }> | null>(\n \"read_records_archived\",\n { p_organization_id: organizationId, p_table_id: scopeTypeId, p_lane: \"org\", p_by_id: false, p_limit: ARCHIVED_SCOPES_PAGE, p_offset: offset },\n \"scopes.archivedScopesOfType\",\n );\n if (!res.ok) return res;\n const rows = res.data ?? [];\n for (const r of rows) {\n if (!wanted.has(r.id)) continue;\n out.push({\n id: r.id,\n name: typeof r.document?.name === \"string\" ? r.document.name : null,\n slug: typeof r.document?.slug === \"string\" ? r.document.slug : null,\n archived_at: r.archived_at ?? null,\n });\n }\n if (rows.length < ARCHIVED_SCOPES_PAGE) break;\n }\n return { ok: true, data: out };\n },\n\n async systemItems() {\n const res = await call<StoreSystemItemRow[] | null>(\"context_system_items\", {}, \"scopes.systemItems\");\n return res.ok ? { ok: true, data: (res.data ?? []).map(systemContextFieldFromStore) } : res;\n },\n\n async tableTemplates(organizationId) {\n const res = await call<TableTemplate[] | null>(\"table_templates\", { p_org_id: organizationId }, \"scopes.tableTemplates\");\n return res.ok ? { ok: true, data: Array.isArray(res.data) ? res.data : [] } : res;\n },\n\n async templates() {\n const res = await call<ScopeTemplate[] | null>(\"context_templates\", {}, \"scopes.templates\");\n return res.ok ? { ok: true, data: res.data ?? [] } : res;\n },\n\n async createType(organizationId, spec) {\n const slug = resolveSlug(spec.slug, spec.label_plural || spec.label_singular || \"\");\n if (!slug.ok) return slug;\n const res = await write(\"context_type_write\", {\n p_organization_id: organizationId,\n p_type_id: null,\n p_spec: definedOnly({\n label_singular: spec.label_singular,\n label_plural: spec.label_plural,\n icon: spec.icon ?? \"folder\",\n description: spec.description ?? \"\",\n sort_order: spec.sort_order ?? 0,\n max_assignments: spec.max_assignments_per_entity ?? undefined,\n default_variable_keys: spec.default_variable_keys ?? [],\n color: spec.color,\n slug: slug.data,\n }),\n });\n return res.ok ? { ok: true, data: scopeTypeFromStore(res.data as unknown as StoreTypeRow) } : res;\n },\n\n async updateType(typeId, spec) {\n let slug: string | undefined;\n if (spec.slug !== undefined) {\n const resolved = resolveSlug(spec.slug, spec.label_plural ?? spec.label_singular ?? \"\");\n if (!resolved.ok) return resolved;\n slug = resolved.data;\n }\n const res = await write(\"context_type_write\", {\n p_organization_id: null,\n p_type_id: typeId,\n p_spec: definedOnly({\n label_singular: spec.label_singular,\n label_plural: spec.label_plural,\n icon: spec.icon,\n description: spec.description,\n sort_order: spec.sort_order,\n max_assignments: spec.max_assignments_per_entity,\n color: spec.color,\n slug,\n }),\n });\n return res.ok ? { ok: true, data: scopeTypeFromStore(res.data as unknown as StoreTypeRow) } : res;\n },\n\n archiveType: (typeId) => archiveOrRestore(\"context_type_archive\", { p_type_id: typeId }, typeId),\n restoreType: (typeId) => archiveOrRestore(\"context_type_restore\", { p_type_id: typeId }, typeId),\n\n async createScope(organizationId, typeId, spec) {\n const slug = resolveSlug(spec.slug, spec.name ?? \"\");\n if (!slug.ok) return slug;\n const res = await write(\"context_scope_write\", {\n p_organization_id: organizationId,\n p_scope_id: null,\n p_type_id: typeId,\n p_spec: definedOnly({\n name: spec.name,\n parent_scope_id: spec.parent_scope_id,\n description: spec.description ?? \"\",\n settings: spec.settings ?? {},\n slug: slug.data,\n sort_order: spec.sort_order,\n }),\n });\n return res.ok ? { ok: true, data: scopeFromStore(res.data as unknown as StoreScopeRow) } : res;\n },\n\n async updateScope(scopeId, spec) {\n let slug: string | undefined;\n if (spec.slug !== undefined) {\n const resolved = resolveSlug(spec.slug, spec.name ?? \"\");\n if (!resolved.ok) return resolved;\n slug = resolved.data;\n }\n const res = await write(\"context_scope_write\", {\n p_organization_id: null,\n p_scope_id: scopeId,\n p_type_id: null,\n p_spec: definedOnly({ name: spec.name, description: spec.description, settings: spec.settings, slug, sort_order: spec.sort_order }),\n });\n return res.ok ? { ok: true, data: scopeFromStore(res.data as unknown as StoreScopeRow) } : res;\n },\n\n archiveScope: (scopeId) => archiveOrRestore(\"context_scope_archive\", { p_scope_id: scopeId }, scopeId),\n restoreScope: (scopeId) => archiveOrRestore(\"context_scope_restore\", { p_scope_id: scopeId }, scopeId),\n\n async createField(scopeTypeId, spec) {\n const res = await write(\"context_item_write\", {\n p_item_id: null,\n p_scope_type_id: scopeTypeId,\n p_spec: fieldSpecForDoor({ kind: \"string\", description: \"\", context_policy: \"on_request\", sensitivity: \"internal\", tags: [], ...spec }),\n });\n if (!res.ok) return res;\n return fieldById(scopeTypeId, String(res.data.id), \"context_item_write\");\n },\n\n async updateField(fieldId, scopeTypeId, spec) {\n const res = await write(\"context_item_write\", { p_item_id: fieldId, p_scope_type_id: null, p_spec: fieldSpecForDoor(spec) });\n if (!res.ok) return res;\n return fieldById(scopeTypeId, fieldId, \"context_item_write\");\n },\n\n archiveField: (fieldId) => archiveOrRestore(\"context_item_archive\", { p_item_id: fieldId }, fieldId),\n restoreField: (fieldId) => archiveOrRestore(\"context_item_restore\", { p_item_id: fieldId }, fieldId),\n\n async writeValue(cell) {\n const res = await call<{ ok?: boolean; data?: { version?: number; source_type?: string }; error?: { code?: string; message?: string } } | null>(\n \"context_value_write\",\n { p_payload: { source_type: \"ai_enriched\", ...valuePayloadForDoor(cell) } },\n \"scopes.writeValue\",\n );\n if (!res.ok) return res;\n const envelope = res.data ?? {};\n if (!envelope.ok) {\n const code = VALUE_DOOR_CODES[envelope.error?.code ?? \"\"] ?? \"internal\";\n return { ok: false, error: { code, message: envelope.error?.message ?? \"The value was not saved.\" } };\n }\n return {\n ok: true,\n data: {\n scope_id: cell.scope_id,\n field_id: cell.field_id,\n version: Number(envelope.data?.version ?? 1),\n source_type: String(envelope.data?.source_type ?? cell.source_type ?? \"ai_enriched\"),\n },\n };\n },\n };\n return doors;\n}\n","// src/scopes/resolve.ts — @ai-matrx/records/scopes (HEADLESS, pure)\n//\n// The two pure joins every scope screen and chat need, so no host re-derives them:\n//\n// joinFieldValues a scope type's context fields beside one scope's values (one row per field)\n// resolveScopeContext local-vs-global resolution: which scope's cell wins each field\n//\n// Resolution rule: sources are ranked closer-first — local task (1000), local project (1100), local\n// scopes (1200…), global task (2000), global project (2100), global scopes (2200…). The first SCOPE\n// source holding a value for a field owns it. A contradiction is the same scope type selected\n// globally and tagged locally with a DIFFERENT scope; it is informational and never blocks.\n\nimport type { Uuid } from \"../record\";\nimport { referenceFence } from \"./codec\";\nimport type { ContextField, ContextFieldKind, ContextReference, ContextValue, Scope } from \"./types\";\n\n/** One context field of a scope type beside the scope's value for it (`value` null = empty). */\nexport interface ScopeFieldValue {\n field: ContextField;\n value: ContextValue | null;\n has_value: boolean;\n}\n\n/** A scope type's fields beside one scope's values, in the fields' order. */\nexport function joinFieldValues(\n fields: readonly ContextField[],\n values: Readonly<Record<Uuid, ContextValue | undefined>>,\n): ScopeFieldValue[] {\n return fields.map((field) => {\n const value = values[field.id] ?? null;\n return { field, value, has_value: value !== null && hasCell(value) };\n });\n}\n\n/** Whether a value holds anything: a reference cell its references, any other cell a non-empty value. */\nexport function hasCell(value: Pick<ContextValue, \"kind\" | \"value\" | \"references\">): boolean {\n if (value.kind === \"reference\" || value.kind === \"document\") return value.references.length > 0;\n const v = value.value;\n if (v === null || v === undefined) return false;\n if (typeof v === \"string\") return v.length > 0;\n if (Array.isArray(v)) return v.length > 0;\n return true;\n}\n\nexport type ContextSourceKind = \"scope\" | \"project\" | \"task\";\nexport type ContextSourceOrigin = \"local\" | \"global\";\n\n/** One contributor to a resolved context. Lower `priority` = closer to the action. */\nexport interface ContextSource {\n kind: ContextSourceKind;\n id: Uuid;\n origin: ContextSourceOrigin;\n priority: number;\n}\n\n/** A resolved cell. A reference cell's `value` is its `referenceFence(references)`. */\nexport interface ResolvedValue {\n field_id: Uuid;\n key: string;\n label: string;\n kind: ContextFieldKind;\n value: unknown;\n references: ContextReference[];\n version: number;\n}\n\nexport interface ScopeContradiction {\n scope_type_id: Uuid;\n global_scope_id: Uuid;\n local_scope_id: Uuid;\n}\n\nexport interface ResolvedScopeContext {\n /** field id → the winning cell. */\n values: Record<Uuid, ResolvedValue>;\n /** field id → the source that won it. */\n sourcePerKey: Record<Uuid, ContextSource>;\n contradictions: ScopeContradiction[];\n /** Every contributing source, closest first. */\n activeScopes: ContextSource[];\n}\n\nexport interface ResolveScopeContextInput {\n /** Finds a scope (for its type) by id; a scope it cannot find contributes nothing locally. */\n scopeById: (id: Uuid) => Pick<Scope, \"id\" | \"scope_type_id\"> | undefined;\n local?: { taskId?: Uuid | null; projectId?: Uuid | null; scopeIds?: readonly Uuid[] };\n global?: { taskId?: Uuid | null; projectId?: Uuid | null; scopeIds?: readonly Uuid[] };\n /** scope id → its values by field id; a scope whose values are not read yet is absent. */\n valuesByScope: Readonly<Record<Uuid, Readonly<Record<Uuid, ContextValue>> | undefined>>;\n /** field id → its field, for the label (a field not here resolves with an empty label). */\n fieldById?: (id: Uuid) => Pick<ContextField, \"label\"> | undefined;\n}\n\n/** Local-vs-global resolution of the active scopes' values (see the header for the rule). */\nexport function resolveScopeContext(input: ResolveScopeContextInput): ResolvedScopeContext {\n const { scopeById, valuesByScope } = input;\n const local = input.local ?? {};\n const global = input.global ?? {};\n const localScopeIds = local.scopeIds ?? [];\n const sources: ContextSource[] = [];\n\n if (local.taskId) sources.push({ kind: \"task\", id: local.taskId, origin: \"local\", priority: 1000 });\n if (local.projectId) sources.push({ kind: \"project\", id: local.projectId, origin: \"local\", priority: 1100 });\n let localPri = 1200;\n const localScopeTypeIds = new Set<Uuid>();\n for (const sid of localScopeIds) {\n const scope = scopeById(sid);\n if (!scope) continue;\n localScopeTypeIds.add(scope.scope_type_id);\n sources.push({ kind: \"scope\", id: sid, origin: \"local\", priority: localPri++ });\n }\n\n if (global.taskId) sources.push({ kind: \"task\", id: global.taskId, origin: \"global\", priority: 2000 });\n if (global.projectId) sources.push({ kind: \"project\", id: global.projectId, origin: \"global\", priority: 2100 });\n let globalPri = 2200;\n const contradictions: ScopeContradiction[] = [];\n for (const scopeId of global.scopeIds ?? []) {\n if (!scopeId) continue;\n const typeId = scopeById(scopeId)?.scope_type_id ?? null;\n if (typeId && localScopeTypeIds.has(typeId)) {\n const localId = localScopeIds.find((sid) => scopeById(sid)?.scope_type_id === typeId);\n if (localId && localId !== scopeId) {\n contradictions.push({ scope_type_id: typeId, global_scope_id: scopeId, local_scope_id: localId });\n }\n }\n sources.push({ kind: \"scope\", id: scopeId, origin: \"global\", priority: globalPri++ });\n }\n\n const sorted = sources.slice().sort((a, b) => a.priority - b.priority);\n const values: Record<Uuid, ResolvedValue> = {};\n const sourcePerKey: Record<Uuid, ContextSource> = {};\n for (const source of sorted) {\n if (source.kind !== \"scope\") continue;\n const cells = valuesByScope[source.id];\n if (!cells) continue;\n for (const fieldId of Object.keys(cells)) {\n if (values[fieldId]) continue;\n const cell = cells[fieldId]!;\n if (!hasCell(cell)) continue;\n values[fieldId] = toResolvedValue(cell, input.fieldById?.(fieldId)?.label ?? \"\");\n sourcePerKey[fieldId] = source;\n }\n }\n return { values, sourcePerKey, contradictions, activeScopes: sorted };\n}\n\n/** One cell as a resolved value: a reference cell's `value` is its fence. */\nexport function toResolvedValue(cell: ContextValue, label = \"\"): ResolvedValue {\n const isRef = cell.kind === \"reference\" || cell.kind === \"document\";\n return {\n field_id: cell.field_id,\n key: cell.key,\n label,\n kind: cell.kind,\n value: isRef ? referenceFence(cell.references) : cell.value,\n references: cell.references,\n version: cell.version,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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isUuidShape } from "@ai-matrx/kit/uuid";
24
25
  var str = (v, fallback = "") => typeof v === "string" ? v : fallback;
25
26
  var strOrNull = (v) => typeof v === "string" ? v : null;
26
27
  var num = (v, fallback = 0) => {
@@ -236,7 +237,6 @@ function systemContextFieldFromStore(row, index) {
236
237
  item_class: strOrNull(row.item_class)
237
238
  };
238
239
  }
239
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
240
240
  function referencesOf(row) {
241
241
  const v = row.value;
242
242
  const list = Array.isArray(v) ? v : v == null ? [] : [v];
@@ -246,7 +246,7 @@ function referencesOf(row) {
246
246
  const out = [];
247
247
  for (const el of list) {
248
248
  let ref = null;
249
- if (typeof el === "string" && UUID.test(el)) ref = { id: el, type: toFile ? "file" : "scope" };
249
+ if (typeof el === "string" && isUuidShape(el)) ref = { id: el, type: toFile ? "file" : "scope" };
250
250
  else if (el && typeof el === "object" && typeof el.id === "string") {
251
251
  const token = String(el.token ?? "");
252
252
  const own = el.label;