@tangle-network/agent-app 0.45.21 → 0.45.22

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 (110) hide show
  1. package/dist/DesignCanvas-ZG7DJS7C.js +10 -0
  2. package/dist/DesignCanvasEditor-SLFMHOII.js +13 -0
  3. package/dist/app-auth/index.js +2 -2
  4. package/dist/assistant/index.d.ts +1 -1
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/{attachment-validation-CsmUzuI3.d.ts → attachment-validation-BfJDBU1g.d.ts} +41 -5
  7. package/dist/{auth-DJjJBtYw.d.ts → auth-BYtiazA4.d.ts} +1 -1
  8. package/dist/chat-react/index.js +2 -2
  9. package/dist/chat-routes/index.d.ts +8 -4
  10. package/dist/chat-routes/index.js +21 -4
  11. package/dist/chat-routes/index.js.map +1 -1
  12. package/dist/{chunk-KPRBFNGT.js → chunk-3IHYJIDJ.js} +3 -3
  13. package/dist/{chunk-MYS7DHMM.js → chunk-4QVG4WJQ.js} +2 -2
  14. package/dist/{chunk-RMHZKMQ4.js → chunk-73CQJOIU.js} +5 -5
  15. package/dist/chunk-CCVG2TL6.js +327 -0
  16. package/dist/chunk-CCVG2TL6.js.map +1 -0
  17. package/dist/{chunk-U4BXAZCN.js → chunk-DRB77FYL.js} +2 -2
  18. package/dist/{chunk-6MUJROBT.js → chunk-E4DHYENH.js} +2 -2
  19. package/dist/chunk-F7VH4G5C.js +283 -0
  20. package/dist/chunk-F7VH4G5C.js.map +1 -0
  21. package/dist/chunk-I24YIKHO.js +183 -0
  22. package/dist/chunk-I24YIKHO.js.map +1 -0
  23. package/dist/{chunk-AH3IOSWF.js → chunk-NZVBJM73.js} +1432 -187
  24. package/dist/chunk-NZVBJM73.js.map +1 -0
  25. package/dist/{chunk-OO4DROKM.js → chunk-OASVAPRL.js} +3 -3
  26. package/dist/{chunk-ZSGTG6PK.js → chunk-P5PIAQVS.js} +2 -2
  27. package/dist/chunk-PC2WYTK7.js +405 -0
  28. package/dist/chunk-PC2WYTK7.js.map +1 -0
  29. package/dist/{chunk-YEFFHORB.js → chunk-TX6S7XXU.js} +8 -2
  30. package/dist/chunk-TX6S7XXU.js.map +1 -0
  31. package/dist/chunk-UGWQLQDS.js +35 -0
  32. package/dist/chunk-UGWQLQDS.js.map +1 -0
  33. package/dist/{chunk-O22STZ3P.js → chunk-X5DQ5QOP.js} +2 -2
  34. package/dist/{chunk-PCJHEZA7.js → chunk-YABHE2QY.js} +2 -2
  35. package/dist/design-canvas/index.d.ts +3 -3
  36. package/dist/design-canvas/index.js +2 -2
  37. package/dist/design-canvas-react/engine.js +4 -4
  38. package/dist/design-canvas-react/index.js +7 -7
  39. package/dist/design-canvas-react/lazy.js +1 -1
  40. package/dist/documents/index.d.ts +233 -0
  41. package/dist/documents/index.js +495 -0
  42. package/dist/documents/index.js.map +1 -0
  43. package/dist/documents/pdf-inspector.d.ts +60 -0
  44. package/dist/documents/pdf-inspector.js +100 -0
  45. package/dist/documents/pdf-inspector.js.map +1 -0
  46. package/dist/eval/index.d.ts +1 -1
  47. package/dist/fold-DACU7gtf.d.ts +320 -0
  48. package/dist/{mcp-BiKqnsJV.d.ts → mcp-xxoZZfor.d.ts} +2 -2
  49. package/dist/openui/index.d.ts +208 -0
  50. package/dist/openui/index.js +350 -0
  51. package/dist/openui/index.js.map +1 -0
  52. package/dist/openui-react/index.d.ts +119 -0
  53. package/dist/openui-react/index.js +149 -0
  54. package/dist/openui-react/index.js.map +1 -0
  55. package/dist/platform/index.js +2 -2
  56. package/dist/preset-cloudflare/index.d.ts +2 -2
  57. package/dist/rate-limit-BOVmJRXZ.d.ts +35 -0
  58. package/dist/record/drizzle.d.ts +682 -0
  59. package/dist/record/drizzle.js +579 -0
  60. package/dist/record/drizzle.js.map +1 -0
  61. package/dist/record/index.d.ts +16 -0
  62. package/dist/record/index.js +35 -0
  63. package/dist/record/index.js.map +1 -0
  64. package/dist/runtime/index.d.ts +3 -3
  65. package/dist/sandbox/index.d.ts +2 -2
  66. package/dist/sandbox/index.js +3 -2
  67. package/dist/sequences/index.d.ts +3 -3
  68. package/dist/sequences/index.js +1 -1
  69. package/dist/session-shell/index.d.ts +173 -1
  70. package/dist/session-shell/index.js +13 -1
  71. package/dist/teams/index.js +9 -9
  72. package/dist/teams/invitations-api.js +3 -3
  73. package/dist/tools/index.d.ts +5 -5
  74. package/dist/tools/index.js +3 -2
  75. package/dist/{types-DbU-oO5h.d.ts → types-B25Mib1r.d.ts} +11 -0
  76. package/dist/types-DrBidf3O.d.ts +123 -0
  77. package/dist/values-C7RidJuI.d.ts +156 -0
  78. package/dist/web/index.d.ts +197 -31
  79. package/dist/web/index.js +15 -3
  80. package/dist/web-react/async/index.d.ts +309 -0
  81. package/dist/web-react/async/index.js +327 -0
  82. package/dist/web-react/async/index.js.map +1 -0
  83. package/dist/web-react/index.d.ts +338 -2
  84. package/dist/web-react/index.js +52 -6
  85. package/dist/work-product/index.d.ts +1 -1
  86. package/dist/work-product/index.js +2 -1
  87. package/dist/work-product/index.js.map +1 -1
  88. package/dist/workspace-react/index.js +1 -1
  89. package/package.json +43 -3
  90. package/dist/DesignCanvas-NEIW3AER.js +0 -10
  91. package/dist/DesignCanvasEditor-QD33OI2W.js +0 -13
  92. package/dist/chunk-AH3IOSWF.js.map +0 -1
  93. package/dist/chunk-GINKOZFD.js +0 -214
  94. package/dist/chunk-GINKOZFD.js.map +0 -1
  95. package/dist/chunk-J25RST7G.js +0 -126
  96. package/dist/chunk-J25RST7G.js.map +0 -1
  97. package/dist/chunk-WBHPN5DY.js +0 -158
  98. package/dist/chunk-WBHPN5DY.js.map +0 -1
  99. package/dist/chunk-YEFFHORB.js.map +0 -1
  100. /package/dist/{DesignCanvas-NEIW3AER.js.map → DesignCanvas-ZG7DJS7C.js.map} +0 -0
  101. /package/dist/{DesignCanvasEditor-QD33OI2W.js.map → DesignCanvasEditor-SLFMHOII.js.map} +0 -0
  102. /package/dist/{chunk-KPRBFNGT.js.map → chunk-3IHYJIDJ.js.map} +0 -0
  103. /package/dist/{chunk-MYS7DHMM.js.map → chunk-4QVG4WJQ.js.map} +0 -0
  104. /package/dist/{chunk-RMHZKMQ4.js.map → chunk-73CQJOIU.js.map} +0 -0
  105. /package/dist/{chunk-U4BXAZCN.js.map → chunk-DRB77FYL.js.map} +0 -0
  106. /package/dist/{chunk-6MUJROBT.js.map → chunk-E4DHYENH.js.map} +0 -0
  107. /package/dist/{chunk-OO4DROKM.js.map → chunk-OASVAPRL.js.map} +0 -0
  108. /package/dist/{chunk-ZSGTG6PK.js.map → chunk-P5PIAQVS.js.map} +0 -0
  109. /package/dist/{chunk-O22STZ3P.js.map → chunk-X5DQ5QOP.js.map} +0 -0
  110. /package/dist/{chunk-PCJHEZA7.js.map → chunk-YABHE2QY.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/record/drizzle/schema.ts","../../src/record/drizzle/store.ts"],"sourcesContent":["/**\n * Drizzle table factory for a record-entry table. The product owns its\n * scope (workspace / tenant / account) table; this factory creates the entry\n * table and wires the foreign key into it, so the whole graph lives in one\n * drizzle schema with real cascade semantics.\n *\n * The table NAME is a parameter, so one product can host several independent\n * record tables (different domains, different schema maps) side by side.\n *\n * Three storage invariants are encoded here, and the store depends on all\n * three:\n *\n * 1. **Every key column is NOT NULL with a sentinel.** SQLite treats NULLs as\n * distinct inside a unique index, so a nullable `item_key` or `dimension`\n * would let two live heads coexist on one logical key and the partial\n * unique index below would silently stop enforcing anything. `''` and `0`\n * are the sentinels; see `RECORD_KEY_SENTINEL` / `RECORD_PERIOD_SENTINEL`.\n * 2. **The live head is unique per key.** The partial unique index covers only\n * rows that are `accepted` and not superseded, which is exactly the set the\n * materializer reads. Two writers racing for the same head make the second\n * one fail loudly instead of both landing.\n * 3. **Ordering is `seq`, never a timestamp.** `created_at` is epoch\n * milliseconds and is display-only. `(scope_id, seq)` is unique, so the\n * fold has a total order even for rows written in the same millisecond.\n *\n * `superseded_by_id` deliberately carries NO foreign key: the supersede batch\n * stamps the replacement's id onto the outgoing head BEFORE inserting the\n * replacement row, and SQLite cannot defer the constraint check to allow that\n * order. Rows are append-only and cascade with their scope, so the link cannot\n * dangle.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable, SQLiteColumnBuilderBase } from 'drizzle-orm/sqlite-core'\nimport type { RecordReviewState, RecordSourceLocator } from '../model'\n\n/** A product table referenced by foreign key — only its `id` column is used. */\nexport type RecordParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/**\n * Product columns added to the entry table, keyed by the property name the\n * store and the product read them under. Ordinary drizzle column builders, so\n * a product declares foreign keys, defaults and null-ability exactly as it\n * would in its own schema.\n */\nexport type RecordExtraColumns = Readonly<Record<string, SQLiteColumnBuilderBase>>\n\n/** Options for {@link createRecordTable}. */\nexport interface CreateRecordTableOptions {\n /**\n * SQL table name, chosen by the product. Also the default prefix for the\n * index names, so two record tables in one schema never collide.\n */\n tableName: string\n /**\n * The tenant table entries belong to. Rows cascade with it — deleting a\n * workspace deletes its record.\n */\n scopeTable: RecordParentTable\n /**\n * Optional table `source_ref` points at (a documents table, a source-record\n * table). Wire it ONLY when every source kind's ref points at this one\n * table; a product whose refs are heterogeneous (a document id for one kind,\n * a message id for another) leaves it off and keeps `source_ref` plain text.\n * When wired, deleting the source sets the ref null and leaves the entry\n * with its quote and locator intact.\n */\n sourceTable?: RecordParentTable\n /** Optional table `reviewed_by` points at (a users table). */\n reviewerTable?: RecordParentTable\n /** Index-name prefix. Defaults to {@link tableName}. */\n indexPrefix?: string\n /**\n * Product columns merged into the table, the `/missions` store-port pattern.\n *\n * The built-in `source_ref` is ONE column, which is right for a store whose\n * refs all point at one table and wrong for one whose kinds cite different\n * things — a chat-sourced row citing a message and a document-sourced row\n * citing a document each want their own foreign key with their own\n * `ON DELETE` behaviour. Declare them here, require them per source kind\n * through `policy.requireExtras`, and pass their values on `write`; the\n * store carries them and reads none of them.\n *\n * A key that collides with a built-in column is refused at construction —\n * silently shadowing `path` or `review_state` would break every invariant\n * the store rests on.\n */\n extraColumns?: RecordExtraColumns\n}\n\n/** Column property names the store owns. An extra column may not take one, and\n * neither may an `extras` value on a write — shadowing `path` or\n * `review_state` would break every invariant this table encodes. */\nexport const RECORD_STORE_COLUMNS: ReadonlySet<string> = new Set([\n 'id',\n 'scopeId',\n 'seq',\n 'dimension',\n 'period',\n 'path',\n 'itemKey',\n 'valueJson',\n 'affirmedEmpty',\n 'reviewState',\n 'conflict',\n 'supersededById',\n 'sourceKind',\n 'sourceRef',\n 'sourceLocator',\n 'sourceQuote',\n 'confidence',\n 'reviewedAt',\n 'reviewedBy',\n 'createdAt',\n])\n\n/** The base table, built with no spread of a type variable so drizzle infers\n * the exact row shape {@link RecordEntryRow} is derived from. */\nfunction buildRecordEntryTable(options: CreateRecordTableOptions) {\n const { tableName, scopeTable, sourceTable, reviewerTable } = options\n const prefix = options.indexPrefix ?? tableName\n const extraColumns = options.extraColumns ?? {}\n const collisions = Object.keys(extraColumns).filter((name) => RECORD_STORE_COLUMNS.has(name))\n if (collisions.length > 0) {\n throw new Error(\n `createRecordTable('${tableName}'): extraColumns may not redefine the store's own columns — ${collisions.sort().join(', ')}`,\n )\n }\n\n // The base columns are an ordinary object literal so drizzle infers the\n // exact table shape `RecordTable` is derived from; the product's columns are\n // attached through a widened reference, which adds them at RUNTIME (drizzle\n // reads the map, migrations emit them) without an index signature leaking\n // into the inferred row type and erasing every built-in column.\n const columns = {\n /** ULID minted by the store — an atomic supersede needs the replacement\n * id before the insert, so this has no column default. */\n id: text('id').primaryKey(),\n scopeId: text('scope_id')\n .notNull()\n .references(() => scopeTable.id, { onDelete: 'cascade' }),\n /** Per-scope monotonic write counter, assigned inside the insert\n * statement. The fold's only ordering key. */\n seq: integer('seq').notNull(),\n /** Consumer-defined partition inside the scope; `''` when unused. */\n dimension: text('dimension').notNull().default(''),\n /** The period the assertion became true in; `0` when the consumer has no\n * time dimension. */\n period: integer('period').notNull().default(0),\n /** The field this entry asserts. Validated against the consumer's schema\n * map on every write. */\n path: text('path').notNull(),\n /** Which element of a collection the path belongs to; `''` when not\n * applicable. */\n itemKey: text('item_key').notNull().default(''),\n /** Canonical JSON (sorted keys) of the validated value. */\n valueJson: text('value_json').notNull(),\n /** \"There are none of these\" — written against an affirmable path with\n * `item_key = ''` and `value_json = 'null'`. */\n affirmedEmpty: integer('affirmed_empty', { mode: 'boolean' }).notNull().default(false),\n reviewState: text('review_state').$type<RecordReviewState>().notNull(),\n /** Set when this entry disagreed with a live head from a different source\n * kind at write time — surfaced for a human to resolve. */\n conflict: integer('conflict', { mode: 'boolean' }).notNull().default(false),\n /** Audit link to the accepted entry that replaced this one; NULL marks a\n * live head. */\n supersededById: text('superseded_by_id'),\n /** Stamped by the server call site, never accepted from model output. */\n sourceKind: text('source_kind').notNull(),\n sourceRef: sourceTable\n ? text('source_ref').references(() => sourceTable.id, { onDelete: 'set null' })\n : text('source_ref'),\n /** JSON position inside the source. */\n sourceLocator: text('source_locator', { mode: 'json' }).$type<RecordSourceLocator>(),\n sourceQuote: text('source_quote'),\n confidence: real('confidence'),\n /** Epoch milliseconds. */\n reviewedAt: integer('reviewed_at'),\n reviewedBy: reviewerTable\n ? text('reviewed_by').references(() => reviewerTable.id, { onDelete: 'set null' })\n : text('reviewed_by'),\n /** Epoch milliseconds. Display only — `seq` orders the fold. */\n createdAt: integer('created_at')\n .notNull()\n .$defaultFn(() => Date.now()),\n }\n const widened: Record<string, SQLiteColumnBuilderBase> = columns\n for (const [name, column] of Object.entries(extraColumns)) widened[name] = column\n\n return sqliteTable(\n tableName,\n columns,\n (table) => [\n uniqueIndex(`${prefix}_scope_seq_uidx`).on(table.scopeId, table.seq),\n uniqueIndex(`${prefix}_live_head_uidx`)\n .on(table.scopeId, table.dimension, table.path, table.itemKey, table.period)\n .where(sql`review_state = 'accepted' AND superseded_by_id IS NULL`),\n index(`${prefix}_scope_period_idx`).on(table.scopeId, table.period),\n index(`${prefix}_scope_review_idx`).on(table.scopeId, table.reviewState),\n index(`${prefix}_scope_path_idx`).on(table.scopeId, table.path),\n ],\n )\n}\n\n/** The table shape {@link createRecordTable} produces. */\nexport type RecordTable = ReturnType<typeof buildRecordEntryTable>\n\n/** One stored entry, as selected. */\nexport type RecordEntryRow = RecordTable['$inferSelect']\n\n/** The record table plus the product's own columns, so a product's direct\n * queries name them and the store still sees the shape it depends on. */\nexport type RecordTableWithExtras<TExtra extends RecordExtraColumns> =\n RecordTable & { readonly [K in keyof TExtra]: AnySQLiteColumn }\n\n/**\n * Build one record-entry table wired to the product's tables.\n *\n * The returned table is an ordinary drizzle table: the product puts it in its\n * schema, generates migrations from it, and queries it directly for anything\n * the store does not cover. Declaring `extraColumns` names those columns on\n * the returned type as well.\n */\n// The `extraColumns` overload comes FIRST: overload resolution takes the\n// earliest match, and `extraColumns` is optional on the plain signature, so\n// the plain one would otherwise swallow every call and drop the product's\n// columns from the returned type.\nexport function createRecordTable<TExtra extends RecordExtraColumns>(\n options: CreateRecordTableOptions & { extraColumns: TExtra },\n): RecordTableWithExtras<TExtra>\nexport function createRecordTable(options: CreateRecordTableOptions): RecordTable\nexport function createRecordTable(options: CreateRecordTableOptions): RecordTable {\n return buildRecordEntryTable(options)\n}\n","/**\n * The write / review / list / materialize surface over a table from\n * {@link createRecordTable}. Policy is enforced HERE, at the write boundary,\n * never in callers.\n *\n * - `path` must be a key of the consumer's schema map, and the value must pass\n * that path's validator. Nothing the fold cannot type-check reaches storage.\n * - `reviewState` on write is a function of `sourceKind` alone, read from the\n * consumer's `reviewStateOnWrite` map. An undeclared source kind is refused.\n * - Conflict rule: a write whose key already holds a live accepted entry from a\n * DIFFERENT source kind with a materially different value does not supersede\n * — it lands `proposed` with `conflict = true` for a human to resolve.\n * - Accepting a proposal is the ONLY path from `proposed` to `accepted`, and it\n * clears the conflict flag — a human looked at the disagreement and chose.\n * Accepted entries change by supersession (a new write), never by re-review.\n *\n * ## The D1 rules this store is built around\n *\n * **`transaction()` does not work on D1.** Drizzle exposes it, and on the D1\n * driver it does not give you a transaction — `batch()` is the only atomic\n * primitive Cloudflare offers. So a supersede is one `db.batch([guard, main])`:\n * a guarded UPDATE that marks the outgoing head, and the INSERT (or the accept\n * UPDATE) that installs the new one. A driver with no `batch` (better-sqlite3)\n * gets an explicit `BEGIN IMMEDIATE` / `COMMIT` instead; a driver with neither\n * is refused with `unsupported-driver` rather than quietly running two\n * statements that can half-land.\n *\n * **Unique indexes do not dedupe NULLs in SQLite.** Every key column is NOT\n * NULL with a sentinel (see the schema factory), which is what makes the\n * partial unique index on the live head enforce anything at all.\n *\n * **Ordering never depends on a timestamp.** `created_at` is second- or\n * millisecond-resolution and two entries can share it; `seq` is assigned\n * inside the INSERT statement (SQLite executes a statement atomically, so\n * `MAX(seq) + 1` cannot race, and `(scope_id, seq)` unique backstops it).\n *\n * ## Losing the head race\n *\n * The guarded UPDATE matches the outgoing head by id AND by \"still accepted,\n * still live\". If a competing writer got there first, one of two things\n * happens, and both are safe:\n *\n * - the competitor installed its own live head, so this write's INSERT trips\n * the partial unique index and the WHOLE batch is rolled back — surfaced as\n * a unique violation and retried from a fresh read;\n * - or the batch committed with the guard matching zero rows, which the live\n * head index makes unreachable. That is an invariant breach, so it is\n * returned as `supersede-race` rather than retried: a retry would insert a\n * SECOND row for a write that already landed.\n *\n * ## Losing the REVIEW race\n *\n * The head race is only half of it. On the accept path the dependent statement\n * has a precondition of its own — the proposal must still be `proposed` — and\n * a second reviewer can reject it between this store's read and its write. A\n * `batch` driver cannot look at the first statement before running the second,\n * so the guard carries that precondition too (`markHeadStatement`'s\n * `requireProposedId`): either both statements match or neither does, and a\n * head can never be stamped superseded by an entry that was rejected. Both row\n * counts are then checked, and which one missed decides the answer — a\n * resolved proposal is `not-reviewable`, a moved head is a retry.\n *\n * Every method returns a typed outcome; callers inspect `succeeded` before\n * touching `value`.\n */\n\nimport { and, asc, eq, getTableColumns, getTableName, isNull, lte, sql } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n canonicalRecordJson,\n detectRecordConflict,\n recordFail,\n recordOk,\n resolveWriteReviewState,\n validateRecordValue,\n RECORD_KEY_SENTINEL,\n RECORD_PERIOD_SENTINEL,\n type RecordOutcome,\n type RecordReviewState,\n type RecordSourceLocator,\n type RecordWritePolicy,\n} from '../model'\nimport {\n defaultRecordPeriodScope,\n foldRecordEntries,\n recordEntryVisibleInPeriod,\n type FoldableRecordEntry,\n type RecordFoldRules,\n type RecordPeriodScopeResolver,\n} from '../fold'\nimport { recordUlid } from '../ulid'\nimport { RECORD_STORE_COLUMNS } from './schema'\nimport type { RecordEntryRow, RecordTable } from './schema'\n\n/**\n * Any SQLite drizzle database. The run-result and schema generics are erased\n * to `unknown` so better-sqlite3, D1 and libsql handles all fit; `batch` is\n * declared optional because only D1 and libsql expose it.\n */\nexport type RecordDatabase = BaseSQLiteDatabase<'sync' | 'async', unknown, Record<string, unknown>> & {\n batch?(statements: [unknown, ...unknown[]]): Promise<unknown[]>\n}\n\n/** How this store executes a two-statement atomic unit on the caller's driver. */\nexport type RecordAtomicStrategy = 'batch' | 'begin-immediate'\n\n/** Input to {@link RecordStore.write}. */\nexport interface WriteRecordEntryInput {\n scopeId: string\n /** Must be a key of the policy's schema map, or — when `affirmedEmpty` — one\n * of its affirmable paths. */\n path: string\n /** Defaults to {@link RECORD_PERIOD_SENTINEL}. */\n period?: number\n /** Defaults to {@link RECORD_KEY_SENTINEL}; canonicalized by the policy. */\n dimension?: string\n /** Defaults to {@link RECORD_KEY_SENTINEL}; canonicalized by the policy. */\n itemKey?: string\n /** The value. Must be absent when `affirmedEmpty` is true. */\n value?: unknown\n /** Assert \"there are none of these\" at `path`. */\n affirmedEmpty?: boolean\n /** Stamped by the SERVER call site — never read from model arguments. */\n sourceKind: string\n sourceRef?: string | null\n sourceLocator?: RecordSourceLocator | null\n sourceQuote?: string | null\n confidence?: number | null\n /**\n * Values for the product columns declared through the table factory's\n * `extraColumns`. Carried onto the INSERT verbatim — the store reads none of\n * them and knows none of their names. `policy.requireExtras` is where a\n * product says which ones a given source kind must supply.\n *\n * A key with no matching column is refused rather than dropped: a citation\n * that silently did not store its source id is the failure this store exists\n * to make impossible.\n */\n extras?: Readonly<Record<string, unknown>>\n}\n\n/** What a write produced. */\nexport interface WriteRecordEntryResult {\n entry: RecordEntryRow\n /** True when the write landed `proposed` with the conflict flag set. */\n conflict: boolean\n /** Id of the live head this write superseded, when it superseded one. */\n supersededEntryId: string | null\n}\n\n/** Input to {@link RecordStore.review}. */\nexport interface ReviewRecordEntryInput {\n scopeId: string\n entryId: string\n action: 'accept' | 'reject'\n /** Recorded on the row; the store never derives it. */\n reviewedBy?: string | null\n}\n\n/** Filters for {@link RecordStore.list}. */\nexport interface ListRecordEntriesInput {\n scopeId: string\n /** Narrow to one review state. Does not resurrect superseded entries. */\n reviewState?: RecordReviewState\n /** Resolve visibility against this period. Omit to return every period. */\n period?: number\n /** Include entries a later accepted entry replaced. Default false. */\n includeSuperseded?: boolean\n /** Include rejected entries. Default false, unless `reviewState` asks for\n * them explicitly. */\n includeRejected?: boolean\n}\n\n/** Input to {@link RecordStore.heads}. */\nexport interface ReadRecordHeadsInput {\n scopeId: string\n /**\n * The period to resolve against. Defaults to {@link RECORD_PERIOD_SENTINEL},\n * which is the right default ONLY for a consumer with no time dimension —\n * every entry it writes sits at `0`. A consumer that uses periods passes one\n * on every read; omitting it there resolves against period `0` and returns\n * nothing, rather than quietly mixing periods together.\n */\n period?: number\n}\n\n/** Input to {@link RecordStore.materialize}. */\nexport interface MaterializeRecordInput<T> {\n scopeId: string\n /** The consumer's grouping rules. */\n rules: RecordFoldRules<T>\n /** Same default and same caveat as {@link ReadRecordHeadsInput.period}. */\n period?: number\n}\n\n/** What a materialization produced. */\nexport interface MaterializeRecordResult<T> {\n value: T\n /** Live accepted entries folded in. */\n entryCount: number\n /** Proposed entries visible at this period and still awaiting review. */\n pendingProposed: number\n /** Subset of those flagged by the conflict rule. */\n conflicts: number\n}\n\n/** Options for {@link createRecordStore}. */\nexport interface CreateRecordStoreOptions {\n db: RecordDatabase\n /** The table from `createRecordTable`. */\n table: RecordTable\n /** Everything domain-specific about a write. */\n policy: RecordWritePolicy\n /**\n * Period scope per path, used by `list`'s period filter and as the default\n * for `materialize` when the fold rules omit their own. Defaults to `'exact'`\n * for every path.\n */\n periodScope?: RecordPeriodScopeResolver\n /** Id minter. Defaults to a ULID. */\n newId?: () => string\n /** Clock for `reviewedAt`. Defaults to `Date.now`. */\n now?: () => number\n /** Attempts before a contended head write gives up. Defaults to 3. */\n maxWriteAttempts?: number\n}\n\n/** The store surface. */\nexport interface RecordStore {\n /** Which atomic primitive this store resolved for the injected driver. */\n readonly atomicStrategy: RecordAtomicStrategy\n /** Append one entry, superseding the live head when the write is accepted. */\n write(input: WriteRecordEntryInput): Promise<RecordOutcome<WriteRecordEntryResult>>\n /** Accept or reject a proposed entry. */\n review(input: ReviewRecordEntryInput): Promise<RecordOutcome<RecordEntryRow>>\n /** Entries visible under the filters, ordered by `seq`. */\n list(input: ListRecordEntriesInput): Promise<RecordOutcome<RecordEntryRow[]>>\n /** Live accepted heads visible at `period`, ordered by `seq`. Visibility is\n * the store's period scope, the same rule `list` applies — an `exact`-scoped\n * entry from an earlier period is not a head at a later one. */\n heads(input: ReadRecordHeadsInput): Promise<RecordOutcome<RecordEntryRow[]>>\n /** Fold the live heads into the consumer's shape. */\n materialize<T>(input: MaterializeRecordInput<T>): Promise<RecordOutcome<MaterializeRecordResult<T>>>\n}\n\nconst DEFAULT_WRITE_ATTEMPTS = 3\n\n/**\n * Build a store bound to one table and one policy. `scopeId` is per call, not\n * per store, so one instance serves every tenant a worker handles — and every\n * query pins it in the WHERE clause, so a leaked id from another scope reads\n * and writes nothing.\n */\nexport function createRecordStore(options: CreateRecordStoreOptions): RecordStore {\n const { db, table, policy } = options\n const tableName = getTableName(table)\n const newId = options.newId ?? (() => recordUlid())\n const now = options.now ?? (() => Date.now())\n const attempts = options.maxWriteAttempts ?? DEFAULT_WRITE_ATTEMPTS\n const storePeriodScope = options.periodScope ?? defaultRecordPeriodScope\n const strategy = resolveAtomicStrategy(db)\n const affirmable = new Set(policy.affirmablePaths ?? [])\n const requireRef = new Set(policy.requireSourceRef ?? [])\n const requireQuote = new Set(policy.requireSourceQuote ?? [])\n // The PRODUCT's column keys — every column on the table minus the ones this\n // store owns. An `extras` key outside this set is a refusal: with no column\n // it would be a value drizzle drops on the floor, and with a store-owned\n // column it would shadow the row's own identity.\n const extraColumnNames = new Set(\n Object.keys(getTableColumns(table)).filter((name) => !RECORD_STORE_COLUMNS.has(name)),\n )\n\n function liveHeadWhere(scopeId: string, key: ValidatedKey) {\n return and(\n eq(table.scopeId, scopeId),\n eq(table.dimension, key.dimension),\n eq(table.path, key.path),\n eq(table.itemKey, key.itemKey),\n eq(table.period, key.period),\n eq(table.reviewState, 'accepted'),\n isNull(table.supersededById),\n )\n }\n\n async function loadLiveHead(scopeId: string, key: ValidatedKey): Promise<RecordEntryRow | undefined> {\n const rows = await db.select().from(table).where(liveHeadWhere(scopeId, key)).limit(1)\n return rows[0]\n }\n\n /**\n * The guarded UPDATE that marks an outgoing head superseded.\n *\n * `requireProposedId` folds the DEPENDENT statement's own precondition into\n * this one. On a `batch` driver the pair commits unconditionally and nothing\n * can inspect the first statement before the second runs, so the two must be\n * unable to disagree. Without it, a proposal a concurrent reviewer rejected\n * still gets its id stamped onto the head as `superseded_by_id` while the\n * accept UPDATE matches nothing — the record left with NO live head while the\n * caller is told the review did not happen.\n */\n function markHeadStatement(headId: string, replacementId: string, requireProposedId?: string) {\n const guards = [eq(table.id, headId), eq(table.reviewState, 'accepted'), isNull(table.supersededById)]\n if (requireProposedId !== undefined) {\n guards.push(\n sql`EXISTS (SELECT 1 FROM ${sql.identifier(tableName)} WHERE id = ${requireProposedId} AND review_state = 'proposed')`,\n )\n }\n return db\n .update(table)\n .set({ supersededById: replacementId })\n .where(and(...guards))\n .returning({ id: table.id })\n }\n\n /** Re-read one entry by id inside its scope. Used to name WHICH precondition\n * a guarded pair failed on, which decides retry versus refusal. */\n async function loadEntry(scopeId: string, entryId: string): Promise<RecordEntryRow | undefined> {\n const rows = await db\n .select()\n .from(table)\n .where(and(eq(table.id, entryId), eq(table.scopeId, scopeId)))\n .limit(1)\n return rows[0]\n }\n\n async function write(input: WriteRecordEntryInput): Promise<RecordOutcome<WriteRecordEntryResult>> {\n const validated = validateWrite(input)\n if (!validated.succeeded) return validated\n const draft = validated.value\n\n let lastError = ''\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n const head = await loadLiveHead(input.scopeId, draft.key)\n const conflict = detectRecordConflict(policy, head, draft)\n const reviewState: RecordReviewState = conflict ? 'proposed' : draft.reviewState\n\n const id = newId()\n const values = insertValues(input, draft, id, reviewState, conflict)\n\n if (reviewState === 'accepted' && head !== undefined) {\n const paired = await runGuardedPair(\n db,\n strategy,\n markHeadStatement(head.id, id),\n db.insert(table).values(values).returning(),\n )\n if (!paired.guardMatched) {\n if (paired.rolledBack) {\n lastError = `write: lost the head race on '${draft.key.path}' (head ${head.id} changed underneath)`\n continue\n }\n return recordFail(\n 'supersede-race',\n `write: head ${head.id} on '${draft.key.path}' was not markable but the write committed — the live-head index is not enforcing`,\n )\n }\n // An INSERT has no precondition to miss, so an empty main here is a\n // driver defect rather than a lost race — and `runGuardedPair` has\n // already rolled the pair back where the driver allows it, so the\n // head is not left marked against a row that was never written.\n const row = firstRow(paired.mainRows)\n if (!row) return recordFail('storage-failed', 'write: insert returned no row')\n return recordOk({ entry: row, conflict: false, supersededEntryId: head.id })\n }\n\n const inserted = await db.insert(table).values(values).returning()\n const row = firstRow(inserted)\n if (!row) return recordFail('storage-failed', 'write: insert returned no row')\n return recordOk({ entry: row, conflict, supersededEntryId: null })\n } catch (error) {\n if (isUniqueViolation(error)) {\n lastError = `write: concurrent head write on '${draft.key.path}' — ${errorMessage(error)}`\n continue\n }\n return recordFail('storage-failed', `write: ${errorMessage(error)}`)\n }\n }\n return recordFail('supersede-race', `${lastError} (gave up after ${attempts} attempts)`)\n }\n\n async function review(input: ReviewRecordEntryInput): Promise<RecordOutcome<RecordEntryRow>> {\n let existing: RecordEntryRow | undefined\n try {\n const rows = await db\n .select()\n .from(table)\n .where(and(eq(table.id, input.entryId), eq(table.scopeId, input.scopeId)))\n .limit(1)\n existing = rows[0]\n } catch (error) {\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n if (!existing) {\n return recordFail('not-found', `review: entry '${input.entryId}' not found in scope '${input.scopeId}'`)\n }\n if (existing.reviewState !== 'proposed') {\n return recordFail(\n 'not-reviewable',\n `review: entry '${input.entryId}' is '${existing.reviewState}' — only proposed entries are reviewable`,\n )\n }\n\n const reviewedAt = now()\n const reviewedBy = input.reviewedBy ?? null\n\n if (input.action === 'reject') {\n try {\n const updated = await db\n .update(table)\n .set({ reviewState: 'rejected', reviewedAt, reviewedBy })\n .where(and(eq(table.id, existing.id), eq(table.reviewState, 'proposed')))\n .returning()\n const row = firstRow(updated)\n if (!row) {\n return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n }\n return recordOk(row)\n } catch (error) {\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n }\n\n const key: ValidatedKey = {\n dimension: existing.dimension,\n path: existing.path,\n itemKey: existing.itemKey,\n period: existing.period,\n }\n\n let lastError = ''\n for (let attempt = 0; attempt < attempts; attempt++) {\n try {\n const head = await loadLiveHead(input.scopeId, key)\n const acceptStatement = db\n .update(table)\n .set({ reviewState: 'accepted', conflict: false, reviewedAt, reviewedBy })\n .where(and(eq(table.id, existing.id), eq(table.reviewState, 'proposed')))\n .returning()\n\n if (head !== undefined) {\n const paired = await runGuardedPair(\n db,\n strategy,\n markHeadStatement(head.id, existing.id, existing.id),\n acceptStatement,\n )\n if (!paired.guardMatched && paired.mainMatched) {\n return recordFail(\n 'supersede-race',\n `review: head ${head.id} was not markable but the accept committed — the live-head index is not enforcing`,\n )\n }\n if (paired.guardMatched && !paired.mainMatched && !paired.rolledBack) {\n // The head is stamped superseded by an entry the accept did not\n // install. Nothing can be retried past this: the record's live\n // value is gone and only an operator can put it back.\n return recordFail(\n 'supersede-race',\n `review: head ${head.id} was marked superseded by '${input.entryId}' but the accept matched no row — the batch is not atomic`,\n )\n }\n if (!paired.guardMatched || !paired.mainMatched) {\n // Nothing landed. Which precondition failed decides the answer: a\n // proposal a concurrent reviewer already resolved is a refusal, a\n // head that moved underneath is a retry.\n const current = await loadEntry(input.scopeId, existing.id)\n if (current === undefined || current.reviewState !== 'proposed') {\n return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n }\n lastError = `review: lost the head race accepting '${input.entryId}' (head ${head.id} changed underneath)`\n continue\n }\n const row = firstRow(paired.mainRows)\n if (!row) return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n return recordOk(row)\n }\n\n const accepted = await acceptStatement\n const row = firstRow(accepted)\n if (!row) return recordFail('not-reviewable', `review: entry '${input.entryId}' was reviewed concurrently`)\n return recordOk(row)\n } catch (error) {\n if (isUniqueViolation(error)) {\n lastError = `review: concurrent head write accepting '${input.entryId}' — ${errorMessage(error)}`\n continue\n }\n return recordFail('storage-failed', `review: ${errorMessage(error)}`)\n }\n }\n return recordFail('supersede-race', `${lastError} (gave up after ${attempts} attempts)`)\n }\n\n async function list(input: ListRecordEntriesInput): Promise<RecordOutcome<RecordEntryRow[]>> {\n if (input.period !== undefined && !Number.isInteger(input.period)) {\n return recordFail('invalid-input', `list: period must be an integer, got ${String(input.period)}`)\n }\n try {\n const where = input.period === undefined\n ? eq(table.scopeId, input.scopeId)\n : and(eq(table.scopeId, input.scopeId), lte(table.period, input.period))\n const rows = await db.select().from(table).where(where).orderBy(asc(table.seq))\n\n const visible = rows.filter((row) => {\n if (input.period !== undefined\n && !recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, input.period)) return false\n if (input.reviewState !== undefined) {\n if (row.reviewState !== input.reviewState) return false\n } else if (!input.includeRejected && row.reviewState === 'rejected') {\n return false\n }\n if (!input.includeSuperseded && row.supersededById !== null) return false\n return true\n })\n return recordOk(visible)\n } catch (error) {\n return recordFail('storage-failed', `list: ${errorMessage(error)}`)\n }\n }\n\n /**\n * The raw live-accepted query. `period <= N` is the only predicate SQL can\n * express — whether an entry written at an earlier period is still TRUE at\n * `N` is the period scope's call, and that resolver is per path, so it runs\n * in JS over these rows.\n */\n async function loadHeads(scopeId: string, period: number): Promise<RecordEntryRow[]> {\n return db\n .select()\n .from(table)\n .where(and(\n eq(table.scopeId, scopeId),\n eq(table.reviewState, 'accepted'),\n isNull(table.supersededById),\n lte(table.period, period),\n ))\n .orderBy(asc(table.seq))\n }\n\n async function heads(input: ReadRecordHeadsInput): Promise<RecordOutcome<RecordEntryRow[]>> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n if (!Number.isInteger(period)) {\n return recordFail('invalid-input', `heads: period must be an integer, got ${String(period)}`)\n }\n try {\n const rows = await loadHeads(input.scopeId, period)\n // The same visibility rule `list` applies. Without it an `exact`-scoped\n // entry written at an earlier period reads as live at a later one, and\n // the two published reads answer the same question differently.\n return recordOk(rows.filter((row) => recordEntryVisibleInPeriod(storePeriodScope(row.path), row.period, period)))\n } catch (error) {\n return recordFail('storage-failed', `heads: ${errorMessage(error)}`)\n }\n }\n\n async function materialize<T>(input: MaterializeRecordInput<T>): Promise<RecordOutcome<MaterializeRecordResult<T>>> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n if (!Number.isInteger(period)) {\n return recordFail('invalid-input', `materialize: period must be an integer, got ${String(period)}`)\n }\n // Deliberately the RAW rows, not `heads()`: the fold applies the caller's\n // own `rules.periodScope` when it supplies one, so pre-filtering here with\n // the store's resolver would drop entries those rules would have kept.\n let loaded: RecordEntryRow[]\n try {\n loaded = await loadHeads(input.scopeId, period)\n } catch (error) {\n return recordFail('storage-failed', `materialize: ${errorMessage(error)}`)\n }\n\n const rules: RecordFoldRules<T> = input.rules.periodScope\n ? input.rules\n : { ...input.rules, periodScope: storePeriodScope }\n const folded = foldRecordEntries(loaded.map(toFoldable), { rules, period })\n if (!folded.succeeded) return folded\n\n const periodScope = rules.periodScope ?? storePeriodScope\n try {\n const proposed = await db\n .select({ path: table.path, period: table.period, conflict: table.conflict })\n .from(table)\n .where(and(\n eq(table.scopeId, input.scopeId),\n eq(table.reviewState, 'proposed'),\n lte(table.period, period),\n ))\n const visible = proposed.filter((row) => recordEntryVisibleInPeriod(periodScope(row.path), row.period, period))\n return recordOk({\n value: folded.value.value,\n entryCount: folded.value.entryCount,\n pendingProposed: visible.length,\n conflicts: visible.filter((row) => row.conflict).length,\n })\n } catch (error) {\n return recordFail('storage-failed', `materialize: ${errorMessage(error)}`)\n }\n }\n\n interface ValidatedKey {\n dimension: string\n path: string\n itemKey: string\n period: number\n }\n\n interface ValidatedWrite {\n key: ValidatedKey\n valueJson: string\n affirmedEmpty: boolean\n reviewState: RecordReviewState\n sourceKind: string\n }\n\n function validateWrite(input: WriteRecordEntryInput): RecordOutcome<ValidatedWrite> {\n const period = input.period ?? RECORD_PERIOD_SENTINEL\n const minPeriod = policy.minPeriod ?? RECORD_PERIOD_SENTINEL\n const maxPeriod = policy.maxPeriod ?? Number.MAX_SAFE_INTEGER\n if (!Number.isInteger(period) || period < minPeriod || period > maxPeriod) {\n return recordFail(\n 'invalid-input',\n `write: period must be an integer in [${minPeriod}, ${maxPeriod}], got ${String(period)}`,\n )\n }\n if (requireRef.has(input.sourceKind) && !input.sourceRef) {\n return recordFail('invalid-input', `write: source kind '${input.sourceKind}' requires a sourceRef ('${input.path}')`)\n }\n if (requireQuote.has(input.sourceKind) && !input.sourceQuote) {\n return recordFail('invalid-input', `write: source kind '${input.sourceKind}' requires a sourceQuote ('${input.path}')`)\n }\n const extras = input.extras ?? {}\n for (const key of Object.keys(extras)) {\n if (!extraColumnNames.has(key)) {\n return recordFail(\n 'invalid-input',\n `write: extras key '${key}' has no column on '${tableName}' — declare it in createRecordTable's extraColumns`,\n )\n }\n }\n for (const key of policy.requireExtras?.[input.sourceKind] ?? []) {\n const held = extras[key]\n if (held === undefined || held === null || held === '') {\n return recordFail(\n 'invalid-input',\n `write: source kind '${input.sourceKind}' requires extras.${key} ('${input.path}')`,\n )\n }\n }\n if (input.confidence !== undefined && input.confidence !== null\n && (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1)) {\n return recordFail('invalid-input', `write: confidence must be in [0, 1], got ${String(input.confidence)}`)\n }\n\n const state = resolveWriteReviewState(policy, input.sourceKind)\n if (!state.succeeded) return state\n\n const dimension = canonicalize(policy.canonicalizeDimension, input.path, input.dimension ?? RECORD_KEY_SENTINEL, 'dimension')\n if (!dimension.succeeded) return dimension\n\n if (input.affirmedEmpty === true) {\n if (input.value !== undefined) {\n return recordFail('invalid-input', `write: an affirmedEmpty entry must not carry a value ('${input.path}')`)\n }\n if (!affirmable.has(input.path)) {\n return recordFail(\n 'unknown-path',\n `write: '${input.path}' is not an affirmable path — affirmedEmpty targets a path declared in policy.affirmablePaths`,\n )\n }\n if ((input.itemKey ?? RECORD_KEY_SENTINEL) !== RECORD_KEY_SENTINEL) {\n return recordFail(\n 'invalid-input',\n `write: an affirmedEmpty entry uses the itemKey sentinel — it asserts that a whole path is empty ('${input.path}')`,\n )\n }\n return recordOk({\n key: { dimension: dimension.value, path: input.path, itemKey: RECORD_KEY_SENTINEL, period },\n valueJson: 'null',\n affirmedEmpty: true,\n reviewState: state.value,\n sourceKind: input.sourceKind,\n })\n }\n\n const validator = policy.schemas[input.path]\n if (validator === undefined) {\n return recordFail('unknown-path', `write: unknown path '${input.path}' — not a key of the policy's schema map`)\n }\n if (input.value === undefined) {\n return recordFail('invalid-input', `write: a value is required unless affirmedEmpty is true ('${input.path}')`)\n }\n const parsed = validateRecordValue(validator, input.value)\n if (!parsed.succeeded) {\n return recordFail('invalid-value', `write: value for '${input.path}' failed validation — ${parsed.error}`)\n }\n\n const itemKey = canonicalize(policy.canonicalizeItemKey, input.path, input.itemKey ?? RECORD_KEY_SENTINEL, 'itemKey')\n if (!itemKey.succeeded) return itemKey\n\n return recordOk({\n key: { dimension: dimension.value, path: input.path, itemKey: itemKey.value, period },\n valueJson: canonicalRecordJson(parsed.value),\n affirmedEmpty: false,\n reviewState: state.value,\n sourceKind: input.sourceKind,\n })\n }\n\n function insertValues(\n input: WriteRecordEntryInput,\n draft: ValidatedWrite,\n id: string,\n reviewState: RecordReviewState,\n conflict: boolean,\n ) {\n return {\n // First, so a product column can never shadow a store-owned one even if\n // the guards above were bypassed.\n ...(input.extras ?? {}),\n id,\n scopeId: input.scopeId,\n // Assigned inside the statement: SQLite executes one statement\n // atomically, so MAX + 1 cannot race, and `(scope_id, seq)` unique\n // backstops it.\n seq: sql<number>`(SELECT COALESCE(MAX(seq), 0) + 1 FROM ${sql.identifier(tableName)} WHERE scope_id = ${input.scopeId})`,\n dimension: draft.key.dimension,\n period: draft.key.period,\n path: draft.key.path,\n itemKey: draft.key.itemKey,\n valueJson: draft.valueJson,\n affirmedEmpty: draft.affirmedEmpty,\n reviewState,\n conflict,\n supersededById: null,\n sourceKind: input.sourceKind,\n sourceRef: input.sourceRef ?? null,\n sourceLocator: input.sourceLocator ?? null,\n sourceQuote: input.sourceQuote ?? null,\n confidence: input.confidence ?? null,\n // A write that lands accepted by policy was not REVIEWED — nobody looked\n // at it. `createdAt` records when it landed; these two stay null until an\n // actual accept/reject.\n reviewedAt: null,\n reviewedBy: null,\n }\n }\n\n return { atomicStrategy: strategy, write, review, list, heads, materialize }\n}\n\n/** Project a stored row onto the slice the pure fold reads. */\nexport function toFoldable(row: RecordEntryRow): FoldableRecordEntry {\n return {\n id: row.id,\n seq: row.seq,\n dimension: row.dimension,\n period: row.period,\n path: row.path,\n itemKey: row.itemKey,\n valueJson: row.valueJson,\n affirmedEmpty: row.affirmedEmpty,\n }\n}\n\nfunction canonicalize(\n canonicalizer: ((path: string, raw: string) => RecordOutcome<string>) | undefined,\n path: string,\n raw: string,\n column: string,\n): RecordOutcome<string> {\n if (!canonicalizer) return recordOk(raw)\n const result = canonicalizer(path, raw)\n if (!result.succeeded) return recordFail('invalid-input', `write: '${path}' ${column} — ${result.error}`)\n return result\n}\n\nfunction firstRow(rows: unknown): RecordEntryRow | undefined {\n return Array.isArray(rows) ? (rows[0] as RecordEntryRow | undefined) : undefined\n}\n\n/**\n * Pick the driver's atomic primitive. `batch` first and unconditionally: on D1\n * it is the ONLY one that works, and a D1 handle also exposes a `transaction`\n * method that does not give you a transaction.\n */\nexport function resolveAtomicStrategy(db: RecordDatabase): RecordAtomicStrategy {\n if (typeof db.batch === 'function') return 'batch'\n if (typeof db.run === 'function') return 'begin-immediate'\n throw new Error(\n 'createRecordStore: the injected driver exposes neither batch() nor run() — an atomic supersede is impossible on it',\n )\n}\n\ninterface GuardedPairResult {\n /** True when the guarded statement matched exactly one row. */\n guardMatched: boolean\n /** True when the dependent statement matched at least one row. */\n mainMatched: boolean\n /** True when a failed precondition left NOTHING written. */\n rolledBack: boolean\n /** Rows the second statement returned. */\n mainRows: unknown[]\n}\n\n/**\n * Run a guarded statement and its dependent statement as one atomic unit.\n *\n * BOTH statements' row counts are reported, and both matter. With only the\n * guard's checked, the destructive half of a supersede can commit alone — the\n * outgoing head stamped `superseded_by_id` while the dependent accept matches\n * zero rows, leaving the record with no live head at all.\n *\n * `batch` (D1, libsql) commits both or neither and cannot inspect the first\n * statement before the second runs — the guard has to carry the dependent\n * statement's precondition itself (see `markHeadStatement`), and the row counts\n * read afterwards say which precondition failed. `begin-immediate`\n * (better-sqlite3 and any driver without `batch`) can do better: it inspects\n * each statement as it runs and rolls back on either mismatch, so the caller\n * retries from a fresh read with nothing written.\n */\nasync function runGuardedPair(\n db: RecordDatabase,\n strategy: RecordAtomicStrategy,\n guard: unknown,\n main: unknown,\n): Promise<GuardedPairResult> {\n if (strategy === 'batch') {\n const batch = db.batch\n if (typeof batch !== 'function') {\n throw new Error('runGuardedPair: batch strategy resolved but the driver has no batch()')\n }\n const results = await batch.call(db, [guard, main] as [unknown, ...unknown[]])\n const guardRows = results[0]\n const mainRows = Array.isArray(results[1]) ? results[1] : []\n return {\n guardMatched: Array.isArray(guardRows) && guardRows.length === 1,\n mainMatched: mainRows.length > 0,\n rolledBack: false,\n mainRows,\n }\n }\n\n await db.run(sql`begin immediate`)\n try {\n const guardRows = await (guard as Promise<unknown>)\n if (!Array.isArray(guardRows) || guardRows.length !== 1) {\n await db.run(sql`rollback`)\n return { guardMatched: false, mainMatched: false, rolledBack: true, mainRows: [] }\n }\n const mainRows = await (main as Promise<unknown>)\n if (!Array.isArray(mainRows) || mainRows.length === 0) {\n await db.run(sql`rollback`)\n return { guardMatched: true, mainMatched: false, rolledBack: true, mainRows: [] }\n }\n await db.run(sql`commit`)\n return { guardMatched: true, mainMatched: true, rolledBack: false, mainRows }\n } catch (error) {\n await rollbackQuietly(db)\n throw error\n }\n}\n\n/** Roll back without masking the error that caused it. */\nasync function rollbackQuietly(db: RecordDatabase): Promise<void> {\n try {\n await db.run(sql`rollback`)\n } catch {\n // The transaction is already gone; the original error is the one to report.\n }\n}\n\n/** Flatten a driver error's cause chain into one readable message. */\nfunction errorMessage(error: unknown): string {\n const parts: string[] = []\n let cursor: unknown = error\n for (let depth = 0; depth < 5 && cursor instanceof Error; depth++) {\n parts.push(cursor.message)\n cursor = cursor.cause\n }\n return parts.length > 0 ? parts.join(' — ') : String(error)\n}\n\n/** Drizzle wraps driver errors (\"Failed query: …\") and keeps the SQLite error\n * in the cause chain, so the whole chain is inspected. */\nfunction isUniqueViolation(error: unknown): boolean {\n let cursor: unknown = error\n for (let depth = 0; depth < 5 && cursor instanceof Error; depth++) {\n if (cursor.message.includes('UNIQUE constraint failed')) return true\n cursor = cursor.cause\n }\n return false\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,M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EAC9E,SAAS,OAAO;AACd,UAAM,gBAAgB,EAAE;AACxB,UAAM;AAAA,EACR;AACF;AAGA,eAAe,gBAAgB,IAAmC;AAChE,MAAI;AACF,UAAM,GAAG,IAAIA,cAAa;AAAA,EAC5B,QAAQ;AAAA,EAER;AACF;AAGA,SAAS,aAAa,OAAwB;AAC5C,QAAM,QAAkB,CAAC;AACzB,MAAI,SAAkB;AACtB,WAAS,QAAQ,GAAG,QAAQ,KAAK,kBAAkB,OAAO,SAAS;AACjE,UAAM,KAAK,OAAO,OAAO;AACzB,aAAS,OAAO;AAAA,EAClB;AACA,SAAO,MAAM,SAAS,IAAI,MAAM,KAAK,UAAK,IAAI,OAAO,KAAK;AAC5D;AAIA,SAAS,kBAAkB,OAAyB;AAClD,MAAI,SAAkB;AACtB,WAAS,QAAQ,GAAG,QAAQ,KAAK,kBAAkB,OAAO,SAAS;AACjE,QAAI,OAAO,QAAQ,SAAS,0BAA0B,EAAG,QAAO;AAChE,aAAS,OAAO;AAAA,EAClB;AACA,SAAO;AACT;","names":["sql","sql","row"]}
@@ -0,0 +1,16 @@
1
+ export { D as DecodedRecordEntry, F as FoldRecordEntriesOptions, a as FoldableRecordEntry, R as RECORD_KEY_SENTINEL, b as RECORD_PERIOD_SENTINEL, c as RECORD_REVIEW_STATES, d as RecordEntryKey, e as RecordErrorCode, f as RecordFoldResult, g as RecordFoldRules, h as RecordKeyCanonicalizer, i as RecordMaterialDifference, j as RecordOutcome, k as RecordParseResult, l as RecordPeriodScope, m as RecordPeriodScopeResolver, n as RecordReviewState, o as RecordSchemaMap, p as RecordSourceLocator, q as RecordValueValidator, r as RecordWritePolicy, s as canonicalRecordJson, t as defaultRecordMaterialDifference, u as defaultRecordPeriodScope, v as detectRecordConflict, w as foldRecordEntries, x as recordEntryVisibleInPeriod, y as recordFail, z as recordKeyString, A as recordOk, B as resolveWriteReviewState, C as validateRecordValue } from '../fold-DACU7gtf.js';
2
+
3
+ /**
4
+ * ULID — a 26-character Crockford-base32 id: a 48-bit millisecond timestamp
5
+ * followed by 80 bits from `crypto.getRandomValues`.
6
+ *
7
+ * The record store mints ids in application code rather than taking a column
8
+ * default, because an atomic supersede stamps the REPLACEMENT's id onto the
9
+ * outgoing head in the same write — the id has to exist before the insert.
10
+ * Lexicographic order approximates creation order, which keeps a raw table
11
+ * scan readable; strict fold ordering comes from `seq`, never from the id.
12
+ */
13
+ /** Mint a ULID. `now` is exposed so a caller can pin time in a test. */
14
+ declare function recordUlid(now?: number): string;
15
+
16
+ export { recordUlid };
@@ -0,0 +1,35 @@
1
+ import {
2
+ RECORD_KEY_SENTINEL,
3
+ RECORD_PERIOD_SENTINEL,
4
+ RECORD_REVIEW_STATES,
5
+ canonicalRecordJson,
6
+ defaultRecordMaterialDifference,
7
+ defaultRecordPeriodScope,
8
+ detectRecordConflict,
9
+ foldRecordEntries,
10
+ recordEntryVisibleInPeriod,
11
+ recordFail,
12
+ recordKeyString,
13
+ recordOk,
14
+ recordUlid,
15
+ resolveWriteReviewState,
16
+ validateRecordValue
17
+ } from "../chunk-I24YIKHO.js";
18
+ export {
19
+ RECORD_KEY_SENTINEL,
20
+ RECORD_PERIOD_SENTINEL,
21
+ RECORD_REVIEW_STATES,
22
+ canonicalRecordJson,
23
+ defaultRecordMaterialDifference,
24
+ defaultRecordPeriodScope,
25
+ detectRecordConflict,
26
+ foldRecordEntries,
27
+ recordEntryVisibleInPeriod,
28
+ recordFail,
29
+ recordKeyString,
30
+ recordOk,
31
+ recordUlid,
32
+ resolveWriteReviewState,
33
+ validateRecordValue
34
+ };
35
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -4,10 +4,10 @@ import * as _tangle_network_agent_runtime_tool_loop from '@tangle-network/agent-
4
4
  import { ToolLoopMessage } from '@tangle-network/agent-runtime/tool-loop';
5
5
  export { RunToolLoopOptions as AppToolLoopOptions, ToolLoopAssistantToolCall as LoopAssistantToolCall, ToolLoopMessage as LoopMessage, ToolLoopCall as LoopToolCall, StreamToolLoopOptions as StreamAppToolLoopOptions, StreamToolLoopYield as StreamLoopYield, ToolLoopEvent, ToolLoopResult, ToolLoopStopReason, runToolLoop as runAppToolLoop, streamToolLoop as streamAppToolLoop } from '@tangle-network/agent-runtime/tool-loop';
6
6
  import { CertifiedProfile } from '@tangle-network/agent-runtime/intelligence';
7
- import { A as AppToolMcpServer } from '../mcp-BiKqnsJV.js';
7
+ import { A as AppToolMcpServer } from '../mcp-xxoZZfor.js';
8
8
  import '@tangle-network/agent-interface';
9
- import '../types-DbU-oO5h.js';
10
- import '../auth-DJjJBtYw.js';
9
+ import '../types-B25Mib1r.js';
10
+ import '../auth-BYtiazA4.js';
11
11
 
12
12
  /**
13
13
  * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.
@@ -2,8 +2,8 @@ import { Sandbox } from '@tangle-network/sandbox/core';
2
2
  import { SandboxInstance, ProvisionEvent, EgressPolicy, StorageConfig, ScopedTokenScope, TurnDriveResult, MintScopedTokenOptions } from '@tangle-network/sandbox';
3
3
  export { StorageConfig } from '@tangle-network/sandbox';
4
4
  import { ReasoningEffort, AgentProfileMcpServer, AgentProfileFileMount, AgentProfile } from '@tangle-network/agent-interface';
5
- import { T as ToolHeaderNames } from '../auth-DJjJBtYw.js';
6
- import { a as AppToolName, A as AppToolContext } from '../types-DbU-oO5h.js';
5
+ import { T as ToolHeaderNames } from '../auth-BYtiazA4.js';
6
+ import { a as AppToolName, A as AppToolContext } from '../types-B25Mib1r.js';
7
7
  import { Harness } from '../harness/index.js';
8
8
  import { a as TangleExecutionEnvironment } from '../model-CdCDfBA9.js';
9
9
  import { b as ProfileFingerprint, C as ComposeProfileBudget } from '../budget-BOucfcb_.js';
@@ -92,9 +92,10 @@ import {
92
92
  } from "../chunk-7V2I3JGZ.js";
93
93
  import "../chunk-TH7L265V.js";
94
94
  import "../chunk-LWSJK546.js";
95
- import "../chunk-ZSGTG6PK.js";
95
+ import "../chunk-P5PIAQVS.js";
96
96
  import "../chunk-KBJL6LIW.js";
97
- import "../chunk-YEFFHORB.js";
97
+ import "../chunk-TX6S7XXU.js";
98
+ import "../chunk-UGWQLQDS.js";
98
99
  import "../chunk-S5SRJJQG.js";
99
100
  import "../chunk-JML7WKWU.js";
100
101
  export {
@@ -1,11 +1,11 @@
1
1
  import { j as SequenceMediaKind, f as SequenceTimeline, k as TimelineInterval, b as SequenceStore } from '../store-B7LLlk9p.js';
2
2
  export { M as MIN_SEQUENCE_CLIP_FRAMES, N as NewSequenceClip, l as NewSequenceDecision, m as NewSequenceTrack, g as SequenceClip, a as SequenceClipMedia, n as SequenceClipPatch, o as SequenceDecision, d as SequenceExportFormat, h as SequenceExportRecord, p as SequenceExportStatus, q as SequenceFrameSnapshot, i as SequenceMeta, r as SequenceStatus, S as SequenceStoreScope, e as SequenceTrack, c as SequenceTrackKind, T as TimelineClipBounds, s as assertClipFitsSequence, t as chooseCaptionPlacement, u as clampClipDuration, v as clampClipStart, w as formatSeconds, x as formatTimecode, y as framesToSeconds, z as secondsToFrames, A as snapshotFrame, B as trackIntervals } from '../store-B7LLlk9p.js';
3
3
  export { A as AddCaptionOperation, C as CaptionTargetResolution, a as CreateTrackOperation, D as DeleteClipOperation, E as ExtendSequenceOperation, M as MoveClipOperation, P as PlaceClipOperation, Q as QueueExportOperation, S as SEQUENCE_OPERATION_TYPES, b as SequenceApplyResult, c as SequenceOperation, d as SequenceOperationContext, e as SequenceOperationType, f as SequencePlan, g as SetClipDisabledOperation, h as SetClipTextOperation, i as SplitClipOperation, T as TrimClipOperation, j as applySequenceOperation, k as applySequenceOperations, l as assertSequenceMediaUrl, m as captionTrackNameForLanguage, n as lastClipEndFrame, p as parseSequenceOperations, r as resolveCaptionPlacement, o as resolveCaptionTarget, q as resolvePlaceClipTrack, v as validateAddCaption, s as validateCreateTrack, t as validateDeleteClip, u as validateExtendSequence, w as validateMoveClip, x as validatePlaceClip, y as validateQueueExport, z as validateSequenceOperation, B as validateSequenceOperations, F as validateSetClipDisabled, G as validateSetClipText, H as validateSplitClip, I as validateTrimClip } from '../apply-6wlMOLf8.js';
4
- import { S as ScopedMcpServerEntryOptions, A as AppToolMcpServer } from '../mcp-BiKqnsJV.js';
4
+ import { S as ScopedMcpServerEntryOptions, A as AppToolMcpServer } from '../mcp-xxoZZfor.js';
5
5
  export { M as SEQUENCES_MCP_PROTOCOL_VERSIONS } from '../mcp-rpc-DYwPlYbZ.js';
6
6
  import '@tangle-network/agent-interface';
7
- import '../types-DbU-oO5h.js';
8
- import '../auth-DJjJBtYw.js';
7
+ import '../types-B25Mib1r.js';
8
+ import '../auth-BYtiazA4.js';
9
9
 
10
10
  /**
11
11
  * Pure interchange-format builders over `SequenceTimeline` — SRT, WebVTT,
@@ -13,7 +13,7 @@ import {
13
13
  } from "../chunk-BVKQKGRK.js";
14
14
  import {
15
15
  assertMediaUrl
16
- } from "../chunk-J25RST7G.js";
16
+ } from "../chunk-F7VH4G5C.js";
17
17
  import {
18
18
  MCP_PROTOCOL_VERSIONS,
19
19
  buildScopedMcpServerEntry,
@@ -1,3 +1,174 @@
1
+ /**
2
+ * Nav destinations, and the guard that proves every href the rail renders
3
+ * resolves to a route the product's router actually registered.
4
+ *
5
+ * A rail row's href is assembled from a base plus a relative path, and nothing
6
+ * downstream re-checks it: the sidebar renders a link, the click navigates, and
7
+ * the router answers 404. A unit test written against the nav builder alone
8
+ * cannot catch that — it asserts the href the builder produced, which is the
9
+ * same wrong string the user clicks.
10
+ *
11
+ * Two mechanisms, meant to be used together:
12
+ *
13
+ * 1. `NavDestination` makes the base a REQUIRED discriminant (`scope`). An
14
+ * optional `absolute?: boolean`-style flag has the opposite property:
15
+ * omitting it type-checks, and the destination silently resolves under the
16
+ * workspace prefix instead of the app-level one. A required literal union
17
+ * turns that omission into a compile error, and widening `TScope` demands a
18
+ * base for the new scope rather than defaulting to a wrong one.
19
+ * 2. `assertNavHrefsRegistered` matches every resolved href against the route
20
+ * table, so a destination the router never registered fails a test instead
21
+ * of a user's click. It reads the product's real route table, so it cannot
22
+ * agree with the builder's mistake the way a hand-maintained expected-href
23
+ * list does.
24
+ */
25
+ /** The bases a product routes rail rows under. `workspace` is the per-workspace
26
+ * prefix (`/app/ws_123`); `app` is the account-level one (`/app`), where
27
+ * singleton surfaces such as a shared terminal or billing live. */
28
+ type NavScope = 'workspace' | 'app';
29
+ /** A base path per scope. Widening `TScope` widens this record, so a product
30
+ * that adds a scope cannot compile until it supplies that scope's base. */
31
+ type NavScopeBases<TScope extends string = NavScope> = Readonly<Record<TScope, string>>;
32
+ /** One rail destination as the product declares it, before a base is applied. */
33
+ interface NavDestination<TScope extends string = NavScope> {
34
+ id: string;
35
+ /** Path relative to the base named by `scope`. `''` is the base itself.
36
+ * Must be empty or start with `/` — a bare `'vault'` would concatenate into
37
+ * `/app/ws_123vault`, so it is rejected rather than silently repaired. */
38
+ path: string;
39
+ /** Which base `path` resolves against. Required on purpose. */
40
+ scope: TScope;
41
+ }
42
+ /** A destination with its base applied. */
43
+ interface ResolvedNavDestination<TScope extends string = NavScope> {
44
+ id: string;
45
+ href: string;
46
+ scope: TScope;
47
+ }
48
+ /** Apply a destination's scope base to its path.
49
+ *
50
+ * Throws when the scope has no base configured — a product that assembles
51
+ * `bases` dynamically can defeat the type-level guarantee, and a missing base
52
+ * would otherwise produce `undefined/vault`. */
53
+ declare function resolveNavHref<TScope extends string>(destination: NavDestination<TScope>, bases: NavScopeBases<TScope>): string;
54
+ /** Apply the bases to every destination, preserving declaration order. */
55
+ declare function resolveNavDestinations<TScope extends string>(destinations: readonly NavDestination<TScope>[], bases: NavScopeBases<TScope>): ResolvedNavDestination<TScope>[];
56
+ interface ResolveScopedActiveNavIdOptions<TScope extends string = NavScope> {
57
+ pathname: string;
58
+ destinations: readonly NavDestination<TScope>[];
59
+ bases: NavScopeBases<TScope>;
60
+ /** Extra ABSOLUTE prefixes that light an existing row, e.g.
61
+ * `{ '/app/ws_1/agents': 'integrations' }`. Same longest-prefix contest. */
62
+ aliases?: Readonly<Record<string, string>>;
63
+ /** ABSOLUTE prefixes that deliberately highlight nothing, beating any shorter
64
+ * match. */
65
+ claimsNothing?: readonly string[];
66
+ }
67
+ /**
68
+ * The rail row to highlight, across scopes.
69
+ *
70
+ * `resolveActiveNavId` resolves rows against ONE base, so an app-level row can
71
+ * only be highlighted by a second, hand-rolled scan — the same split that lets
72
+ * an app-level destination render under the workspace base. This resolves the
73
+ * hrefs first and runs a single longest-prefix contest over absolute paths, so
74
+ * declaration order cannot change the answer and no scope needs its own pass.
75
+ *
76
+ * Prefixes in `aliases` / `claimsNothing` are absolute here, unlike
77
+ * `resolveActiveNavId`'s base-relative ones, because the contest itself is
78
+ * absolute.
79
+ */
80
+ declare function resolveScopedActiveNavId<TScope extends string>({ pathname, destinations, bases, aliases, claimsNothing, }: ResolveScopedActiveNavIdOptions<TScope>): string | undefined;
81
+ /**
82
+ * One entry of a registered route table. Structurally compatible with
83
+ * react-router's `RouteConfigEntry`, so a product passes its real `routes.ts`
84
+ * default export straight in — the point of the guard is that it reads the
85
+ * router's own truth rather than a second list that can agree with the bug.
86
+ */
87
+ interface RegisteredRoute {
88
+ /** Absent on a pathless layout route: its children inherit the parent path. */
89
+ path?: string;
90
+ index?: boolean;
91
+ children?: readonly RegisteredRoute[];
92
+ }
93
+ /** A route table entry is either a bare pattern string or a router config node. */
94
+ type NavRouteTable = readonly (string | RegisteredRoute)[];
95
+ /**
96
+ * Every path pattern the table registers, rooted and de-duplicated.
97
+ *
98
+ * Parent nodes contribute their own cumulative path as well as their children's:
99
+ * a router matches a parent route with an index child at the parent path, and a
100
+ * parent without one still matches with an empty outlet, so treating parents as
101
+ * unregistered would flag working hrefs.
102
+ */
103
+ declare function flattenRouteTable(table: NavRouteTable): string[];
104
+ /**
105
+ * A nav row as the guard needs to see it. Structurally satisfied by
106
+ * `SessionRailNavItem` / `SessionRailSubItem` and by sandbox-ui's
107
+ * `SidebarLayoutNavItem`, so the guard runs over the builder's real output
108
+ * rather than a re-declaration of it.
109
+ */
110
+ interface NavHrefItem {
111
+ id: string;
112
+ href: string;
113
+ subItems?: readonly NavHrefItem[];
114
+ }
115
+ type NavHrefProblemReason =
116
+ /** No registered pattern matches the resolved href. */
117
+ 'unregistered'
118
+ /** Empty, fragment-only, or not rooted at `/` — the row navigates nowhere
119
+ * predictable regardless of the route table. */
120
+ | 'not-a-path'
121
+ /** Leaves the router (scheme or protocol-relative) while `allowExternal` is
122
+ * off. */
123
+ | 'external';
124
+ interface NavHrefProblem {
125
+ id: string;
126
+ href: string;
127
+ reason: NavHrefProblemReason;
128
+ /** Registered patterns ending in the same segment. A destination resolved
129
+ * under the wrong base lands here as its correctly-based twin, which is what
130
+ * names the missing scope in the failure message. */
131
+ nearest: string[];
132
+ message: string;
133
+ }
134
+ interface NavHrefReport {
135
+ /** Hrefs examined, including nested sub-items. */
136
+ checked: number;
137
+ problems: NavHrefProblem[];
138
+ /** Off-router destinations accepted because `allowExternal` is on. */
139
+ external: string[];
140
+ /** The flattened route table the check ran against. */
141
+ patterns: string[];
142
+ }
143
+ interface NavHrefCheckOptions {
144
+ /** Hrefs to skip, compared after query/fragment removal. For a destination
145
+ * served outside this route table (a static asset, another worker). */
146
+ ignore?: readonly string[];
147
+ /** Absolute URLs / `mailto:` / `tel:` are reported under `external` instead
148
+ * of failing. Default true. */
149
+ allowExternal?: boolean;
150
+ /** Compare literal segments case-sensitively. Default true — a router that
151
+ * matches case-insensitively still renders a link the deploy's CDN or a
152
+ * case-sensitive origin may not. */
153
+ caseSensitive?: boolean;
154
+ }
155
+ /**
156
+ * Check every nav href against the product's route table.
157
+ *
158
+ * Pure — returns the full report so a caller can assert on parts of it. Use
159
+ * {@link assertNavHrefsRegistered} in tests; it turns the report into a failure
160
+ * that names the offending row, its resolved href, and the near-miss pattern.
161
+ */
162
+ declare function checkNavHrefs(items: readonly NavHrefItem[], routes: NavRouteTable, options?: NavHrefCheckOptions): NavHrefReport;
163
+ /**
164
+ * Fail unless every nav href resolves to a registered route.
165
+ *
166
+ * Throws on an empty item list or an empty route table as well: a guard that
167
+ * examined nothing reports safety it does not provide, and both are what a
168
+ * mis-wired import looks like.
169
+ */
170
+ declare function assertNavHrefsRegistered(items: readonly NavHrefItem[], routes: NavRouteTable, options?: NavHrefCheckOptions): void;
171
+
1
172
  /**
2
173
  * Session shell — the app-shell mechanism every agent product needs around the
3
174
  * chat surface: a list of past sessions in the rail, an entry point for a new
@@ -14,6 +185,7 @@
14
185
  * shape to the shell, and the product supplies routing through `hrefForSession`
15
186
  * rather than the shell knowing any URL.
16
187
  */
188
+
17
189
  /** One session as the shell needs to see it. Products map their own row
18
190
  * (thread / session / matter) onto this before handing it over. */
19
191
  interface SessionSummary {
@@ -290,4 +462,4 @@ declare function railCollapsedCookie(collapsed: boolean, { name, maxAge, path, s
290
462
  * so a shared toggle handler is safe to call during SSR. */
291
463
  declare function writeRailCollapsedCookie(collapsed: boolean, options?: RailCookieOptions): void;
292
464
 
293
- export { type ActiveSessionIdOptions, type BuildSessionNavItemOptions, type BuildSessionSubItemsOptions, type ComposeSidebarSessionsOptions, type ComposedSidebarSessions, DEFAULT_RAIL_COOKIE_NAME, type NavRouteDef, type RailCookieOptions, type RailPrefetch, type ResolveActiveNavIdOptions, type ResolveSessionUnreadOptions, type SessionPage, type SessionRailAction, type SessionRailNavItem, type SessionRailSubItem, type SessionRowActions, type SessionSort, type SessionSummary, UNTITLED_SESSION_LABEL, activeSessionIdFromPath, buildSessionNavItem, buildSessionSubItems, composeSidebarSessions, mergeSessionPages, railCollapsedCookie, readRailCollapsedCookie, resolveActiveNavId, resolveSessionUnread, sessionLabel, writeRailCollapsedCookie };
465
+ export { type ActiveSessionIdOptions, type BuildSessionNavItemOptions, type BuildSessionSubItemsOptions, type ComposeSidebarSessionsOptions, type ComposedSidebarSessions, DEFAULT_RAIL_COOKIE_NAME, type NavDestination, type NavHrefCheckOptions, type NavHrefItem, type NavHrefProblem, type NavHrefProblemReason, type NavHrefReport, type NavRouteDef, type NavRouteTable, type NavScope, type NavScopeBases, type RailCookieOptions, type RailPrefetch, type RegisteredRoute, type ResolveActiveNavIdOptions, type ResolveScopedActiveNavIdOptions, type ResolveSessionUnreadOptions, type ResolvedNavDestination, type SessionPage, type SessionRailAction, type SessionRailNavItem, type SessionRailSubItem, type SessionRowActions, type SessionSort, type SessionSummary, UNTITLED_SESSION_LABEL, activeSessionIdFromPath, assertNavHrefsRegistered, buildSessionNavItem, buildSessionSubItems, checkNavHrefs, composeSidebarSessions, flattenRouteTable, mergeSessionPages, railCollapsedCookie, readRailCollapsedCookie, resolveActiveNavId, resolveNavDestinations, resolveNavHref, resolveScopedActiveNavId, resolveSessionUnread, sessionLabel, writeRailCollapsedCookie };
@@ -2,28 +2,40 @@ import {
2
2
  DEFAULT_RAIL_COOKIE_NAME,
3
3
  UNTITLED_SESSION_LABEL,
4
4
  activeSessionIdFromPath,
5
+ assertNavHrefsRegistered,
5
6
  buildSessionNavItem,
6
7
  buildSessionSubItems,
8
+ checkNavHrefs,
7
9
  composeSidebarSessions,
10
+ flattenRouteTable,
8
11
  mergeSessionPages,
9
12
  railCollapsedCookie,
10
13
  readRailCollapsedCookie,
11
14
  resolveActiveNavId,
15
+ resolveNavDestinations,
16
+ resolveNavHref,
17
+ resolveScopedActiveNavId,
12
18
  resolveSessionUnread,
13
19
  sessionLabel,
14
20
  writeRailCollapsedCookie
15
- } from "../chunk-GINKOZFD.js";
21
+ } from "../chunk-PC2WYTK7.js";
16
22
  export {
17
23
  DEFAULT_RAIL_COOKIE_NAME,
18
24
  UNTITLED_SESSION_LABEL,
19
25
  activeSessionIdFromPath,
26
+ assertNavHrefsRegistered,
20
27
  buildSessionNavItem,
21
28
  buildSessionSubItems,
29
+ checkNavHrefs,
22
30
  composeSidebarSessions,
31
+ flattenRouteTable,
23
32
  mergeSessionPages,
24
33
  railCollapsedCookie,
25
34
  readRailCollapsedCookie,
26
35
  resolveActiveNavId,
36
+ resolveNavDestinations,
37
+ resolveNavHref,
38
+ resolveScopedActiveNavId,
27
39
  resolveSessionUnread,
28
40
  sessionLabel,
29
41
  writeRailCollapsedCookie
@@ -3,15 +3,6 @@ import {
3
3
  isInviteTokenShape,
4
4
  validateInviteToken
5
5
  } from "../chunk-DJ4VJIH5.js";
6
- import {
7
- INVITATION_EXPIRY_DAYS,
8
- generateInvitationToken,
9
- getInvitationExpiresAt,
10
- inviteUrlForToken,
11
- normalizeInvitationEmail,
12
- parseInvitationPermission,
13
- renderInvitationEmail
14
- } from "../chunk-2DRYTJHI.js";
15
6
  import {
16
7
  ASSIGNABLE_WORKSPACE_ROLES,
17
8
  ORGANIZATION_ROLES,
@@ -27,6 +18,15 @@ import {
27
18
  workspaceRoleToCollaborationAccess,
28
19
  workspaceRoleToSandboxRole
29
20
  } from "../chunk-6XIAPIW6.js";
21
+ import {
22
+ INVITATION_EXPIRY_DAYS,
23
+ generateInvitationToken,
24
+ getInvitationExpiresAt,
25
+ inviteUrlForToken,
26
+ normalizeInvitationEmail,
27
+ parseInvitationPermission,
28
+ renderInvitationEmail
29
+ } from "../chunk-2DRYTJHI.js";
30
30
  export {
31
31
  ASSIGNABLE_WORKSPACE_ROLES,
32
32
  INVITATION_EXPIRY_DAYS,
@@ -2,6 +2,9 @@ import {
2
2
  SeatLimitError
3
3
  } from "../chunk-MEUNTJL5.js";
4
4
  import "../chunk-DJ4VJIH5.js";
5
+ import {
6
+ hasWorkspaceRole
7
+ } from "../chunk-6XIAPIW6.js";
5
8
  import {
6
9
  generateInvitationToken,
7
10
  getInvitationExpiresAt,
@@ -9,9 +12,6 @@ import {
9
12
  normalizeInvitationEmail,
10
13
  parseInvitationPermission
11
14
  } from "../chunk-2DRYTJHI.js";
12
- import {
13
- hasWorkspaceRole
14
- } from "../chunk-6XIAPIW6.js";
15
15
 
16
16
  // src/teams/invitations-api.ts
17
17
  import { and, eq, lte, sql } from "drizzle-orm";
@@ -1,8 +1,8 @@
1
- import { T as ToolHeaderNames } from '../auth-DJjJBtYw.js';
2
- export { A as AuthenticateOptions, C as CapabilitySubject, D as DEFAULT_HEADER_NAMES, a as ToolAuthResult, b as authenticateToolRequest, r as readToolArgs } from '../auth-DJjJBtYw.js';
3
- import { e as AppToolTaxonomy, d as AppToolHandlers, b as AppToolDefinition, A as AppToolContext, c as AppToolProducedEvent, f as AppToolOutcome, a as AppToolName } from '../types-DbU-oO5h.js';
4
- export { g as APP_TOOL_NAMES, h as AddCitationArgs, i as AddCitationResult, B as BuildAppToolsOptions, O as OpenAIFunctionTool, R as RenderUiArgs, j as RenderUiResult, S as ScheduleFollowupArgs, k as ScheduleFollowupResult, l as SubmitProposalArgs, m as SubmitProposalResult, n as buildAppToolOpenAITools, o as customToolToOpenAI, p as defineAppTool, q as findCustomTool, r as isAppToolName } from '../types-DbU-oO5h.js';
5
- export { A as AppToolMcpServer, B as BuildHttpMcpServerOptions, a as BuildMcpServerOptions, D as DEFAULT_APP_TOOL_PATHS, S as ScopedMcpServerEntryOptions, b as buildAppToolMcpServer, c as buildHttpMcpServer, d as buildScopedMcpServerEntry, u as unresolvableSurfaceCredential } from '../mcp-BiKqnsJV.js';
1
+ import { T as ToolHeaderNames } from '../auth-BYtiazA4.js';
2
+ export { A as AuthenticateOptions, C as CapabilitySubject, D as DEFAULT_HEADER_NAMES, a as ToolAuthResult, b as authenticateToolRequest, r as readToolArgs } from '../auth-BYtiazA4.js';
3
+ import { e as AppToolTaxonomy, d as AppToolHandlers, b as AppToolDefinition, A as AppToolContext, c as AppToolProducedEvent, f as AppToolOutcome, a as AppToolName } from '../types-B25Mib1r.js';
4
+ export { g as APP_TOOL_NAMES, h as AddCitationArgs, i as AddCitationResult, B as BuildAppToolsOptions, O as OpenAIFunctionTool, R as RenderUiArgs, j as RenderUiResult, S as ScheduleFollowupArgs, k as ScheduleFollowupResult, l as SubmitProposalArgs, m as SubmitProposalResult, n as buildAppToolOpenAITools, o as customToolToOpenAI, p as defineAppTool, q as findCustomTool, r as isAppToolName } from '../types-B25Mib1r.js';
5
+ export { A as AppToolMcpServer, B as BuildHttpMcpServerOptions, a as BuildMcpServerOptions, D as DEFAULT_APP_TOOL_PATHS, S as ScopedMcpServerEntryOptions, b as buildAppToolMcpServer, c as buildHttpMcpServer, d as buildScopedMcpServerEntry, u as unresolvableSurfaceCredential } from '../mcp-xxoZZfor.js';
6
6
  export { C as CreateMcpToolHandlerOptions, M as MCP_PROTOCOL_VERSIONS, b as McpProtocolVersion, c as McpServerInfo, d as McpToolCallContent, a as McpToolDefinition, e as createMcpToolHandler } from '../mcp-rpc-DYwPlYbZ.js';
7
7
  import '@tangle-network/agent-interface';
8
8
 
@@ -9,7 +9,7 @@ import {
9
9
  restrictTaxonomy,
10
10
  verifyCapabilityToken,
11
11
  verifyExpiringCapabilityToken
12
- } from "../chunk-ZSGTG6PK.js";
12
+ } from "../chunk-P5PIAQVS.js";
13
13
  import {
14
14
  DEFAULT_APP_TOOL_PATHS,
15
15
  DEFAULT_HEADER_NAMES,
@@ -30,7 +30,8 @@ import {
30
30
  defineAppTool,
31
31
  findCustomTool,
32
32
  isAppToolName
33
- } from "../chunk-YEFFHORB.js";
33
+ } from "../chunk-TX6S7XXU.js";
34
+ import "../chunk-UGWQLQDS.js";
34
35
  import "../chunk-S5SRJJQG.js";
35
36
  export {
36
37
  APP_TOOL_NAMES,
@@ -116,6 +116,17 @@ interface BuildAppToolsOptions {
116
116
  /** Product-registered tools to advertise to the model alongside the four
117
117
  * built-ins (appended in order, after the built-ins). */
118
118
  customTools?: readonly AppToolDefinition[];
119
+ /**
120
+ * Teach the model the interactive page vocabulary (forms, inputs, sliders)
121
+ * by appending {@link import('../openui/index').OPENUI_INTERACTIVE_AUTHORING_GUIDE}
122
+ * to `render_ui`'s description.
123
+ *
124
+ * Off by default, and it must stay off until the product's renderer knows the
125
+ * input nodes AND the host passes an action handler — otherwise the agent
126
+ * authors forms the page silently drops. A `descriptions.render_ui` override
127
+ * replaces the default prose; the guide is still appended after it.
128
+ */
129
+ interactiveUi?: boolean;
119
130
  }
120
131
  /** Define the arguments required to submit a proposal including type, title, description, and approval status */
121
132
  interface SubmitProposalArgs {